import { useRef, useState } from 'react';
import { Button, Modal, Form, Select, message } from 'antd';
import { DownloadOutlined, FileExcelOutlined } from '@ant-design/icons';
import { ProTable, type ActionType, type ProColumns } from '@ant-design/pro-components';
import PageContainer from '@/components/common/PageContainer';
import CodeBadge from '@/components/common/CodeBadge';
import MoneyText from '@/components/common/MoneyText';
import { useCommonCodes } from '@/hooks/useCommonCodes';
import { paymentApi, PaymentResp, TransferFileResp } from '@/api/payment';
import DatePicker from 'antd/es/date-picker';
import dayjs from 'dayjs';

const { MonthPicker } = DatePicker;

export default function PaymentList() {
  const actionRef = useRef<ActionType>();
  const { data: statusCodes = [] } = useCommonCodes('PAYMENT_STATUS');
  const { data: bankCodes = [] } = useCommonCodes('BANK_CODE');

  const [transferModalOpen, setTransferModalOpen] = useState(false);
  const [resultModalOpen, setResultModalOpen] = useState(false);
  const [transferResult, setTransferResult] = useState<TransferFileResp | null>(null);
  const [generating, setGenerating] = useState(false);
  const [form] = Form.useForm();

  const handleGenerateTransferFile = async () => {
    const values = await form.validateFields();
    const settleMonth = values.settleMonth ? dayjs(values.settleMonth).format('YYYYMM') : undefined;
    if (!settleMonth) return;

    setGenerating(true);
    try {
      const result = await paymentApi.generateTransferFile(settleMonth, values.bankCode);
      setTransferResult(result);
      setTransferModalOpen(false);
      setResultModalOpen(true);
      actionRef.current?.reload();
      message.success('이체파일이 생성되었습니다');
    } catch {
      // 에러는 request.ts 인터셉터에서 처리
    } finally {
      setGenerating(false);
    }
  };

  const handleDownload = () => {
    if (!transferResult) return;
    window.open(`/api/files/${transferResult.fileId}`, '_blank');
  };

  const columns: ProColumns<PaymentResp>[] = [
    {
      title: '정산월', dataIndex: 'settleMonth', width: 90,
      valueType: 'dateMonth', fieldProps: { format: 'YYYYMM' },
    },
    {
      title: '지급상태', dataIndex: 'payStatus', width: 100, valueType: 'select',
      valueEnum: Object.fromEntries(statusCodes.map((c) => [c.code, { text: c.codeName }])),
      render: (_, r) => <CodeBadge groupCode="PAYMENT_STATUS" value={r.payStatus} />,
    },
    { title: '설계사', dataIndex: 'agentName', width: 100, search: false },
    { title: '은행',   dataIndex: 'bankName',  width: 100, search: false },
    { title: '계좌',   dataIndex: 'accountNo', width: 180, search: false },
    {
      title: '지급액', dataIndex: 'payAmount', width: 140, align: 'right', search: false,
      render: (_, r) => <strong><MoneyText value={r.payAmount} /></strong>,
    },
    { title: '지급일',   dataIndex: 'payDate',    width: 110, search: false },
    { title: '실패사유', dataIndex: 'failReason', ellipsis: true, search: false },
    {
      title: '이체파일', dataIndex: 'transferFileId', width: 120, search: false,
      render: (_, r) =>
        r.transferFileId ? (
          <a href={`/api/files/${r.transferFileId}`} target="_blank" rel="noreferrer">
            <DownloadOutlined /> #{r.transferFileId}
          </a>
        ) : (
          '-'
        ),
    },
  ];

  return (
    <PageContainer title="지급 관리" description="확정 정산 → 이체 파일 생성 / 결과 추적">
      <ProTable<PaymentResp>
        actionRef={actionRef}
        rowKey="paymentId"
        columns={columns}
        scroll={{ x: 1200 }}
        request={async (params) => {
          const { current, pageSize, ...rest } = params as any;
          const res = await paymentApi.list({ ...rest, 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"
        toolBarRender={() => [
          <Button
            key="transfer-file"
            type="primary"
            icon={<FileExcelOutlined />}
            onClick={() => { form.resetFields(); setTransferModalOpen(true); }}
          >
            이체파일 생성
          </Button>,
        ]}
      />

      {/* 이체파일 생성 입력 모달 */}
      <Modal
        title="이체파일 생성"
        open={transferModalOpen}
        onOk={handleGenerateTransferFile}
        onCancel={() => setTransferModalOpen(false)}
        confirmLoading={generating}
        okText="생성"
        cancelText="취소"
        destroyOnClose
      >
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="settleMonth"
            label="정산월"
            rules={[{ required: true, message: '정산월을 선택해주세요' }]}
          >
            <MonthPicker style={{ width: '100%' }} format="YYYYMM" placeholder="정산월 선택" />
          </Form.Item>
          <Form.Item
            name="bankCode"
            label="은행"
            rules={[{ required: true, message: '은행을 선택해주세요' }]}
          >
            <Select placeholder="은행 선택" allowClear>
              {bankCodes.map((c) => (
                <Select.Option key={c.code} value={c.code}>
                  {c.codeName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 이체파일 생성 결과 모달 */}
      <Modal
        title="이체파일 생성 완료"
        open={resultModalOpen}
        onOk={() => setResultModalOpen(false)}
        onCancel={() => setResultModalOpen(false)}
        okText="확인"
        cancelButtonProps={{ style: { display: 'none' } }}
        footer={[
          <Button key="download" type="primary" icon={<DownloadOutlined />} onClick={handleDownload}>
            파일 다운로드
          </Button>,
          <Button key="close" onClick={() => setResultModalOpen(false)}>
            닫기
          </Button>,
        ]}
      >
        {transferResult && (
          <div style={{ lineHeight: 2 }}>
            <div>파일명: <strong>{transferResult.fileName}</strong></div>
            <div>파일 ID: <strong>{transferResult.fileId}</strong></div>
            <div>처리 건수: <strong>{transferResult.paymentCount.toLocaleString()}건</strong></div>
            <div>
              합계 금액:{' '}
              <strong>
                {Number(transferResult.totalAmount).toLocaleString()}원
              </strong>
            </div>
          </div>
        )}
      </Modal>
    </PageContainer>
  );
}
