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

const CATEGORIES = ['인터넷', 'TV', '집전화', '렌탈', '정수기', '공기청정기', '비데', '홈IOT']
const options = (values: string[]) => values.map((value) => ({ value, label: value }))

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

  const detail = useQuery({
    queryKey: ['product-detail', editId],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<Record<string, unknown>>>(`${apiPrefix()}/products/${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>) => {
      const payload = {
        ...values,
        monthlyFee: values.monthlyFee ?? 0,
        price: values.price ?? 0 }
      if (editId) {
        const { data } = await client.put(`${apiPrefix()}/products/${editId}`, payload)
        return unwrap(data as ApiResponse)
      }
      const { data } = await client.post(`${apiPrefix()}/products`, payload)
      return unwrap(data as ApiResponse)
    },
    onSuccess: () => {
      message.success(editId ? '상품을 수정했습니다.' : '상품을 등록했습니다.')
      navigate('/care/product/list')
    },
    onError: (e: Error) => message.error(e.message) })

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

      <Form
        form={form}
        layout="horizontal"
        labelCol={{ flex: '100px' }}
        wrapperCol={{ flex: 1 }}
        initialValues={{ status: '판매중', category: '인터넷', telecom: 'KT' }}
        onFinish={(v) => save.mutate(v)}
      >
        <Card size="small" title="상품정보" style={{ marginBottom: 12 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="category" label="분류" rules={[{ required: true }]}>
                <Select options={options(CATEGORIES)} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="status" label="상태">
                <Select options={options(['판매중', '판매중지'])} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="name" label="상품명" rules={[{ required: true }]}>
                <Input />
              </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="plan" label="요금제/모델">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="monthlyFee" label="월정액">
                <InputNumber style={{ width: '100%' }} min={0} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="price" label="판매가">
                <InputNumber style={{ width: '100%' }} min={0} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="description" label="설명">
                <Input.TextArea rows={3} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="memo" label="메모">
                <Input.TextArea rows={2} />
              </Form.Item>
            </Col>
          </Row>
        </Card>

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