import { useEffect } from 'react';
import { Button, Card, Col, DatePicker, Form, Input, message, Row, Space } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import dayjs from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import CodeSelect from '@/components/common/CodeSelect';
import { agentApi, AgentSaveReq } from '@/api/agent';

export default function AgentForm() {
  const { id } = useParams<{ id: string }>();
  const isEdit = id && id !== 'new';
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const { data } = useQuery({
    queryKey: ['agent', 'detail', id],
    queryFn: () => agentApi.detail(Number(id)),
    enabled: !!isEdit,
  });

  useEffect(() => {
    if (data) {
      form.setFieldsValue({
        ...data,
        joinDate: data.joinDate ? dayjs(data.joinDate) : null,
      });
    }
  }, [data, form]);

  const onFinish = async (values: any) => {
    const req: AgentSaveReq = {
      ...values,
      joinDate: values.joinDate ? values.joinDate.format('YYYY-MM-DD') : undefined,
    };
    try {
      if (isEdit) {
        await agentApi.update(Number(id), req);
        message.success('수정 완료');
      } else {
        await agentApi.create(req);
        message.success('등록 완료');
      }
      navigate('/org/agents');
    } catch {
      // 인터셉터에서 처리
    }
  };

  return (
    <PageContainer title={isEdit ? '설계사 수정' : '설계사 등록'}>
      <Card>
        <Form form={form} layout="vertical" onFinish={onFinish}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="설계사명" name="agentName" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="사번" name="licenseNo">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="소속 ID" name="orgId" rules={[{ required: true }]}>
                <Input type="number" placeholder="조직 ID" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="직급 ID" name="gradeId" rules={[{ required: true }]}>
                <Input type="number" placeholder="직급 ID" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="전화번호" name="phone">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="이메일" name="email" rules={[{ type: 'email' }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="주민번호" name="residentNo" extra="저장 시 자동 암호화">
                <Input />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="은행" name="bankCode">
                <CodeSelect groupCode="BANK_CODE" />
              </Form.Item>
            </Col>
            <Col span={18}>
              <Form.Item label="계좌번호" name="accountNo" extra="저장 시 자동 암호화">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="입사일" name="joinDate">
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Space>
            <Button type="primary" htmlType="submit">{isEdit ? '수정' : '등록'}</Button>
            <Button onClick={() => navigate(-1)}>취소</Button>
          </Space>
        </Form>
      </Card>
    </PageContainer>
  );
}
