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

type MyInvoiceRow = {
  id: number
  yearMonth?: string
  employee?: string
  internetCount?: number
  internetAmount?: number
  homeCount?: number
  homeAmount?: number
  balanceCount?: number
  balanceAmount?: number
  settleAmount?: number
  amount?: number
  status?: string
}

type MyInvoiceResult = {
  total: number
  employee?: string
  list: MyInvoiceRow[]
}

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 moneyCell = (v: unknown) => (num(v) === 0 ? '' : money(v))

const formatYm = (ym?: string) => {
  if (!ym) return '-'
  const d = dayjs(`${ym}-01`)
  return d.isValid() ? d.format('YYYY년 M월') : ym
}

export default function InvoiceMyPage() {
  const query = useQuery({
    queryKey: ['homes-invoice-my'],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<MyInvoiceResult>>(`${apiPrefix()}/homes/invoices/my`)
      return unwrap(data)
    } })

  const download = async (row: MyInvoiceRow) => {
    try {
      const { data } = await client.get(`${apiPrefix()}/homes/invoices/${row.id}/export`, { responseType: 'blob' })
      const url = URL.createObjectURL(data)
      const a = document.createElement('a')
      a.href = url
      a.download = `나의정산서_${row.yearMonth || row.id}.csv`
      a.click()
      URL.revokeObjectURL(url)
    } catch {
      message.error('엑셀 다운로드에 실패했습니다.')
    }
  }

  const columns = useMemo(() => [
    {
      title: '기준월',
      dataIndex: 'yearMonth',
      width: 110,
      align: 'center' as const,
      render: (v: string) => formatYm(v) },
    { title: '직원', dataIndex: 'employee', width: 100, align: 'center' as const },
    {
      title: '인터넷',
      dataIndex: 'internetCount',
      width: 80,
      align: 'center' as const,
      render: cell },
    {
      title: '인터넷금액',
      dataIndex: 'internetAmount',
      width: 110,
      align: 'center' as const,
      render: moneyCell },
    {
      title: '홈렌탈',
      dataIndex: 'homeCount',
      width: 80,
      align: 'center' as const,
      render: cell },
    {
      title: '홈렌탈금액',
      dataIndex: 'homeAmount',
      width: 110,
      align: 'center' as const,
      render: moneyCell },
    {
      title: '후정산',
      dataIndex: 'balanceCount',
      width: 80,
      align: 'center' as const,
      render: cell },
    {
      title: '후정산금액',
      dataIndex: 'balanceAmount',
      width: 110,
      align: 'center' as const,
      render: moneyCell },
    {
      title: '정산금액',
      dataIndex: 'settleAmount',
      width: 110,
      align: 'center' as const,
      render: (_: unknown, row: MyInvoiceRow) => moneyCell(row.settleAmount ?? row.amount) },
    {
      title: '엑셀',
      width: 70,
      align: 'center' as const,
      render: (_: unknown, row: MyInvoiceRow) => (
        <Button
          type="link"
          size="small"
          className="invoice-excel-link"
          icon={<FileExcelOutlined />}
          onClick={() => download(row)}
        />
      ) },
    {
      title: '상태',
      dataIndex: 'status',
      width: 80,
      align: 'center' as const,
      render: (v: string) => v || '-' },
  ], [])

  return (
    <div className="stock-page invoice-my-page">
      <div className="stock-title">
        <div>
          <h2>
            <CalculatorOutlined className="product-title-icon" />
            나의정산서
          </h2>
          <p>최근 12개월 이내 발행된 정산서를 확인하실 수 있습니다.</p>
        </div>
      </div>

      <Card className="stock-table-card" size="small">
        <CareTable
          rowKey="id"
          size="small"
          loading={query.isLoading}
          dataSource={query.data?.list}
          columns={columns}
          pagination={false}
          scroll={{ x: 1100 }}
          locale={{ emptyText: '등록된 자료가 없습니다.' }}
        />
      </Card>
    </div>
  )
}
