import { useRef, useState } from 'react';
import {
  Form,
  Input,
  InputNumber,
  Modal,
  Space,
  Tag,
  message,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {
  ProTable,
  type ActionType,
  type ProColumns,
} from '@ant-design/pro-components';
import dayjs from 'dayjs';
import DatePicker from 'antd/es/date-picker';
import PageContainer from '@/components/common/PageContainer';
import MoneyText from '@/components/common/MoneyText';
import PermissionButton from '@/components/common/PermissionButton';
import {
  disputeApi,
  DisputeResp,
  DisputeSaveReq,
  DisputeSearchParam,
} from '@/api/dispute';

const { MonthPicker } = DatePicker;

// ── 상태 Badge 색상 정의 ─────────────────────────────────────────────────────
const STATUS_TAG: Record<string, { color: string; label: string }> = {
  PENDING:   { color: 'orange', label: '대기' },
  REVIEWING: { color: 'blue',   label: '검토중' },
  APPROVED:  { color: 'green',  label: '승인' },
  REJECTED:  { color: 'red',    label: '반려' },
};

const STATUS_ENUM: Record<string, { text: string }> = {
  PENDING:   { text: '대기' },
  REVIEWING: { text: '검토중' },
  APPROVED:  { text: '승인' },
  REJECTED:  { text: '반려' },
};

// ── 등록 폼 내부 타입 ────────────────────────────────────────────────────────
interface RegisterFormValues {
  agentId: number;
  settleMonthPicker?: unknown;
  settleId?: number;
  disputedAmount?: number;
  claimAmount?: number;
  reason: string;
  evidenceUrl?: string;
}

export default function CommissionDispute() {
  const actionRef = useRef<ActionType>();

  // 이의신청 등록 모달
  const [registerOpen, setRegisterOpen] = useState(false);
  const [registering, setRegistering] = useState(false);
  const [registerForm] = Form.useForm<RegisterFormValues>();

  // 승인 모달
  const [approveOpen, setApproveOpen] = useState(false);
  const [approving, setApproving] = useState(false);
  const [approveTarget, setApproveTarget] = useState<DisputeResp | null>(null);
  const [approveForm] = Form.useForm<{ resolution: string; adjustmentAmount?: number }>();

  // 반려 모달
  const [rejectOpen, setRejectOpen] = useState(false);
  const [rejecting, setRejecting] = useState(false);
  const [rejectTarget, setRejectTarget] = useState<DisputeResp | null>(null);
  const [rejectForm] = Form.useForm<{ resolution: string }>();

  // ── 등록 처리 ────────────────────────────────────────────────────────────────
  const handleRegister = async () => {
    const values = await registerForm.validateFields();
    const payload: DisputeSaveReq = {
      agentId:      values.agentId,
      settleMonth:  values.settleMonthPicker
        ? dayjs(values.settleMonthPicker as Parameters<typeof dayjs>[0]).format('YYYYMM')
        : '',
      settleId:     values.settleId,
      disputedAmount: values.disputedAmount,
      claimAmount:  values.claimAmount,
      reason:       values.reason,
      evidenceUrl:  values.evidenceUrl,
    };
    setRegistering(true);
    try {
      await disputeApi.create(payload);
      message.success('이의신청이 등록되었습니다');
      setRegisterOpen(false);
      registerForm.resetFields();
      actionRef.current?.reload();
    } finally {
      setRegistering(false);
    }
  };

  // ── 검토시작 처리 ────────────────────────────────────────────────────────────
  const handleReview = (record: DisputeResp) => {
    Modal.confirm({
      title: '검토 시작',
      content: `"${record.agentName}"의 이의신청을 검토 상태로 변경하시겠습니까?`,
      okText: '검토시작',
      cancelText: '취소',
      onOk: async () => {
        await disputeApi.review(record.disputeId);
        message.success('검토 상태로 변경되었습니다');
        actionRef.current?.reload();
      },
    });
  };

  // ── 승인 처리 ────────────────────────────────────────────────────────────────
  const openApprove = (record: DisputeResp) => {
    setApproveTarget(record);
    approveForm.resetFields();
    setApproveOpen(true);
  };

  const handleApprove = async () => {
    if (!approveTarget) return;
    const values = await approveForm.validateFields();
    setApproving(true);
    try {
      await disputeApi.approve(
        approveTarget.disputeId,
        values.resolution,
        values.adjustmentAmount,
      );
      message.success('이의신청이 승인되었습니다');
      setApproveOpen(false);
      setApproveTarget(null);
      actionRef.current?.reload();
    } finally {
      setApproving(false);
    }
  };

  // ── 반려 처리 ────────────────────────────────────────────────────────────────
  const openReject = (record: DisputeResp) => {
    setRejectTarget(record);
    rejectForm.resetFields();
    setRejectOpen(true);
  };

  const handleReject = async () => {
    if (!rejectTarget) return;
    const { resolution } = await rejectForm.validateFields();
    setRejecting(true);
    try {
      await disputeApi.reject(rejectTarget.disputeId, resolution);
      message.success('이의신청이 반려되었습니다');
      setRejectOpen(false);
      setRejectTarget(null);
      actionRef.current?.reload();
    } finally {
      setRejecting(false);
    }
  };

  // ── 컬럼 정의 ────────────────────────────────────────────────────────────────
  const columns: ProColumns<DisputeResp>[] = [
    {
      title: '설계사명',
      dataIndex: 'agentName',
      width: 100,
      fixed: 'left',
      search: false,
    },
    {
      title: '조직명',
      dataIndex: 'orgName',
      width: 140,
      ellipsis: true,
      search: false,
    },
    {
      title: '정산월',
      dataIndex: 'settleMonth',
      width: 90,
      valueType: 'dateMonth',
      fieldProps: { format: 'YYYYMM' },
    },
    {
      title: '이의금액',
      dataIndex: 'disputedAmount',
      width: 130,
      align: 'right',
      search: false,
      render: (_, r) => <MoneyText value={r.disputedAmount} />,
    },
    {
      title: '청구금액',
      dataIndex: 'claimAmount',
      width: 130,
      align: 'right',
      search: false,
      render: (_, r) => <MoneyText value={r.claimAmount} />,
    },
    {
      title: '상태',
      dataIndex: 'status',
      width: 100,
      valueType: 'select',
      valueEnum: STATUS_ENUM,
      render: (_, r) => {
        const info = STATUS_TAG[r.status] ?? { color: 'default', label: r.statusName ?? r.status };
        return <Tag color={info.color}>{info.label}</Tag>;
      },
    },
    {
      title: '이의사유',
      dataIndex: 'reason',
      width: 200,
      ellipsis: true,
      search: false,
    },
    {
      title: '검토자',
      dataIndex: 'reviewerName',
      width: 90,
      search: false,
    },
    {
      title: '처리자',
      dataIndex: 'resolvedByName',
      width: 90,
      search: false,
    },
    {
      title: '등록일',
      dataIndex: 'createdAt',
      width: 160,
      search: false,
    },
    {
      title: '액션',
      dataIndex: 'disputeId',
      width: 180,
      fixed: 'right',
      search: false,
      render: (_, r) => (
        <Space>
          {r.status === 'PENDING' && (
            <PermissionButton
              menuCode="DISPUTE"
              permCode="UPDATE"
              size="small"
              type="default"
              onClick={() => handleReview(r)}
            >
              검토시작
            </PermissionButton>
          )}
          {r.status === 'REVIEWING' && (
            <>
              <PermissionButton
                menuCode="DISPUTE"
                permCode="APPROVE"
                size="small"
                type="primary"
                onClick={() => openApprove(r)}
              >
                승인
              </PermissionButton>
              <PermissionButton
                menuCode="DISPUTE"
                permCode="APPROVE"
                size="small"
                danger
                onClick={() => openReject(r)}
              >
                반려
              </PermissionButton>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      title="수수료 이의신청 관리"
      description="설계사 수수료 이의신청 접수 · 검토 · 승인/반려"
    >
      <ProTable<DisputeResp, DisputeSearchParam>
        actionRef={actionRef}
        rowKey="disputeId"
        columns={columns}
        scroll={{ x: 1400 }}
        request={async (params) => {
          const { current, pageSize, settleMonth, status } = params as any;
          const res = await disputeApi.list({
            settleMonth: settleMonth
              ? dayjs(settleMonth).format('YYYYMM')
              : undefined,
            status,
            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={() => [
          <PermissionButton
            key="register"
            menuCode="DISPUTE"
            permCode="CREATE"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              registerForm.resetFields();
              setRegisterOpen(true);
            }}
          >
            이의신청 등록
          </PermissionButton>,
        ]}
      />

      {/* ── 이의신청 등록 모달 ────────────────────────────────────────────────── */}
      <Modal
        title="이의신청 등록"
        open={registerOpen}
        onOk={handleRegister}
        onCancel={() => setRegisterOpen(false)}
        confirmLoading={registering}
        okText="등록"
        cancelText="닫기"
        destroyOnClose
        width={560}
      >
        <Form form={registerForm} layout="vertical" style={{ marginTop: 16 }}>
          <Space style={{ width: '100%', display: 'flex', gap: 8 }}>
            <Form.Item
              name="agentId"
              label="설계사 ID"
              rules={[{ required: true, message: '설계사 ID를 입력해주세요' }]}
              style={{ flex: 1 }}
            >
              <InputNumber style={{ width: '100%' }} placeholder="설계사 ID" min={1} />
            </Form.Item>
            <Form.Item
              name="settleMonthPicker"
              label="정산월"
              rules={[{ required: true, message: '정산월을 선택해주세요' }]}
              style={{ flex: 1 }}
            >
              <MonthPicker style={{ width: '100%' }} format="YYYYMM" placeholder="YYYYMM" />
            </Form.Item>
          </Space>

          <Form.Item name="settleId" label="정산 ID (선택)">
            <InputNumber style={{ width: '100%' }} placeholder="정산 ID" min={1} />
          </Form.Item>

          <Space style={{ width: '100%', display: 'flex', gap: 8 }}>
            <Form.Item name="disputedAmount" label="이의금액" style={{ flex: 1 }}>
              <InputNumber
                style={{ width: '100%' }}
                formatter={(v) => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={(v) => Number(v?.replace(/,/g, '') ?? 0) as unknown as 0}
                placeholder="이의금액"
                min={0}
              />
            </Form.Item>
            <Form.Item name="claimAmount" label="청구금액" style={{ flex: 1 }}>
              <InputNumber
                style={{ width: '100%' }}
                formatter={(v) => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={(v) => Number(v?.replace(/,/g, '') ?? 0) as unknown as 0}
                placeholder="청구금액"
                min={0}
              />
            </Form.Item>
          </Space>

          <Form.Item
            name="reason"
            label="이의 사유"
            rules={[{ required: true, message: '이의 사유를 입력해주세요' }]}
          >
            <Input.TextArea rows={3} placeholder="이의 사유를 상세히 입력해주세요" />
          </Form.Item>

          <Form.Item name="evidenceUrl" label="증빙 파일 URL">
            <Input placeholder="https://..." />
          </Form.Item>
        </Form>
      </Modal>

      {/* ── 승인 모달 ──────────────────────────────────────────────────────────── */}
      <Modal
        title={`이의신청 승인 — ${approveTarget?.agentName ?? ''}`}
        open={approveOpen}
        onOk={handleApprove}
        onCancel={() => setApproveOpen(false)}
        confirmLoading={approving}
        okText="승인"
        okButtonProps={{ type: 'primary' }}
        cancelText="닫기"
        destroyOnClose
      >
        <Form form={approveForm} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="resolution"
            label="처리 결과"
            rules={[{ required: true, message: '처리 결과를 입력해주세요' }]}
          >
            <Input.TextArea rows={3} placeholder="처리 결과 내용" />
          </Form.Item>
          <Form.Item name="adjustmentAmount" label="조정 금액">
            <InputNumber
              style={{ width: '100%' }}
              formatter={(v) => `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
              parser={(v) => Number(v?.replace(/,/g, '') ?? 0)}
              placeholder="조정 금액 (선택)"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* ── 반려 모달 ──────────────────────────────────────────────────────────── */}
      <Modal
        title={`이의신청 반려 — ${rejectTarget?.agentName ?? ''}`}
        open={rejectOpen}
        onOk={handleReject}
        onCancel={() => setRejectOpen(false)}
        confirmLoading={rejecting}
        okText="반려"
        okButtonProps={{ danger: true }}
        cancelText="닫기"
        destroyOnClose
      >
        <Form form={rejectForm} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="resolution"
            label="처리 결과"
            rules={[{ required: true, message: '처리 결과를 입력해주세요' }]}
          >
            <Input.TextArea rows={3} placeholder="반려 사유를 입력해주세요" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
