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

const CATEGORIES = ['인터넷', 'TV', '집전화', '렌탈', '정수기', '공기청정기', '비데', '홈IOT'] as const
const categoryFromPath: Record<string, string> = {
  '/care/product/internet': '인터넷',
  '/care/product/tv': 'TV',
  '/care/product/phone': '집전화',
  '/care/product/rental': '렌탈',
  '/care/product/water': '정수기',
  '/care/product/air': '공기청정기',
  '/care/product/bidet': '비데',
  '/care/product/iot': '홈IOT' }

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

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

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

export default function ProductListPage() {
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const location = useLocation()
  const pathCategory = categoryFromPath[location.pathname]
  const [filters, setFilters] = useState<Record<string, unknown>>({
    ...initial,
    category: pathCategory ?? 'ALL' })

  useEffect(() => {
    setFilters((v) => ({ ...v, category: pathCategory ?? 'ALL', page: 0 }))
  }, [pathCategory])

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

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

  const reset = () => {
    form.resetFields()
    form.setFieldsValue({ size: 15 })
    setFilters({ ...initial, category: pathCategory ?? 'ALL' })
  }

  const columns = [
    { title: '분류', dataIndex: 'category', width: 100 },
    { title: '상품명', dataIndex: 'name', width: 180, ellipsis: true, sorter: true },
    { title: '통신사', dataIndex: 'telecom', width: 70 },
    { title: '요금제/모델', dataIndex: 'plan', width: 140, ellipsis: true },
    { title: '월정액', dataIndex: 'monthlyFee', width: 100, align: 'right' as const, render: money },
    { title: '판매가', dataIndex: 'price', width: 100, align: 'right' as const, render: money },
    { title: '상태', dataIndex: 'status', width: 80 },
    {
      title: '관리', width: 58, fixed: 'right' as const,
      render: (_: unknown, row: Product) => (
        <Button
          size="small"
          type="text"
          icon={<FileTextOutlined style={{ color: '#1677ff' }} />}
          onClick={() => navigate(`/care/product/write?id=${row.id}`)}
        />
      ) },
  ]

  return (
    <div className="stock-page home-sale-page">
      <div className="stock-title">
        <div>
          <h2><ShoppingOutlined style={{ marginRight: 8 }} />상품목록</h2>
          <p>인터넷·TV·렌탈·가전 등 홈상품을 관리합니다.</p>
        </div>
        <Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('/care/product/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="telecom"><Select allowClear placeholder="-통신사-" className="w-110" options={options(['SKT', 'KT', 'LGU+'])} /></Form.Item>
            <Form.Item name="status"><Select allowClear placeholder="-상태-" className="w-110" options={options(['판매중', '판매중지'])} /></Form.Item>
            <Form.Item name="name"><Input placeholder="상품명" className="w-150" 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">
        <div className="stock-table-actions">
          <Tabs
            activeKey={String(filters.category)}
            onChange={(category) => setFilters((v) => ({ ...v, category, page: 0 }))}
            items={[
              { key: 'ALL', label: `전체 ${query.data?.counts?.ALL ?? query.data?.total ?? 0}` },
              ...CATEGORIES.map((key) => ({
                key,
                label: `${key} ${query.data?.counts?.[key] ?? 0}` })),
            ]}
          />
        </div>
        <CareTable
          rowKey="id"
          size="small"
          loading={query.isLoading}
          dataSource={query.data?.list}
          columns={columns}
          scroll={{ x: 1000 }}
          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>
  )
}
