import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { Button, Card, Form, Input, Select } from 'antd'
import CareTable from '../../components/CareTable'
import { FileTextOutlined, PlusOutlined, ReloadOutlined, SearchOutlined, UserOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'

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

type Customer = Record<string, unknown> & { id: number }
type SearchResult = { total: number; list: Customer[] }

const initial = { page: 0, size: 15 } as Record<string, unknown>

export default function CustomerListPage() {
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const [filters, setFilters] = useState<Record<string, unknown>>(initial)

  const query = useQuery({
    queryKey: ['customers-list', filters],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<SearchResult>>(`${apiPrefix()}/customers`, { params: filters })
      return unwrap(data)
    } })

  const onSearch = (values: Record<string, unknown>) => {
    setFilters({ ...initial, ...values, page: 0, size: values.size ?? filters.size ?? 15 })
  }

  const reset = () => {
    form.resetFields()
    form.setFieldsValue({ size: 15 })
    setFilters(initial)
  }

  const columns = [
    { title: '고객명', dataIndex: 'name', width: 100, sorter: true },
    { title: '연락처', dataIndex: 'phone', width: 120 },
    { title: '통신사', dataIndex: 'telecom', width: 70 },
    { title: '주소', dataIndex: 'address', width: 200, ellipsis: true },
    { title: '상태', dataIndex: 'status', width: 80 },
    { title: '담당자', dataIndex: 'employee', width: 90 },
    { title: '등록일', dataIndex: 'createdDate', width: 100 },
    {
      title: '관리', width: 58, fixed: 'right' as const,
      render: (_: unknown, row: Customer) => (
        <Button
          size="small"
          type="text"
          icon={<FileTextOutlined style={{ color: '#1677ff' }} />}
          onClick={() => navigate(`/care/customer/write?id=${row.id}`)}
        />
      ) },
  ]

  return (
    <div className="stock-page home-sale-page">
      <div className="stock-title">
        <div>
          <h2><UserOutlined style={{ marginRight: 8 }} />고객목록</h2>
          <p>홈상품·계약 고객 정보를 조회하고 관리합니다.</p>
        </div>
        <Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('/care/customer/write')}>고객 등록</Button>
      </div>

      <Card className="stock-filter-card" size="small">
        <Form form={form} layout="inline" className="home-filter" initialValues={{ size: 15 }} onFinish={onSearch}>
          <div className="stock-filter-row">
            <Form.Item name="status"><Select allowClear placeholder="-상태-" className="w-110" options={options(['정상', '휴면', '해지'])} /></Form.Item>
            <Form.Item name="telecom"><Select allowClear placeholder="-통신사-" className="w-110" options={options(['SKT', 'KT', 'LGU+'])} /></Form.Item>
            <Form.Item name="name"><Input placeholder="고객명" className="w-130" allowClear /></Form.Item>
            <Form.Item name="phone"><Input placeholder="연락처" className="w-130" allowClear /></Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>검색</Button>
            <Button icon={<ReloadOutlined />} onClick={reset}>초기화</Button>
            <Form.Item name="size" className="sheet-size">
              <Select
                className="w-150"
                options={[15, 30, 50, 100].map((n) => ({ value: n, label: `목록 ${n}개씩 보기` }))}
                onChange={(size) => { form.setFieldValue('size', size); setFilters((v) => ({ ...v, size, page: 0 })) }}
              />
            </Form.Item>
          </div>
        </Form>
      </Card>

      <Card className="stock-table-card" size="small">
        <CareTable
          rowKey="id"
          size="small"
          loading={query.isLoading}
          dataSource={query.data?.list}
          columns={columns}
          scroll={{ x: 900 }}
          pagination={{
            current: Number(filters.page) + 1,
            pageSize: Number(filters.size),
            total: query.data?.total,
            showSizeChanger: false,
            showTotal: (total) => `총 ${total}건`,
            onChange: (page) => setFilters((v) => ({ ...v, page: page - 1 })) }}
          locale={{ emptyText: query.isError ? '데이터를 불러오지 못했습니다.' : '등록된 고객이 없습니다.' }}
        />
      </Card>
    </div>
  )
}
