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

const { RangePicker } = DatePicker
const tabs = [
  ['ALL', '전체'],
  ['반납', '반납'],
  ['미반납', '미반납'],
] as const
const searchTypes = ['개통번호(뒷4자리)', '고객명', '모델명', '일련번호']
const options = (values: string[]) => values.map((value) => ({ value, label: value }))
const money = (v: unknown) => (v == null || v === '' ? '-' : Number(v).toLocaleString())

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

const initial = { page: 0, size: 15, tab: 'ALL', searchType: '개통번호(뒷4자리)' } as Record<string, unknown>

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

  const companies = useQuery({ queryKey: ['return-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: ['return-search', filters],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<ReturnSearch>>(`${apiPrefix()}/returns/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,
      searchType: values.searchType || '개통번호(뒷4자리)' })
  }

  const reset = () => {
    form.resetFields()
    form.setFieldsValue({ searchType: '개통번호(뒷4자리)', size: 15 })
    setFilters(initial)
  }

  const clearDates = () => form.setFieldValue('dates', undefined)

  const download = async () => {
    try {
      const { data } = await client.get(`${apiPrefix()}/returns/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: '개통일', dataIndex: 'opendate', width: 110 },
    { title: '출고처', dataIndex: 'outcompanyName', width: 130, ellipsis: true },
    { title: '고객명', dataIndex: 'customerName', width: 90 },
    { title: '개통번호', dataIndex: 'openphone', width: 130 },
    {
      title: '구분',
      dataIndex: 'returnStatus',
      width: 80,
      render: (v: string) => (
        <span className={v === '미반납' ? 'return-status-pending' : 'return-status-done'}>{v || '미반납'}</span>
      ) },
    { title: '모델명', dataIndex: 'model', width: 130, ellipsis: true },
    { title: '일련번호', dataIndex: 'serial', width: 120, ellipsis: true },
    { title: '차감금액', dataIndex: 'deductAmount', width: 100, align: 'right' as const, render: money },
  ]

  return (
    <div className="stock-page return-page">
      <div className="stock-title">
        <div>
          <h2><MobileOutlined style={{ marginRight: 8 }} />반납단말기</h2>
          <p>반납단말기에 등록된 내역을 모두 확인하실 수 있습니다.</p>
        </div>
      </div>

      <Card className="stock-filter-card" size="small">
        <Form
          form={form}
          layout="inline"
          className="return-filter"
          initialValues={{ searchType: '개통번호(뒷4자리)', 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>
              <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={clearDates} />
            <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="outcompanyName">
              <Input placeholder="출고처" className="w-130" allowClear />
            </Form.Item>
            <Form.Item name="searchType">
              <Select className="w-150" options={searchTypes.map((v) => ({ value: v, label: v }))} />
            </Form.Item>
            <Form.Item name="keyword">
              <Input className="w-130" allowClear />
            </Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>검색</Button>
            <Button icon={<ReloadOutlined />} onClick={reset}>초기화</Button>
          </div>
        </Form>
      </Card>

      <Card className="stock-table-card" size="small">
        <div className="stock-table-actions return-table-actions">
          <Tabs
            activeKey={String(filters.tab)}
            onChange={(tab) => setFilters((v) => ({ ...v, tab, page: 0 }))}
            items={tabs.map(([key, label]) => ({
              key,
              label: `${label} ${query.data?.counts?.[key] ?? 0}` }))}
          />
          <Space>
            <Select
              className="w-150"
              value={Number(filters.size)}
              options={[15, 30, 50, 100].map((n) => ({ value: n, label: `목록 ${n}개씩 보기` }))}
              onChange={(size) => setFilters((v) => ({ ...v, size, page: 0 }))}
            />
            <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: 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 })) }}
        />
      </Card>
    </div>
  )
}
