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

const { RangePicker } = DatePicker
const productTabs = [
  'ALL', '인터넷', 'TV', '집전화', '인터넷전화', '신용카드', '홈IOT', '동반', '기타', '후결합', '재약정', '소호', '원스톱', '렌탈',
] as const
const tabLabel: Record<string, string> = {
  ALL: '전체', 인터넷: '인터넷', TV: 'TV', 집전화: '집전화', 인터넷전화: '인터넷전화', 신용카드: '신용카드',
  홈IOT: '홈IOT', 동반: '동판', 기타: '기타', 후결합: '후결합', 재약정: '재약정', 소호: '소호', 원스톱: '원스톱', 렌탈: '렌탈' }
const options = (values: string[]) => values.map((value) => ({ value, label: value }))
const money = (v: unknown) => (v == null || v === '' ? '-' : Number(v).toLocaleString())

type HomeSale = Record<string, unknown> & { id: number; status?: string; settleAmount?: number }
type HomeSearch = { total: number; list: HomeSale[]; counts: Record<string, number> }

const initial = { page: 0, size: 15, tab: 'ALL', dateBasis: '설치일기준' } as Record<string, unknown>

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

  const companies = useQuery({ queryKey: ['homesale-companies'], queryFn: () => resourceApi.list('companies', { size: 200 }) })
  const inOptions = useMemo(
    () => (companies.data?.items ?? []).filter((c) => String(c.type) === 'IN').map((c) => ({ value: c.id, label: String(c.name) })),
    [companies.data],
  )

  const query = useQuery({
    queryKey: ['homesale-search', filters],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<HomeSearch>>(`${apiPrefix()}/homesales/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,
      tab: filters.tab })
  }

  const reset = () => {
    form.resetFields()
    form.setFieldsValue({ dateBasis: '설치일기준', size: 15 })
    setFilters(initial)
  }

  const download = async () => {
    try {
      const { data } = await client.get(`${apiPrefix()}/homesales/export`, { params: filters, responseType: 'blob' })
      const url = URL.createObjectURL(data)
      const a = document.createElement('a')
      a.href = url
      a.download = '홈상품판매.csv'
      a.click()
      URL.revokeObjectURL(url)
    } catch {
      message.error('엑셀 다운로드에 실패했습니다.')
    }
  }

  const columns = [
    { title: <Checkbox />, width: 42, render: () => <Checkbox /> },
    { title: '설치일', dataIndex: 'installDate', width: 100, sorter: true },
    { title: '출고처', dataIndex: 'outcompanyName', width: 110, ellipsis: true, sorter: true },
    {
      title: '상태', dataIndex: 'status', width: 70,
      render: (v: string) => <span className={v === '대기' ? 'home-status-wait' : 'home-status-done'}>{v}</span> },
    { title: '입고처', dataIndex: 'incompanyName', width: 100, ellipsis: true },
    { title: '통신사', dataIndex: 'telecom', width: 70, sorter: true },
    { title: '고객명', dataIndex: 'customerName', width: 90, sorter: true },
    { title: '휴대폰', dataIndex: 'phone', width: 120 },
    { title: '가입상품', dataIndex: 'products', width: 140, ellipsis: true },
    {
      title: '정산', dataIndex: 'settleAmount', width: 100, align: 'right' as const, sorter: true,
      render: (v: unknown) => {
        const n = Number(v ?? 0)
        return <span className={n < 0 ? 'home-settle-neg' : ''}>{money(v)}</span>
      } },
    { title: '마진', dataIndex: 'margin', width: 90, align: 'right' as const, render: money },
    { title: '접수일', dataIndex: 'receiptDate', width: 100, sorter: true },
    {
      title: '관리', width: 58, fixed: 'right' as const,
      render: (_: unknown, row: HomeSale) => (
        <Button size="small" type="text" icon={<FileTextOutlined style={{ color: '#1677ff' }} />} onClick={() => navigate(`/care/open/home-write?id=${row.id}`)} />
      ) },
  ]

  return (
    <div className="stock-page home-sale-page">
      <div className="stock-title">
        <div>
          <h2><HomeOutlined style={{ marginRight: 8 }} />홈상품판매</h2>
          <p>인터넷, TV, 전화 등 홈상품판매와 관련된 모든 업무를 관리하실 수 있습니다.</p>
        </div>
        <Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('/care/open/home-write')}>홈상품판매 등록</Button>
      </div>

      <Card className="stock-filter-card" size="small">
        <Form form={form} layout="inline" className="home-filter" initialValues={{ dateBasis: '설치일기준', size: 15 }} onFinish={onSearch}>
          <div className="stock-filter-row">
            <Form.Item name="dateBasis">
              <Select className="w-120" options={options(['설치일기준', '접수일기준'])} />
            </Form.Item>
            <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>
              <Button onClick={() => setPreset(dayjs().subtract(2, 'month').startOf('month'), dayjs().subtract(2, 'month').endOf('month'))}>전전월</Button>
            </Space.Compact>
            <Button className="sheet-clear" icon={<CloseOutlined />} onClick={() => form.setFieldValue('dates', undefined)} />
            <Button onClick={() => form.getFieldInstance('dates')?.focus?.()}>날짜설정</Button>
          </div>
          <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="incompanyId"><Select allowClear placeholder="-입고처-" className="w-150" options={inOptions} /></Form.Item>
            <Form.Item name="outCategory"><Select allowClear placeholder="-출고분류-" className="w-120" options={options(['판매점', '도매'])} /></Form.Item>
            <Form.Item name="outcompanyName"><Input placeholder="출고처" className="w-130" allowClear /></Form.Item>
            <Form.Item name="employee"><Select allowClear placeholder="-직원-" className="w-110" options={options(['demo'])} /></Form.Item>
          </div>
          <div className="stock-filter-row">
            <Form.Item name="status"><Select allowClear placeholder="-상태-" className="w-110" options={options(['대기', '완료'])} /></Form.Item>
            <Form.Item name="customerName"><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">
        <div className="stock-table-actions">
          <Tabs
            activeKey={String(filters.tab)}
            onChange={(tab) => setFilters((v) => ({ ...v, tab, page: 0 }))}
            items={productTabs.map((key) => ({
              key,
              label: `${tabLabel[key]} ${query.data?.counts?.[key] ?? 0}` }))}
          />
          <Button type="link" icon={<DownloadOutlined />} onClick={download}>엑셀다운로드</Button>
        </div>
        <CareTable
          rowKey="id"
          size="small"
          loading={query.isLoading}
          dataSource={query.data?.list}
          columns={columns}
          scroll={{ x: 1400 }}
          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 })) }}
          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>
  )
}
