import { Button, Card, Dialog, Form, Input, List, NavBar, Toast } from 'antd-mobile';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import { authApi } from '@/api/auth';
import { useAuthStore } from '@/stores/authStore';

export default function Profile() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const clear = useAuthStore((s) => s.clear);
  const setProfile = useAuthStore((s) => s.setProfile);
  const [phoneOpen, setPhoneOpen] = useState(false);
  const [phoneInput, setPhoneInput] = useState('');
  const [pwOpen, setPwOpen] = useState(false);
  const [pwForm] = Form.useForm<{ oldPassword: string; newPassword: string; confirm: string }>();

  const { data: me, refetch } = useQuery({
    queryKey: ['mobile.me.profile'],
    queryFn: () => authApi.me(),
  });

  const submitPhone = async () => {
    try {
      await authApi.updateMyPhone(phoneInput.trim());
      Toast.show({ icon: 'success', content: '전화번호 저장 완료' });
      setPhoneOpen(false);
      await refetch();
      const fresh = await authApi.me().catch(() => null);
      if (fresh) setProfile(fresh);
    } catch {
      // interceptor 처리
    }
  };

  const submitPassword = async () => {
    try {
      const v = await pwForm.validateFields();
      if (v.newPassword !== v.confirm) {
        Toast.show({ icon: 'fail', content: '새 비밀번호 확인이 일치하지 않습니다' });
        return;
      }
      await authApi.changePassword(v.oldPassword, v.newPassword);
      Toast.show({ icon: 'success', content: '비밀번호 변경 완료' });
      setPwOpen(false);
      pwForm.resetFields();
    } catch {
      // 검증 실패 또는 서버 오류
    }
  };

  const onLogout = () => {
    Dialog.confirm({
      content: '로그아웃 하시겠습니까?',
      onConfirm: async () => {
        await authApi.logout();
        queryClient.clear();
        clear();
        navigate('/login', { replace: true });
      },
    });
  };

  return (
    <div className="page">
      <NavBar back={null}>내 정보</NavBar>
      <div style={{ padding: 12 }}>
        <Card title={me?.userName ?? me?.loginId ?? '-'}>
          <List>
            <List.Item extra={me?.loginId ?? '-'}>아이디</List.Item>
            <List.Item extra={me?.userName ?? '-'}>이름</List.Item>
            <List.Item extra={me?.email ?? '-'}>이메일</List.Item>
            <List.Item
              extra={me?.phone ?? <span style={{ color: '#bbb' }}>미등록</span>}
              clickable
              onClick={() => { setPhoneInput(me?.phone ?? ''); setPhoneOpen(true); }}
            >
              전화번호
            </List.Item>
            <List.Item extra={me?.agentName ?? <span style={{ color: '#bbb' }}>미연결</span>}>설계사</List.Item>
            <List.Item extra={me?.orgName ?? '-'}>소속</List.Item>
          </List>
        </Card>

        <Card style={{ marginTop: 12 }}>
          <List>
            <List.Item clickable onClick={() => setPwOpen(true)}>비밀번호 변경</List.Item>
            <List.Item clickable onClick={onLogout} style={{ color: '#ff3141' }}>로그아웃</List.Item>
          </List>
        </Card>

        <Dialog
          visible={phoneOpen}
          title="전화번호 등록"
          content={
            <div>
              <Input placeholder="010-1234-5678" value={phoneInput} onChange={setPhoneInput} autoFocus />
              <div style={{ marginTop: 8, fontSize: 12, color: '#999' }}>
                SMS 알림 발송에 사용됩니다.
              </div>
            </div>
          }
          actions={[
            [
              { key: 'cancel', text: '취소', onClick: () => setPhoneOpen(false) },
              { key: 'save', text: '저장', bold: true, onClick: submitPhone },
            ],
          ]}
        />

        <Dialog
          visible={pwOpen}
          title="비밀번호 변경"
          content={
            <Form form={pwForm} layout="vertical">
              <Form.Item name="oldPassword" label="현재 비밀번호" rules={[{ required: true, message: '필수' }]}>
                <Input type="password" />
              </Form.Item>
              <Form.Item name="newPassword" label="새 비밀번호" rules={[{ required: true, min: 8, message: '8자 이상' }]}>
                <Input type="password" />
              </Form.Item>
              <Form.Item name="confirm" label="새 비밀번호 확인" rules={[{ required: true, message: '필수' }]}>
                <Input type="password" />
              </Form.Item>
            </Form>
          }
          actions={[
            [
              { key: 'cancel', text: '취소', onClick: () => { setPwOpen(false); pwForm.resetFields(); } },
              { key: 'save', text: '변경', bold: true, onClick: submitPassword },
            ],
          ]}
        />

        <Button block style={{ marginTop: 16 }} onClick={onLogout}>로그아웃</Button>
      </div>
    </div>
  );
}
