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
  internetCount?: number
  homeCount?: number
  count?: number
  settleAmount?: number
  margin?: number
  policySum?: number
}

type GroupStatData = {
  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 = {
  apiKind: 'member' | 'agency'
  title: string
  description: string
  labelTitle: string
}

export function GroupStatReportPage({ apiKind, title, description, labelTitle }: Props) {
  const [cursor, setCursor] = useState<Dayjs>(dayjs())

  const params = useMemo(() => ({
    year: cursor.year(),
    month: cursor.month() + 1 }), [cursor])

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

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

  const columns = useMemo(() => [
    {
      title: labelTitle,
      dataIndex: 'label',
      width: 140 },
    {
      title: '인터넷접수',
      dataIndex: 'internetCount',
      width: 110,
      align: 'right' as const,
      render: countCell },
    {
      title: '홈렌탈접수',
      dataIndex: 'homeCount',
      width: 110,
      align: 'right' as const,
      render: countCell },
    {
      title: '계약합계',
      dataIndex: 'count',
      width: 100,
      align: 'right' as const,
      render: countCell },
    {
      title: '정산합계',
      dataIndex: 'settleAmount',
      width: 120,
      align: 'right' as const,
      render: cell },
    {
      title: '마진합계',
      dataIndex: 'margin',
      width: 120,
      align: 'right' as const,
      render: cell },
  ], [labelTitle])

  return (
    <div className="stock-page kind-stat-page">
      <div className="stock-title">
        <div>
          <h2>
            <BarChartOutlined className="product-title-icon kind-stat-icon" />
            {title}
          </h2>
          <p>{description}</p>
        </div>
      </div>

      <Card className="kind-stat-period-card" size="small">
        <div className="kind-stat-period-nav">
          <Button type="text" icon={<LeftOutlined />} onClick={() => setCursor((d) => d.subtract(1, 'month'))} />
          <span className="kind-stat-period-label">{cursor.format('YYYY년 M월')}</span>
          <Button type="text" icon={<RightOutlined />} onClick={() => setCursor((d) => d.add(1, 'month'))} />
        </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: 700 }}
            summary={() => (
              <Table.Summary.Row>
                <Table.Summary.Cell index={0}><b>합계</b></Table.Summary.Cell>
                <Table.Summary.Cell index={1} align="right"><b>{countCell(totals?.internetCount)}</b></Table.Summary.Cell>
                <Table.Summary.Cell index={2} align="right"><b>{countCell(totals?.homeCount)}</b></Table.Summary.Cell>
                <Table.Summary.Cell index={3} align="right"><b>{countCell(totals?.count)}</b></Table.Summary.Cell>
                <Table.Summary.Cell index={4} align="right"><b>{cell(totals?.settleAmount)}</b></Table.Summary.Cell>
                <Table.Summary.Cell index={5} 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>
  )
}
