import { useRef, useState } from 'react';
import { Input, Modal, Space, message } from 'antd';
import { ProCard, ProTable, StatisticCard, type ActionType, type ProColumns } from '@ant-design/pro-components';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import PageContainer from '@/components/common/PageContainer';
import CodeBadge from '@/components/common/CodeBadge';
import MoneyText from '@/components/common/MoneyText';
import PermissionButton from '@/components/common/PermissionButton';
import { useCommonCodes } from '@/hooks/useCommonCodes';
import { settleApi, SettleResp, SettleSearchParam } from '@/api/settle';

const { Statistic } = StatisticCard;

export default function SettleList() {
  const qc = useQueryClient();
  const actionRef = useRef<ActionType>();
  const [settleMonth, setSettleMonth] = useState<string | undefined>(undefined);
  const { data: statusCodes = [] } = useCommonCodes('SETTLE_STATUS');

  const { data: summary } = useQuery({
    queryKey: ['settle', 'summary', settleMonth],
    queryFn: () => settleApi.summary(settleMonth!),
    enabled: !!settleMonth,
  });

  const refresh = () => {
    qc.invalidateQueries({ queryKey: ['settle'] });
    actionRef.current?.reload();
  };

  const onConfirm = (id: number) =>
    Modal.confirm({
      title: '정산 확정', content: '확정 후에는 변경할 수 없습니다. 진행하시겠습니까?',
      onOk: async () => { await settleApi.confirm(id); message.success('확정 완료'); refresh(); },
    });

  const onHold = (id: number) => {
    let reason = '';
    Modal.confirm({
      title: '정산 보류',
      content: <Input placeholder="보류 사유" onChange={(e) => { reason = e.target.value; }} />,
      onOk: async () => { await settleApi.hold(id, reason); message.success('보류 처리'); refresh(); },
    });
  };

  const columns: ProColumns<SettleResp>[] = [
    { title: '정산월', dataIndex: 'settleMonth', width: 90, fixed: 'left',
      valueType: 'dateMonth', fieldProps: { format: 'YYYYMM' } },
    {
      title: '상태', dataIndex: 'status', width: 100, valueType: 'select', fixed: 'right',
      valueEnum: Object.fromEntries(statusCodes.map((c) => [c.code, { text: c.codeName }])),
      render: (_, r) => <CodeBadge groupCode="SETTLE_STATUS" value={r.status} />,
    },
    { title: '설계사', dataIndex: 'agentName', width: 100, fixed: 'left', search: false },
    { title: '소속',   dataIndex: 'orgName',   width: 160, search: false },
    { title: '직급',   dataIndex: 'gradeName', width: 80,  search: false },
    { title: '모집',   dataIndex: 'recruitTotal',  width: 110, align: 'right', search: false, render: (_, r) => <MoneyText value={r.recruitTotal} /> },
    { title: '유지',   dataIndex: 'maintainTotal', width: 110, align: 'right', search: false, render: (_, r) => <MoneyText value={r.maintainTotal} /> },
    { title: '예외(+)', dataIndex: 'exceptionPlus', width: 100, align: 'right', search: false, render: (_, r) => <MoneyText value={r.exceptionPlus} /> },
    { title: '예외(-)', dataIndex: 'exceptionMinus', width: 100, align: 'right', search: false, render: (_, r) => <MoneyText value={r.exceptionMinus} /> },
    { title: '오버라이드', dataIndex: 'overrideTotal', width: 110, align: 'right', search: false, render: (_, r) => <MoneyText value={r.overrideTotal} /> },
    {
      title: '환수', dataIndex: 'chargebackTotal', width: 100, align: 'right', search: false,
      render: (_, r) => <MoneyText value={r.chargebackTotal ? -Math.abs(Number(r.chargebackTotal)) : 0} />,
    },
    { title: '총액', dataIndex: 'grossAmount', width: 120, align: 'right', search: false, render: (_, r) => <MoneyText value={r.grossAmount} /> },
    { title: '세액', dataIndex: 'taxAmount', width: 100, align: 'right', search: false, render: (_, r) => <MoneyText value={r.taxAmount} /> },
    {
      title: '실지급', dataIndex: 'netAmount', width: 130, align: 'right', search: false,
      render: (_, r) => <strong><MoneyText value={r.netAmount} /></strong>,
    },
    {
      title: '액션', dataIndex: 'settleId', width: 200, fixed: 'right', search: false,
      render: (_, r) => (
        <Space>
          <PermissionButton menuCode="SETTLE_LIST" permCode="APPROVE" size="small" type="primary"
                            onClick={() => onConfirm(r.settleId)}
                            disabled={r.status === 'CONFIRMED' || r.status === 'PAID'}>확정</PermissionButton>
          <PermissionButton menuCode="SETTLE_LIST" permCode="APPROVE" size="small" danger
                            onClick={() => onHold(r.settleId)} disabled={r.status === 'PAID'}>보류</PermissionButton>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer title="정산 결과" description="설계사별 월 정산 합산 / 확정·보류">
      {summary && (
        <ProCard ghost gutter={16} style={{ marginBottom: 16 }} wrap>
          <ProCard colSpan={6} bordered={false}>
            <Statistic title="대상 설계사" value={Number(summary.agentCount ?? 0)} suffix="명" />
          </ProCard>
          <ProCard colSpan={6} bordered={false}>
            <Statistic title="총 지급액 (net)" value={Number(summary.netAmount ?? 0)} />
          </ProCard>
          <ProCard colSpan={6} bordered={false}>
            <Statistic title="총 세액" value={Number(summary.taxAmount ?? 0)} valueStyle={{ color: '#E24B4A' }} />
          </ProCard>
          <ProCard colSpan={6} bordered={false}>
            <Statistic title="확정 건수" value={Number(summary.confirmedCount ?? 0)} suffix="건" />
          </ProCard>
        </ProCard>
      )}

      <ProTable<SettleResp, SettleSearchParam>
        actionRef={actionRef}
        rowKey="settleId"
        columns={columns}
        scroll={{ x: 1700 }}
        request={async (params) => {
          const { current, pageSize, settleMonth: sm, ...rest } = params as any;
          setSettleMonth(sm);
          const res = await settleApi.list({ ...rest, settleMonth: sm, pageNum: current, pageSize });
          return { data: res.list, total: res.total, success: true };
        }}
        pagination={{
          pageSize: 30, showSizeChanger: true, pageSizeOptions: ['20', '50', '100'],
          showTotal: (total) => `총 ${total.toLocaleString()}건`,
        }}
        search={{ labelWidth: 'auto', searchText: '검색', resetText: '초기화', collapsed: false, collapseRender: false }}
        options={{ density: false, fullScreen: true, reload: true, setting: true }}
        dateFormatter="string"
      />
    </PageContainer>
  );
}
