import React, { useEffect, useMemo, useState } from 'react';
import { DatePicker, Input, InputNumber, Modal, Select } from 'antd';
import dayjs from 'dayjs';
import type { PaymentRecord } from '../types';
import { buildBankOptions, buildCompanyEntityOptions } from '../utils/payment';

export interface AddPaymentFormValues {
  paymentTime: string;
  customerName: string;
  companyEntity: string;
  bank: string;
  amount: number;
  remark: string;
}

interface AddPaymentModalProps {
  open: boolean;
  records: PaymentRecord[];
  onClose: () => void;
  onConfirm: (values: AddPaymentFormValues) => void;
}

const DEFAULT_FORM: AddPaymentFormValues = {
  paymentTime: '',
  customerName: '',
  companyEntity: '',
  bank: '',
  amount: 0,
  remark: '',
};

export function AddPaymentModal({ open, records, onClose, onConfirm }: AddPaymentModalProps) {
  const [form, setForm] = useState<AddPaymentFormValues>(DEFAULT_FORM);

  const companyEntityOptions = useMemo(() => buildCompanyEntityOptions(records), [records]);
  const bankOptions = useMemo(() => buildBankOptions(records), [records]);

  useEffect(() => {
    if (!open) setForm(DEFAULT_FORM);
  }, [open]);

  const handleConfirm = () => {
    if (!form.paymentTime || !form.customerName.trim() || !form.amount || form.amount <= 0) return;
    onConfirm({
      paymentTime: form.paymentTime,
      customerName: form.customerName.trim(),
      companyEntity: form.companyEntity.trim(),
      bank: form.bank.trim(),
      amount: Number(form.amount),
      remark: form.remark.trim(),
    });
  };

  const valid = Boolean(form.paymentTime && form.customerName.trim() && form.amount > 0);

  return (
    <Modal
      title="新增收款"
      open={open}
      onCancel={onClose}
      onOk={handleConfirm}
      okText="保存"
      cancelText="取消"
      okButtonProps={{ disabled: !valid }}
      destroyOnClose
      width={560}
      data-annotation-id="pr-add-modal"
    >
      <div className="pr-form-grid">
        <label className="vm-filter-field">
          <span>收款时间 <em className="pr-required">*</em></span>
          <DatePicker
            showTime
            style={{ width: '100%' }}
            placeholder="请选择到账时间"
            value={form.paymentTime ? dayjs(form.paymentTime) : null}
            onChange={(value) => setForm((prev) => ({
              ...prev,
              paymentTime: value ? value.format('YYYY-MM-DD HH:mm:ss') : '',
            }))}
          />
        </label>
        <label className="vm-filter-field">
          <span>汇款账户名 <em className="pr-required">*</em></span>
          <Input
            value={form.customerName}
            placeholder="请输入汇款账户名"
            aria-label="汇款账户名"
            onChange={(e) => setForm((prev) => ({ ...prev, customerName: e.target.value }))}
          />
        </label>
        <label className="vm-filter-field">
          <span>公司主体</span>
          <Select
            style={{ width: '100%' }}
            placeholder="请选择公司主体"
            aria-label="公司主体"
            value={form.companyEntity || undefined}
            onChange={(value) => setForm((prev) => ({ ...prev, companyEntity: value || '' }))}
            allowClear
            showSearch
            options={companyEntityOptions}
            filterOption={(input, option) =>
              (option?.label ?? '').toString().toLowerCase().includes(input.toLowerCase())}
          />
        </label>
        <label className="vm-filter-field">
          <span>银行</span>
          <Select
            style={{ width: '100%' }}
            placeholder="请选择收款银行"
            aria-label="银行"
            value={form.bank || undefined}
            onChange={(value) => setForm((prev) => ({ ...prev, bank: value || '' }))}
            allowClear
            showSearch
            options={bankOptions}
            filterOption={(input, option) =>
              (option?.label ?? '').toString().toLowerCase().includes(input.toLowerCase())}
          />
        </label>
        <label className="vm-filter-field">
          <span>金额（元） <em className="pr-required">*</em></span>
          <InputNumber
            style={{ width: '100%' }}
            className="tabular-nums"
            min={0}
            step={0.01}
            precision={2}
            value={form.amount || undefined}
            placeholder="请输入到账金额"
            aria-label="金额"
            onChange={(value) => setForm((prev) => ({ ...prev, amount: Number(value) || 0 }))}
          />
        </label>
        <label className="vm-filter-field pr-form-field--full">
          <span>备注</span>
          <Input.TextArea
            rows={3}
            value={form.remark}
            placeholder="选填，如银行转账、到账说明等"
            aria-label="备注"
            onChange={(e) => setForm((prev) => ({ ...prev, remark: e.target.value }))}
          />
        </label>
      </div>
    </Modal>
  );
}
