import { useRef, useState } from 'react';
import { Modal, Space, message } from 'antd';
import {
  ModalForm, ProForm, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea,
  ProTable, type ActionType, type ProColumns,
} from '@ant-design/pro-components';
import { useQuery } 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 { exceptionApi, ExceptionLedgerResp, ExceptionLedgerSaveReq } from '@/api/exceptionLedger';
import { agentApi } from '@/api/agent';
import { ruleApi } from '@/api/rule';

export default function ExceptionLedger() {
  const actionRef = useRef<ActionType>();
  const [open, setOpen] = useState(false);
  const { data: approveCodes = [] } = useCommonCodes('APPROVE_STATUS');

  const { data: agents } = useQuery({
    queryKey: ['agents', 'all'], queryFn: () => agentApi.list({ pageSize: 999 }), enabled: open,
  });
  const { data: excCodes = [] } = useQuery({
    queryKey: ['rules', 'exceptions'], queryFn: ruleApi.exceptionCodes, enabled: open,
  });

  const onApprove = (id: number, status: 'APPROVED' | 'REJECTED') =>
    Modal.confirm({
      title: status === 'APPROVED' ? '승인하시겠습니까?' : '반려하시겠습니까?',
      onOk: async () => {
        await exceptionApi.approve(id, status);
        message.success(status === 'APPROVED' ? '승인 완료' : '반려 완료');
        actionRef.current?.reload();
      },
    });

  const onSubmit = async (v: any) => {
    const req: ExceptionLedgerSaveReq = { ...v };
    await exceptionApi.create(req);
    message.success('등록 완료. 승인 대기 상태입니다.');
    setOpen(false);
    actionRef.current?.reload();
    return true;
  };

  const columns: ProColumns<ExceptionLedgerResp>[] = [
    { title: '정산월', dataIndex: 'settleMonth', width: 90, valueType: 'dateMonth', fieldProps: { format: 'YYYYMM' } },
    {
      title: '승인상태', dataIndex: 'approveStatus', width: 100, valueType: 'select',
      valueEnum: Object.fromEntries(approveCodes.map((c) => [c.code, { text: c.codeName }])),
      render: (_, r) => <CodeBadge groupCode="APPROVE_STATUS" value={r.approveStatus} />,
    },
    { title: '설계사', dataIndex: 'agentName', width: 100, search: false },
    { title: '소속',   dataIndex: 'orgName',   width: 160, search: false },
    { title: '예외코드', dataIndex: 'exceptionName', width: 120, search: false },
    {
      title: '구분', dataIndex: 'direction', width: 80, search: false,
      render: (_, r) => <CodeBadge groupCode="EXCEPTION_DIRECTION" value={r.direction} />,
    },
    {
      title: '금액', dataIndex: 'amount', width: 130, align: 'right', search: false,
      render: (_, r) => <MoneyText value={r.direction === 'MINUS' ? -Math.abs(r.amount) : r.amount} />,
    },
    { title: '내용', dataIndex: 'description', ellipsis: true, search: false },
    {
      title: '재반복', dataIndex: 'recurringLeft', width: 90, align: 'center', search: false,
      render: (_, r) => r.recurringYn === 'Y' ? `${r.recurringLeft}회 남음` : '-',
    },
    { title: '승인자', dataIndex: 'approverName', width: 100, search: false },
    { title: '승인일시', dataIndex: 'approveDate', width: 160, search: false },
    {
      title: '액션', dataIndex: 'ledgerId', width: 180, fixed: 'right', search: false,
      render: (_, r) => r.approveStatus === 'PENDING' ? (
        <Space>
          <PermissionButton menuCode="LEDGER_EXCEPTION" permCode="APPROVE" size="small"
                            type="primary" onClick={() => onApprove(r.ledgerId, 'APPROVED')}>승인</PermissionButton>
          <PermissionButton menuCode="LEDGER_EXCEPTION" permCode="APPROVE" size="small"
                            danger onClick={() => onApprove(r.ledgerId, 'REJECTED')}>반려</PermissionButton>
        </Space>
      ) : null,
    },
  ];

  return (
    <PageContainer title="예외금액 원장" description="수동 등록 예외 금액 / 승인 워크플로우">
      <ProTable<ExceptionLedgerResp>
        actionRef={actionRef}
        rowKey="ledgerId"
        columns={columns}
        scroll={{ x: 1500 }}
        request={async (params) => {
          const { current, pageSize, ...rest } = params as any;
          const res = await exceptionApi.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 }}
        toolBarRender={() => [
          <PermissionButton key="create" menuCode="LEDGER_EXCEPTION" permCode="CREATE" type="primary"
            onClick={() => setOpen(true)}>+ 예외금액 등록</PermissionButton>,
        ]}
        dateFormatter="string"
      />

      <ModalForm
        title="예외금액 등록"
        open={open}
        onOpenChange={setOpen}
        width={620}
        layout="vertical"
        onFinish={onSubmit}
        submitter={{ searchConfig: { submitText: '등록', resetText: '취소' } }}
        modalProps={{ destroyOnClose: true, maskClosable: false }}
      >
        <ProForm.Group>
          <ProFormSelect
            name="agentId" label="설계사" rules={[{ required: true }]} width="md" showSearch
            options={agents?.list.map((a) => ({ value: a.agentId, label: `${a.agentName} (${a.licenseNo ?? '-'})` })) ?? []}
          />
          <ProFormText
            name="settleMonth" label="정산월 (YYYYMM)" rules={[{ required: true, pattern: /^\d{6}$/ }]}
            width="md" placeholder="202605"
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            name="exceptionCode" label="예외코드" rules={[{ required: true }]} width="md"
            options={excCodes.map((c) => ({ value: c.exceptionCode, label: `${c.exceptionName} (${c.direction})` }))}
          />
          <ProFormDigit
            name="amount" label="금액" rules={[{ required: true }]} width="md" min={1}
            fieldProps={{ formatter: (v) => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText name="policyNo" label="증권번호 (선택)" width="md" />
          <ProFormText name="companyCode" label="보험사코드 (선택)" width="md" />
        </ProForm.Group>
        <ProFormTextArea name="description" label="내용" placeholder="예외 사유 / 참조 문서" />
      </ModalForm>
    </PageContainer>
  );
}
