import { useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import dayjs from 'dayjs'
import { Button, Card, Form, Select, Space, Typography } from 'antd'
import CareTable from '../../components/CareTable'
import { BarChartOutlined, SearchOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'
import { resourceApi } from '../../api/resources'

type SaleStatRow = {
  key: number
  label: string
  saleCount: number
  contractCount: number
  customerCount: number
  amount: number
  settleAmount: number
  _summary?: boolean
}

type SaleStatData = {
  year: number
  month?: number
  title: string
  rows: SaleStatRow[]
  totals?: SaleStatRow
}

const num = (v: unknown) => {
  const n = Number(v ?? 0)
  return Number.isFinite(n) ? n : 0
}
const cell = (v: unknown) => (num(v) === 0 ? '' : num(v).toLocaleString())
const money = (v: unknown) => (num(v) === 0 ? '' : num(v).toLocaleString())

export default function ReportSalePage() {
  const now = useMemo(() => dayjs(), [])
  const [form] = Form.useForm()
  const [filters, setFilters] = useState<Record<string, unknown>>({
    year: now.year(),
    month: now.month() + 1 })

  const companies = useQuery({
    queryKey: ['sale-stats-companies'],
    queryFn: () => resourceApi.list('companies', { size: 200 }) })

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

  const outOptions = useMemo(
    () => (companies.data?.items ?? [])
      .filter((c) => ['SHOP', 'OUT'].includes(String(c.type)))
      .map((c) => ({ value: Number(c.id), label: String(c.name) })),
    [companies.data],
  )

  const yearOptions = useMemo(() => {
    const years: number[] = []
    for (let y = now.year(); y >= now.year() - 5; y--) years.push(y)
    return years.map((y) => ({ value: y, label: `${y}년` }))
  }, [now])

  const monthOptions = useMemo(
    () => Array.from({ length: 12 }, (_, i) => ({ value: i + 1, label: `${i + 1}월` })),
    [],
  )

  const shiftMonth = (delta: number) => {
    const year = Number(form.getFieldValue('year') ?? now.year())
    const month = Number(form.getFieldValue('month') ?? now.month() + 1)
    const next = dayjs(`${year}-${String(month).padStart(2, '0')}-01`).add(delta, 'month')
    form.setFieldsValue({ year: next.year(), month: next.month() + 1 })
  }

  const onSearch = (values: Record<string, unknown>) => {
    setFilters({
      year: values.year,
      month: values.month,
      telecom: values.telecom,
      outcompanyId: values.outcompanyId })
  }

  const onReset = () => {
    const init = { year: now.year(), month: now.month() + 1, telecom: undefined, outcompanyId: undefined }
    form.setFieldsValue(init)
    setFilters({ year: init.year, month: init.month })
  }

  const dataSource = useMemo(() => {
    const list = query.data?.rows ?? []
    if (!list.length || !query.data?.totals) return list
    return [...list, { ...query.data.totals, key: -1, label: '합계', _summary: true }]
  }, [query.data])

  const columns = [
    {
      title: `${filters.year}년 ${filters.month}월`,
      dataIndex: 'label',
      width: 100,
      align: 'center' as const,
      render: (v: string) => (v === '합계' ? <b>{v}</b> : v) },
    { title: '판매건수', dataIndex: 'saleCount', width: 90, align: 'center' as const, render: cell },
    { title: '계약건수', dataIndex: 'contractCount', width: 90, align: 'center' as const, render: cell },
    { title: '고객수', dataIndex: 'customerCount', width: 80, align: 'center' as const, render: cell },
    { title: '매출금액', dataIndex: 'amount', width: 120, align: 'center' as const, render: money },
    { title: '정산금액', dataIndex: 'settleAmount', width: 120, align: 'center' as const, render: money },
  ]

  return (
    <div className="stock-page open-stat-page">
      <div className="stock-title">
        <div>
          <h2><BarChartOutlined style={{ marginRight: 8 }} />매출통계</h2>
          <p>판매·계약·고객 기준 매출 통계를 확인합니다.</p>
        </div>
        <Typography.Text type="secondary">* API: /reports/sale-stats</Typography.Text>
      </div>

      <Card className="stock-filter-card" size="small">
        <Form
          form={form}
          layout="inline"
          className="open-stat-filter"
          initialValues={{ year: now.year(), month: now.month() + 1 }}
          onFinish={onSearch}
        >
          <Button onClick={() => shiftMonth(-1)}>전월</Button>
          <Form.Item name="year"><Select className="w-110" options={yearOptions} /></Form.Item>
          <Form.Item name="month"><Select className="w-100" options={monthOptions} /></Form.Item>
          <Button onClick={() => shiftMonth(1)}>익월</Button>
          <Form.Item name="telecom">
            <Select allowClear placeholder="-통신사-" className="w-110" options={['SKT', 'KT', 'LGU+'].map((v) => ({ value: v, label: v }))} />
          </Form.Item>
          <Form.Item name="outcompanyId">
            <Select allowClear showSearch optionFilterProp="label" placeholder="-출고처-" className="w-130" options={outOptions} />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>검색</Button>
              <Button onClick={onReset}>초기화</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card className="stock-table-card" size="small">
        <CareTable
          size="small"
          bordered
          loading={query.isLoading}
          rowKey="key"
          dataSource={dataSource}
          columns={columns}
          pagination={false}
          scroll={{ x: 700 }}
          rowClassName={(row) => (row._summary ? 'open-stat-summary' : '')}
          locale={{ emptyText: query.isError ? '데이터를 불러오지 못했습니다.' : '등록되어 있는 자료가 없습니다.' }}
        />
      </Card>
    </div>
  )
}
