import { useEffect, useState } from 'react';
import { Image, Input, Modal, Space, Typography } from 'antd';
import { PAYMENT_PROOF_IMAGE_MAX_COUNT } from '@dukang/shared-types';
import MultiImageUpload from './MultiImageUpload';

export function parsePaymentProofUrls(raw: unknown): string[] {
  if (!Array.isArray(raw)) return [];
  return raw.map((u) => String(u ?? '').trim()).filter(Boolean);
}

export function PaymentProofGallery({ urls }: { urls?: unknown }) {
  const list = parsePaymentProofUrls(urls);
  if (!list.length) return <>—</>;
  return (
    <Image.PreviewGroup>
      <Space wrap size={8}>
        {list.map((url, index) => (
          <Image
            key={`${url}-${index}`}
            src={url}
            width={72}
            height={72}
            style={{ objectFit: 'cover', borderRadius: 6, border: '1px solid #f0f0f0' }}
          />
        ))}
      </Space>
    </Image.PreviewGroup>
  );
}

type FinancePayProofModalProps = {
  open: boolean;
  title: string;
  hint: string;
  okText: string;
  confirmLoading?: boolean;
  onCancel: () => void;
  onOk: (payload: { paymentRef?: string; paymentProofUrls?: string[] }) => Promise<void>;
};

export function FinancePayProofModal({
  open,
  title,
  hint,
  okText,
  confirmLoading,
  onCancel,
  onOk,
}: FinancePayProofModalProps) {
  const [paymentRef, setPaymentRef] = useState('');
  const [proofUrls, setProofUrls] = useState<string[]>([]);

  useEffect(() => {
    if (open) {
      setPaymentRef('');
      setProofUrls([]);
    }
  }, [open]);

  return (
    <Modal
      title={title}
      open={open}
      okText={okText}
      cancelText="取消"
      confirmLoading={confirmLoading}
      destroyOnClose
      width={480}
      onCancel={onCancel}
      onOk={async () => {
        await onOk({
          paymentRef: paymentRef.trim() || undefined,
          paymentProofUrls: proofUrls.length ? proofUrls : undefined,
        });
      }}
    >
      <Typography.Paragraph style={{ marginBottom: 12 }}>{hint}</Typography.Paragraph>
      <Input
        placeholder="打款凭证号（可选）"
        value={paymentRef}
        onChange={(e) => setPaymentRef(e.target.value)}
        style={{ marginBottom: 12 }}
      />
      <Typography.Text type="secondary">打款凭证照片（可选，银行转账回单等）</Typography.Text>
      <div style={{ marginTop: 8 }}>
        <MultiImageUpload
          bizType="PAYMENT_PROOF"
          value={proofUrls}
          onChange={setProofUrls}
          maxCount={PAYMENT_PROOF_IMAGE_MAX_COUNT}
          buttonText="上传凭证照片"
          tip={`最多 ${PAYMENT_PROOF_IMAGE_MAX_COUNT} 张，支持一次选择多张`}
        />
      </div>
    </Modal>
  );
}
