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

const { RangePicker } = DatePicker
const options = (values: string[]) => values.map((value) => ({ value, label: value }))
const money = (v: unknown) => (v == null || v === '' ? '-' : Number(v).toLocaleString())

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

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

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

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

  const setPreset = (from: Dayjs, to: Dayjs) => form.setFieldsValue({ dates: [from, to] })

  const onSearch = (values: Record<string, unknown>) => {
    const dates = values.dates as [Dayjs, Dayjs] | undefined
    setFilters({
      ...initial,
      ...values,
      dateFrom: dates?.[0]?.format('YYYY-MM-DD'),
      dateTo: dates?.[1]?.format('YYYY-MM-DD'),
      page: 0,
      size: values.size ?? filters.size ?? 15 })
  }

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

  const columns = [
    { title: '계약일', dataIndex: 'contractDate', width: 100, sorter: true },
    { title: '상태', dataIndex: 'status', width: 80 },
    { title: '고객명', dataIndex: 'customerName', width: 100, sorter: true },
    { title: '연락처', dataIndex: 'phone', width: 120 },
    { title: '상품', dataIndex: 'productName', width: 140, ellipsis: true },
    { title: '통신사', dataIndex: 'telecom', width: 70 },
    { title: '계약금액', dataIndex: 'amount', width: 110, align: 'right' as const, render: money },
    { title: '월정액', dataIndex: 'monthlyFee', width: 100, align: 'right' as const, render: money },
    { title: '담당자', dataIndex: 'employee', width: 90 },
    {
      title: '관리', width: 58, fixed: 'right' as const,
      render: (_: unknown, row: Contract) => (
        <Button
          size="small"
          type="text"
          icon={<FileTextOutlined style={{ color: '#1677ff' }} />}
          onClick={() => navigate(`/care/contract/write?id=${row.id}`)}
        />
      ) },
  ]

  return (
    <div className="stock-page home-sale-page">
      <div className="stock-title">
        <div>
          <h2><SolutionOutlined style={{ marginRight: 8 }} />계약목록</h2>
          <p>홈상품·렌탈 등 계약 내역을 조회하고 관리합니다.</p>
        </div>
        <Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('/care/contract/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="dates">
              <RangePicker className="w-230" placeholder={['YYYY-MM-DD', 'YYYY-MM-DD']} />
            </Form.Item>
            <Space.Compact className="sheet-presets">
              <Button onClick={() => setPreset(dayjs(), dayjs())}>오늘</Button>
              <Button onClick={() => setPreset(dayjs().subtract(6, 'day'), dayjs())}>1주일</Button>
              <Button onClick={() => setPreset(dayjs().startOf('month'), dayjs().endOf('month'))}>당월</Button>
              <Button onClick={() => setPreset(dayjs().subtract(1, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month'))}>전월</Button>
            </Space.Compact>
            <Button className="sheet-clear" icon={<CloseOutlined />} onClick={() => form.setFieldValue('dates', undefined)} />
          </div>
          <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="customerName"><Input placeholder="고객명" className="w-130" allowClear /></Form.Item>
            <Form.Item name="productName"><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: 1100 }}
          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 ? '데이터를 불러오지 못했습니다.' : '등록된 계약이 없습니다.' }}
          onChange={(_, __, sorter) => {
            const order = Array.isArray(sorter) ? sorter[0] : sorter
            if (order?.field) setFilters((v) => ({ ...v, sort: `${String(order.field)},${order.order === 'ascend' ? 'asc' : 'desc'}` }))
          }}
        />
      </Card>
    </div>
  )
}
