import { useEffect } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { Button, Card, Col, Form, Input, Row, Select, message } from 'antd'
import { UnorderedListOutlined, UserOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'

const options = (values: string[]) => values.map((value) => ({ value, label: value }))

export default function CustomerWritePage() {
  const navigate = useNavigate()
  const [search] = useSearchParams()
  const editId = search.get('id') ? Number(search.get('id')) : null
  const [form] = Form.useForm()

  const detail = useQuery({
    queryKey: ['customer-detail', editId],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<Record<string, unknown>>>(`${apiPrefix()}/customers/${editId}`)
      return unwrap(data)
    },
    enabled: Boolean(editId) })

  useEffect(() => {
    if (detail.data) form.setFieldsValue(detail.data)
  }, [detail.data, form])

  const save = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      if (editId) {
        const { data } = await client.put(`${apiPrefix()}/customers/${editId}`, values)
        return unwrap(data as ApiResponse)
      }
      const { data } = await client.post(`${apiPrefix()}/customers`, values)
      return unwrap(data as ApiResponse)
    },
    onSuccess: () => {
      message.success(editId ? '고객을 수정했습니다.' : '고객을 등록했습니다.')
      navigate('/care/customer/list')
    },
    onError: (e: Error) => message.error(e.message) })

  return (
    <div className="home-write-page">
      <div className="stock-title">
        <div>
          <h2><UserOutlined style={{ marginRight: 8 }} />고객 {editId ? '수정' : '등록'}</h2>
          <p>고객 기본정보를 입력해주세요. ('필수' 표시는 필수항목입니다.)</p>
        </div>
        <Button icon={<UnorderedListOutlined />} onClick={() => navigate('/care/customer/list')}>
          목록
        </Button>
      </div>

      <Form
        form={form}
        layout="horizontal"
        labelCol={{ flex: '100px' }}
        wrapperCol={{ flex: 1 }}
        initialValues={{ status: '정상', telecom: 'KT' }}
        onFinish={(v) => save.mutate(v)}
      >
        <Card size="small" title="고객정보" style={{ marginBottom: 12 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="name" label="고객명" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="phone" label="연락처" rules={[{ required: true }]}>
                <Input placeholder="010-0000-0000" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="telecom" label="통신사">
                <Select options={options(['SKT', 'KT', 'LGU+'])} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="status" label="상태">
                <Select options={options(['정상', '휴면', '해지'])} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="employee" label="담당자">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="email" label="이메일">
                <Input />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="address" label="주소">
                <Input />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="memo" label="메모">
                <Input.TextArea rows={3} />
              </Form.Item>
            </Col>
          </Row>
        </Card>

        <div style={{ display: 'flex', gap: 8 }}>
          <Button type="primary" htmlType="submit" loading={save.isPending}>저장</Button>
          <Button onClick={() => navigate('/care/customer/list')}>목록</Button>
        </div>
      </Form>
    </div>
  )
}
