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

const { RangePicker } = DatePicker
const tabs = [
  ['ALL', '전체'], ['신규', '신규'], ['번호이동', '번호이동'], ['보상', '보상'],
  ['기변', '기변'], ['메이징', '메이징'], ['가개통', '가개통'], ['선불개통', '선불개통'],
] as const
const options = (values: string[]) => values.map((value) => ({ value, label: value }))
const money = (v: unknown) => (v == null || v === '' ? '-' : Number(v).toLocaleString())
const initial = { page: 0, size: 15, tab: 'ALL' } as Record<string, unknown>

export default function OpenManagePage() {
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const [filters, setFilters] = useState<Record<string, unknown>>(initial)
  const companies = useQuery({ queryKey: ['open-companies'], queryFn: () => resourceApi.list('companies', { size: 100 }) })
  const query = useQuery({ queryKey: ['open-search', filters], queryFn: () => openApi.search(filters) })
  const inOptions = useMemo(() => (companies.data?.items ?? []).filter((c) => String(c.type) === 'IN').map((c) => ({ value: c.id, label: String(c.name) })), [companies.data])

  const search = (values: Record<string, unknown>) => {
    const dates = values.dates as [dayjs.Dayjs, dayjs.Dayjs] | undefined
    const next: Record<string, unknown> = {
      ...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 }
    delete next.dates
    setFilters(next)
  }
  const reset = () => { form.resetFields(); setFilters(initial) }
  const download = async () => {
    try {
      const { data } = await client.get(`${apiPrefix()}/opens/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: 'opendate', width: 96, sorter: true },
    { title: '통신사', dataIndex: 'telecom', width: 72, sorter: true },
    { title: '출고처', dataIndex: 'outcompanyName', width: 110, ellipsis: true, sorter: true },
    { title: '고객명', dataIndex: 'name', width: 90 },
    { title: '구분', dataIndex: 'gubun', width: 64 },
    { title: '종류', dataIndex: 'openhow', width: 80 },
    { title: '개통번호', dataIndex: 'openphone', width: 120 },
    { title: '상태', dataIndex: 'openStatus', width: 64 },
    { title: '모델명', dataIndex: 'pmodel', width: 130, ellipsis: true, sorter: true },
    { title: '일련번호', dataIndex: 'pserial', width: 120, ellipsis: true },
    { title: '입고처', dataIndex: 'incompanyName', width: 110, ellipsis: true },
    { title: '정산', dataIndex: 'sellprice', width: 90, align: 'right' as const, sorter: true, render: (v: unknown) => <span className="open-settle">{money(v)}</span> },
    { title: '차감', dataIndex: 'declprice1', width: 80, align: 'right' as const, render: money },
    { title: '마진', dataIndex: 'dealermargin1', width: 80, align: 'right' as const, render: money },
    { title: '관리', width: 58, fixed: 'right' as const, render: (_: unknown, row: OpenRecord) => (
      <Button size="small" type="text" icon={<FileTextOutlined style={{ color: '#1677ff' }} />} onClick={() => navigate(`/care/open/open-form-write1?id=${row.id}`)} />
    ) },
  ]

  return <div className="stock-page open-page">
    <div className="stock-title">
      <div>
        <h2>개통관리</h2>
        <p>모바일 개통과 관련된 모든 업무를 관리하실 수 있습니다.</p>
      </div>
      <Space wrap>
        <Button type="primary" icon={<EditOutlined />} onClick={() => navigate('/care/open/open-form-write1')}>할부 개통</Button>
        <Button type="primary" icon={<EditOutlined />} onClick={() => navigate('/care/open/open-form-write2')}>현금 개통</Button>
        <Button icon={<EditOutlined />} onClick={() => navigate('/care/open/open-form-write3')}>유심 개통</Button>
      </Space>
    </div>

    <Card className="stock-filter-card" size="small">
      <Form form={form} layout="inline" onFinish={search}>
        <div className="stock-filter-row">
          <Form.Item name="dates"><RangePicker className="w-230" /></Form.Item>
          <Space.Compact>
            <Button onClick={() => form.setFieldValue('dates', [dayjs(), dayjs()])}>오늘</Button>
            <Button onClick={() => form.setFieldValue('dates', [dayjs().subtract(6, 'day'), dayjs()])}>1주일</Button>
            <Button onClick={() => form.setFieldValue('dates', [dayjs().startOf('month'), dayjs().endOf('month')])}>당월</Button>
            <Button onClick={() => form.setFieldValue('dates', [dayjs().subtract(1, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month')])}>전월</Button>
            <Button onClick={() => form.setFieldValue('dates', [dayjs().subtract(2, 'month').startOf('month'), dayjs().subtract(2, 'month').endOf('month')])}>전전월</Button>
          </Space.Compact>
          <Button icon={<ReloadOutlined />} onClick={() => form.setFieldValue('dates', undefined)} />
          <Button onClick={() => form.getFieldInstance('dates')?.focus?.()}>날짜설정</Button>
        </div>
        <div className="stock-filter-row">
          <Form.Item name="gubun"><Select allowClear placeholder="-구분-" className="w-110" options={options(['할부', '현금', '유심'])} /></Form.Item>
          <Form.Item name="history"><Select allowClear placeholder="-이력-" className="w-110" options={options(['OPEN', 'PENDING', 'CANCEL'])} /></Form.Item>
          <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" /></Form.Item>
        </div>
        <div className="stock-filter-row">
          <Form.Item name="salesperson"><Select allowClear placeholder="-영업사원-" className="w-120" options={options(['김영업', '이영업'])} /></Form.Item>
          <Form.Item name="employee"><Select allowClear placeholder="-직원-" className="w-110" options={options(['demo'])} /></Form.Item>
          <Form.Item name="openhow"><Select allowClear placeholder="-종류-" className="w-120" options={options(['신규', '번호이동', '보상', '기변', '메이징', '가개통', '선불개통'])} /></Form.Item>
          <Form.Item name="openStatus"><Select allowClear placeholder="-상태-" className="w-110" options={options(['정상', '취소', '보류'])} /></Form.Item>
          <Form.Item name="model"><Input placeholder="모델명" className="w-130" /></Form.Item>
          <Form.Item name="phoneTail"><Input placeholder="개통번호(뒷4자리)" className="w-150" maxLength={4} /></Form.Item>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>검색</Button>
          <Button onClick={reset}>초기화</Button>
          <Form.Item name="size" initialValue={15} className="open-size-item"><Select className="w-130" options={[15, 30, 50, 100].map((v) => ({ value: v, label: `목록 ${v}개씩 보기` }))} /></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={tabs.map(([key, label]) => ({
            key,
            label: key === 'ALL' ? `${label} ${query.data?.counts?.[key] ?? 0}` : `${label} ${query.data?.counts?.[key] ?? 0}` }))}
        />
        <Space>
          <Button type="link">엑셀설정</Button>
          <Button type="link" icon={<DownloadOutlined />} onClick={download}>엑셀다운로드</Button>
        </Space>
      </div>
      <CareTable
        rowKey="id"
        size="small"
        loading={query.isLoading}
        dataSource={query.data?.list}
        columns={columns}
        scroll={{ x: 1700 }}
        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>
}
