import { useRef, useState } from 'react';
import {
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  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 {
  taxInvoiceApi,
  TaxInvoiceResp,
  TaxInvoiceSaveReq,
  TaxInvoiceSearchParam,
} from '@/api/tax-invoice';

const { MonthPicker } = DatePicker;

const INVOICE_TYPE_OPTIONS = [
  { label: '매출(공급)', value: 'SUPPLY' },
  { label: '매입(구매)', value: 'PURCHASE' },
];

const INVOICE_TYPE_TAG: Record<string, { color: string; label: string }> = {
  SUPPLY:   { color: 'blue',   label: '매출(공급)' },
  PURCHASE: { color: 'orange', label: '매입(구매)' },
};

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

  // 발행 모달
  const [issueOpen, setIssueOpen] = useState(false);
  const [issuing, setIssuing] = useState(false);
  const [issueForm] = Form.useForm<TaxInvoiceSaveReq & { issueDatePicker?: unknown; settleMonthPicker?: unknown }>();

  // 취소 모달
  const [cancelOpen, setCancelOpen] = useState(false);
  const [cancelling, setCancelling] = useState(false);
  const [cancelTarget, setCancelTarget] = useState<TaxInvoiceResp | null>(null);
  const [cancelForm] = Form.useForm<{ cancelReason: string }>();

  // ── 발행 처리 ────────────────────────────────────────────────────────────────
  const handleIssue = async () => {
    const values = await issueForm.validateFields();
    const payload: TaxInvoiceSaveReq = {
      invoiceNo:        values.invoiceNo,
      invoiceType:      values.invoiceType,
      issueDate:        values.issueDatePicker
        ? dayjs(values.issueDatePicker as Parameters<typeof dayjs>[0]).format('YYYY-MM-DD')
        : '',
      supplyAmount:     values.supplyAmount,
      taxAmount:        values.taxAmount,
      counterpartName:  values.counterpartName,
      counterpartBizNo: values.counterpartBizNo,
      counterpartRep:   values.counterpartRep,
      counterpartAddr:  values.counterpartAddr,
      agentId:          values.agentId,
      settleMonth:      values.settleMonthPicker
        ? dayjs(values.settleMonthPicker as Parameters<typeof dayjs>[0]).format('YYYYMM')
        : undefined,
      description:      values.description,
    };
    setIssuing(true);
    try {
      await taxInvoiceApi.create(payload);
      message.success('세금계산서가 발행되었습니다');
      setIssueOpen(false);
      issueForm.resetFields();
      actionRef.current?.reload();
    } finally {
      setIssuing(false);
    }
  };

  // ── 취소 처리 ────────────────────────────────────────────────────────────────
  const openCancel = (record: TaxInvoiceResp) => {
    setCancelTarget(record);
    cancelForm.resetFields();
    setCancelOpen(true);
  };

  const handleCancel = async () => {
    if (!cancelTarget) return;
    const { cancelReason } = await cancelForm.validateFields();
    setCancelling(true);
    try {
      await taxInvoiceApi.cancel(cancelTarget.invoiceId, cancelReason);
      message.success('세금계산서가 취소되었습니다');
      setCancelOpen(false);
      setCancelTarget(null);
      actionRef.current?.reload();
    } finally {
      setCancelling(false);
    }
  };

  // ── 컬럼 정의 ────────────────────────────────────────────────────────────────
  const columns: ProColumns<TaxInvoiceResp>[] = [
    {
      title: '발행번호',
      dataIndex: 'invoiceNo',
      width: 160,
      fixed: 'left',
      copyable: true,
    },
    {
      title: '유형',
      dataIndex: 'invoiceType',
      width: 110,
      valueType: 'select',
      valueEnum: Object.fromEntries(
        INVOICE_TYPE_OPTIONS.map((o) => [o.value, { text: o.label }]),
      ),
      render: (_, r) => {
        const info = INVOICE_TYPE_TAG[r.invoiceType] ?? { color: 'default', label: r.invoiceType };
        return <Tag color={info.color}>{info.label}</Tag>;
      },
    },
    {
      title: '발행일',
      dataIndex: 'issueDate',
      width: 110,
      search: false,
    },
    {
      title: '공급가액',
      dataIndex: 'supplyAmount',
      width: 130,
      align: 'right',
      search: false,
      render: (_, r) => <MoneyText value={r.supplyAmount} />,
    },
    {
      title: '세액',
      dataIndex: 'taxAmount',
      width: 110,
      align: 'right',
      search: false,
      render: (_, r) => <MoneyText value={r.taxAmount} />,
    },
    {
      title: '합계금액',
      dataIndex: 'totalAmount',
      width: 140,
      align: 'right',
      search: false,
      render: (_, r) => (
        <strong>
          <MoneyText value={r.totalAmount} />
        </strong>
      ),
    },
    {
      title: '거래처명',
      dataIndex: 'counterpartName',
      width: 140,
      search: false,
    },
    {
      title: '사업자번호',
      dataIndex: 'counterpartBizNo',
      width: 130,
      search: false,
    },
    {
      title: '설계사명',
      dataIndex: 'agentName',
      width: 100,
      search: false,
    },
    {
      title: '정산월',
      dataIndex: 'settleMonth',
      width: 90,
      valueType: 'dateMonth',
      fieldProps: { format: 'YYYYMM' },
    },
    {
      title: '상태',
      dataIndex: 'cancelDate',
      width: 80,
      search: false,
      render: (_, r) =>
        r.cancelDate ? (
          <Tag color="red">취소</Tag>
        ) : (
          <Tag color="green">발행</Tag>
        ),
    },
    {
      title: '액션',
      dataIndex: 'invoiceId',
      width: 90,
      fixed: 'right',
      search: false,
      render: (_, r) =>
        r.cancelDate ? null : (
          <PermissionButton
            menuCode="TAX_INVOICE"
            permCode="UPDATE"
            size="small"
            danger
            onClick={() => openCancel(r)}
          >
            취소
          </PermissionButton>
        ),
    },
  ];

  return (
    <PageContainer
      title="세금계산서 관리"
      description="매출·매입 세금계산서 발행 및 취소 관리"
    >
      <ProTable<TaxInvoiceResp, TaxInvoiceSearchParam>
        actionRef={actionRef}
        rowKey="invoiceId"
        columns={columns}
        scroll={{ x: 1400 }}
        request={async (params) => {
          const { current, pageSize, invoiceType, settleMonth } = params as any;
          const res = await taxInvoiceApi.list({
            invoiceType,
            settleMonth: settleMonth
              ? dayjs(settleMonth).format('YYYYMM')
              : undefined,
            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="issue"
            menuCode="TAX_INVOICE"
            permCode="CREATE"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              issueForm.resetFields();
              setIssueOpen(true);
            }}
          >
            세금계산서 발행
          </PermissionButton>,
        ]}
      />

      {/* ── 발행 모달 ──────────────────────────────────────────────────────────── */}
      <Modal
        title="세금계산서 발행"
        open={issueOpen}
        onOk={handleIssue}
        onCancel={() => setIssueOpen(false)}
        confirmLoading={issuing}
        okText="발행"
        cancelText="닫기"
        destroyOnClose
        width={640}
      >
        <Form form={issueForm} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="invoiceNo"
            label="발행번호"
            rules={[{ required: true, message: '발행번호를 입력해주세요' }]}
          >
            <Input placeholder="발행번호" />
          </Form.Item>

          <Form.Item
            name="invoiceType"
            label="유형"
            rules={[{ required: true, message: '유형을 선택해주세요' }]}
          >
            <Select placeholder="유형 선택" options={INVOICE_TYPE_OPTIONS} />
          </Form.Item>

          <Form.Item
            name="issueDatePicker"
            label="발행일"
            rules={[{ required: true, message: '발행일을 선택해주세요' }]}
          >
            <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" />
          </Form.Item>

          <Space style={{ width: '100%', display: 'flex', gap: 8 }}>
            <Form.Item
              name="supplyAmount"
              label="공급가액"
              rules={[{ required: true, message: '공급가액을 입력해주세요' }]}
              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="taxAmount"
              label="세액"
              rules={[{ required: true, message: '세액을 입력해주세요' }]}
              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="counterpartName"
            label="거래처명"
            rules={[{ required: true, message: '거래처명을 입력해주세요' }]}
          >
            <Input placeholder="거래처명" />
          </Form.Item>

          <Space style={{ width: '100%', display: 'flex', gap: 8 }}>
            <Form.Item
              name="counterpartBizNo"
              label="사업자번호"
              rules={[{ required: true, message: '사업자번호를 입력해주세요' }]}
              style={{ flex: 1 }}
            >
              <Input placeholder="000-00-00000" />
            </Form.Item>
            <Form.Item
              name="counterpartRep"
              label="대표자명"
              style={{ flex: 1 }}
            >
              <Input placeholder="대표자명" />
            </Form.Item>
          </Space>

          <Form.Item name="counterpartAddr" label="거래처 주소">
            <Input placeholder="거래처 주소" />
          </Form.Item>

          <Space style={{ width: '100%', display: 'flex', gap: 8 }}>
            <Form.Item name="agentId" label="설계사 ID" style={{ flex: 1 }}>
              <InputNumber
                style={{ width: '100%' }}
                placeholder="설계사 ID"
                min={1}
              />
            </Form.Item>
            <Form.Item name="settleMonthPicker" label="정산월" style={{ flex: 1 }}>
              <MonthPicker
                style={{ width: '100%' }}
                format="YYYYMM"
                placeholder="정산월 (선택)"
              />
            </Form.Item>
          </Space>

          <Form.Item name="description" label="비고">
            <Input.TextArea rows={2} placeholder="비고" />
          </Form.Item>
        </Form>
      </Modal>

      {/* ── 취소 모달 ──────────────────────────────────────────────────────────── */}
      <Modal
        title={`세금계산서 취소 — ${cancelTarget?.invoiceNo ?? ''}`}
        open={cancelOpen}
        onOk={handleCancel}
        onCancel={() => setCancelOpen(false)}
        confirmLoading={cancelling}
        okText="취소 처리"
        okButtonProps={{ danger: true }}
        cancelText="닫기"
        destroyOnClose
      >
        <Form form={cancelForm} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="cancelReason"
            label="취소 사유"
            rules={[{ required: true, message: '취소 사유를 입력해주세요' }]}
          >
            <Input.TextArea rows={3} placeholder="취소 사유를 입력해주세요" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
