import { useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import dayjs, { type Dayjs } from 'dayjs'
import { Table, Button, Card, Empty } from 'antd'
import CareTable from '../../components/CareTable'
import { BarChartOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'
import { money } from './homesShared'

type StatRow = {
  key?: number
  label?: string
  day?: number
  month?: number
  count?: number
  policySum?: number
  settleAmount?: number
  margin?: number
}

type KindStatData = {
  mode?: 'daily' | 'monthly'
  year?: number
  month?: number
  title?: string
  rows?: StatRow[]
  totals?: StatRow
}

const num = (v?: number) => Number(v ?? 0)
const cell = (v?: number) => (num(v) === 0 ? '' : money(v))
const countCell = (v?: number) => (num(v) === 0 ? '' : String(v))

type Props = {
  kind: 'internet' | 'home'
  title: string
  description: string
}

export function KindStatReportPage({ kind, title, description }: Props) {
  const [mode, setMode] = useState<'daily' | 'monthly'>('daily')
  const [cursor, setCursor] = useState<Dayjs>(dayjs())

  const params = useMemo(() => ({
    mode,
    year: cursor.year(),
    month: mode === 'daily' ? cursor.month() + 1 : undefined }), [mode, cursor])

  const query = useQuery({
    queryKey: [`homes-report-${kind}`, params],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<KindStatData>>(`${apiPrefix()}/homes/reports/${kind}`, {
        params })
      return unwrap(data)
    } })

  const rows = query.data?.rows || []
  const totals = query.data?.totals

  const columns = useMemo(() => [
    {
      title: mode === 'daily' ? '일자' : '월',
      dataIndex: 'label',
      width: 90,
      align: 'center' as const },
    {
      title: '건수',
      dataIndex: 'count',
      width: 90,
      align: 'right' as const,
      render: countCell },
    {
      title: '정책합산',
      dataIndex: 'policySum',
      width: 120,
      align: 'right' as const,
      render: cell },
    {
      title: '정산합계',
      dataIndex: 'settleAmount',
      width: 120,
      align: 'right' as const,
      render: cell },
    {
      title: '마진합계',
      dataIndex: 'margin',
      width: 120,
      align: 'right' as const,
      render: cell },
  ], [mode])

  const shift = (dir: -1 | 1) => {
    setCursor((d) => (mode === 'daily' ? d.add(dir, 'month') : d.add(dir, 'year')))
  }

  const periodLabel = mode === 'daily'
    ? cursor.format('YYYY년 M월')
    : cursor.format('YYYY년')

  return (
    <div className="stock-page kind-stat-page">
      <div className="stock-title kind-stat-title-row">
        <div>
          <h2>
            <BarChartOutlined className="product-title-icon kind-stat-icon" />
            {title}
          </h2>
          <p>{description}</p>
        </div>
        <div className="kind-stat-view-toggle">
          <Button className={mode === 'daily' ? 'kind-stat-view-active' : ''} onClick={() => setMode('daily')}>
            일별통계
          </Button>
          <Button className={mode === 'monthly' ? 'kind-stat-view-active' : ''} onClick={() => setMode('monthly')}>
            월별통계
          </Button>
        </div>
        <div className="kind-stat-note">* 철회된 계약은 제외됩니다.</div>
      </div>

      <Card className="kind-stat-period-card" size="small">
        <div className="kind-stat-period-nav">
          <Button type="text" icon={<LeftOutlined />} onClick={() => shift(-1)} />
          <span className="kind-stat-period-label">{periodLabel}</span>
          <Button type="text" icon={<RightOutlined />} onClick={() => shift(1)} />
        </div>
      </Card>

      <Card className="stock-table-card kind-stat-table-card" size="small" loading={query.isLoading}>
        {rows.length ? (
          <CareTable
            rowKey={(r) => String(r.key ?? r.label)}
            size="small"
            dataSource={rows}
            columns={columns}
            pagination={false}
            scroll={{ x: 600 }}
            summary={() => (
              <Table.Summary.Row>
                <Table.Summary.Cell index={0} align="center"><b>합계</b></Table.Summary.Cell>
                <Table.Summary.Cell index={1} align="right"><b>{countCell(totals?.count)}</b></Table.Summary.Cell>
                <Table.Summary.Cell index={2} align="right"><b>{cell(totals?.policySum)}</b></Table.Summary.Cell>
                <Table.Summary.Cell index={3} align="right"><b>{cell(totals?.settleAmount)}</b></Table.Summary.Cell>
                <Table.Summary.Cell index={4} align="right"><b>{cell(totals?.margin)}</b></Table.Summary.Cell>
              </Table.Summary.Row>
            )}
          />
        ) : (
          <Empty className="kind-stat-empty" image={Empty.PRESENTED_IMAGE_SIMPLE} description="자료가 없습니다." />
        )}
      </Card>
    </div>
  )
}
