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

type MonthlyRow = {
  key?: number
  month?: number
  label?: string
  internetCount?: number
  homeCount?: number
  settleAmount?: number
  discountSum?: number
  employeeRebate?: number
  margin?: number
}

type MonthlyReport = {
  year?: number
  title?: string
  rows?: MonthlyRow[]
}

const cell = (v?: number) => {
  if (v == null || Number(v) === 0) return ''
  return money(v)
}

const countCell = (v?: number) => {
  if (v == null || Number(v) === 0) return ''
  return String(v)
}

export default function ReportMonthlyPage() {
  const [year, setYear] = useState(dayjs().year())

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

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

  const download = () => {
    if (!rows.length) {
      message.warning('다운로드할 목록이 없습니다.')
      return
    }
    const header = ['월', '인터넷접수', '홈렌탈접수', '정산합계', '할인합계', '직원리베이트', '마진합계']
    const lines = rows.map((r) =>
      [r.label, r.internetCount ?? 0, r.homeCount ?? 0, r.settleAmount ?? 0, r.discountSum ?? 0, r.employeeRebate ?? 0, r.margin ?? 0]
        .map((v) => `"${String(v ?? '').replace(/"/g, '""')}"`)
        .join(','),
    )
    const blob = new Blob(['\uFEFF' + [header.join(','), ...lines].join('\n')], { type: 'text/csv;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `월간리포트_${year}.csv`
    a.click()
    URL.revokeObjectURL(url)
  }

  const columns = useMemo(
    () => [
      {
        title: '월',
        dataIndex: 'label',
        width: 80,
        align: 'center' as const },
      {
        title: '인터넷접수',
        dataIndex: 'internetCount',
        width: 110,
        align: 'right' as const,
        render: countCell },
      {
        title: '홈렌탈접수',
        dataIndex: 'homeCount',
        width: 110,
        align: 'right' as const,
        render: countCell },
      {
        title: '정산합계',
        dataIndex: 'settleAmount',
        width: 120,
        align: 'right' as const,
        render: cell },
      {
        title: '할인합계',
        dataIndex: 'discountSum',
        width: 120,
        align: 'right' as const,
        render: cell },
      {
        title: '직원리베이트',
        dataIndex: 'employeeRebate',
        width: 120,
        align: 'right' as const,
        render: cell },
      {
        title: '마진합계',
        dataIndex: 'margin',
        width: 120,
        align: 'right' as const,
        render: cell },
    ],
    [],
  )

  return (
    <div className="stock-page monthly-report-page">
      <div className="stock-title">
        <div>
          <h2>
            <BarChartOutlined className="product-title-icon monthly-report-icon" />
            월간리포트
          </h2>
          <p>원하시는 년도의 월간리포트를 확인하실 수 있습니다.</p>
        </div>
      </div>

      <Card className="monthly-report-year-card" size="small">
        <div className="monthly-report-year-nav">
          <Button type="text" icon={<LeftOutlined />} onClick={() => setYear((y) => y - 1)} />
          <span className="monthly-report-year-label">{year}년</span>
          <Button type="text" icon={<RightOutlined />} onClick={() => setYear((y) => y + 1)} />
        </div>
      </Card>

      <Card className="stock-table-card monthly-report-table-card" size="small">
        <div className="recovery-table-head">
          <Typography.Text strong>월별목록</Typography.Text>
          <Button type="link" icon={<DownloadOutlined />} onClick={download}>엑셀다운로드</Button>
        </div>
        <CareTable
          rowKey={(r) => String(r.month ?? r.key ?? r.label)}
          size="small"
          loading={query.isLoading}
          dataSource={rows}
          columns={columns}
          pagination={false}
          scroll={{ x: 800 }}
          locale={{ emptyText: '자료가 없습니다.' }}
        />
      </Card>
    </div>
  )
}
