import { useState } from 'react';
import { Alert, DatePicker } from 'antd';
import { ProCard, ProTable, type ProColumns } from '@ant-design/pro-components';
import { useQuery } from '@tanstack/react-query';
import dayjs, { type Dayjs } from 'dayjs';
import PageContainer from '@/components/common/PageContainer';
import MoneyText from '@/components/common/MoneyText';
import ExcelExportButton from '@/components/common/ExcelExportButton';
import api, { unwrap } from '@/api/request';

interface SimplifiedPaymentRow {
  agentId: number;
  settleMonth: string;
  agentName: string;
  residentNo?: string;
  businessNo?: string;
  incomeTypeName: string;
  grossAmount: number;
  incomeTaxAmount: number;
  localTaxAmount: number;
  netAmount: number;
}

function fetchReport(settleMonth: string) {
  return unwrap<SimplifiedPaymentRow[]>(
    api.get('/api/report/simplified-payment', { params: { settleMonth } }),
  );
}

// 화면 표시용 주민번호 마스킹(생년월일+성별구분 이후 *). 엑셀 export(국세청 제출용)는 원본 유지.
function maskResidentNo(v?: string): string {
  if (!v) return '-';
  return v.length > 8 ? v.slice(0, 8) + '*'.repeat(v.length - 8) : v;
}

const columns: ProColumns<SimplifiedPaymentRow>[] = [
  { title: '소득자', dataIndex: 'agentName', width: 120, fixed: 'left' },
  { title: '주민등록번호', dataIndex: 'residentNo', width: 140, render: (_, r) => maskResidentNo(r.residentNo) },
  { title: '사업자번호', dataIndex: 'businessNo', width: 140 },
  { title: '소득구분', dataIndex: 'incomeTypeName', width: 90 },
  {
    title: '지급액', dataIndex: 'grossAmount', width: 130, align: 'right',
    render: (_, r) => <MoneyText value={r.grossAmount} />,
  },
  {
    title: '소득세', dataIndex: 'incomeTaxAmount', width: 120, align: 'right',
    render: (_, r) => <MoneyText value={r.incomeTaxAmount} />,
  },
  {
    title: '지방소득세', dataIndex: 'localTaxAmount', width: 120, align: 'right',
    render: (_, r) => <MoneyText value={r.localTaxAmount} />,
  },
  {
    title: '차인지급액', dataIndex: 'netAmount', width: 140, align: 'right',
    render: (_, r) => <strong><MoneyText value={r.netAmount} /></strong>,
  },
];

export default function SimplifiedPaymentReport() {
  const [settleMonth, setSettleMonth] = useState<Dayjs>(dayjs());

  const monthStr = settleMonth.format('YYYYMM');

  const { data, isLoading, isError } = useQuery({
    queryKey: ['report', 'simplified-payment', monthStr],
    queryFn: () => fetchReport(monthStr),
    retry: false,
  });

  return (
    <PageContainer
      title="사업소득 간이지급명세서"
      description="월별 사업소득 지급·원천징수 명세 (국세청 간이지급명세서 제출 대응)"
      extra={
        <ExcelExportButton
          url="/api/report/simplified-payment/export"
          fileName={`간이지급명세서_${monthStr}`}
          params={{ settleMonth: monthStr }}
        />
      }
    >
      {isError && (
        <Alert
          type="warning"
          showIcon
          message="조회 실패"
          description="/api/report/simplified-payment API 응답이 없습니다."
          style={{ marginBottom: 16 }}
        />
      )}

      <ProCard bordered style={{ marginBottom: 16 }}>
        <DatePicker
          picker="month"
          value={settleMonth}
          onChange={(d) => d && setSettleMonth(d)}
          allowClear={false}
          format="YYYY-MM"
        />
      </ProCard>

      <ProTable<SimplifiedPaymentRow>
        rowKey="agentId"
        columns={columns}
        dataSource={data ?? []}
        loading={isLoading}
        search={false}
        pagination={{ pageSize: 50, showTotal: (t) => `총 ${t}건` }}
        options={{ density: false, reload: false }}
        scroll={{ x: 1000 }}
      />
    </PageContainer>
  );
}
