import React, { useEffect, useMemo, useState } from 'react';
import { X } from 'lucide-react';
import type { CustomerRecord } from '../types';
import { EMPTY_RISK_TAG_FORM, type MockUser, type RiskTagApplyForm, type RiskTagsByCustomer } from '../types/riskTag';
import { canApplyRiskTagByName, roleToTagCategory } from '../utils/permissions';
import { TAG_CATALOG_MAP } from '../utils/riskTagConstants';
import { defaultEffectiveTo, hasDuplicateActiveTag, todayDate, validateApplyForm } from '../utils/riskTagStore';
import { RiskTagApplyFormSection } from './RiskTagForm';

interface BatchRiskTagModalProps {
  open: boolean;
  records: CustomerRecord[];
  selectedIds: Set<string>;
  riskTagsByCustomer: RiskTagsByCustomer;
  currentUser: MockUser;
  onClose: () => void;
  onSubmit: (form: RiskTagApplyForm, customerIds: string[]) => string | null;
}

export function BatchRiskTagModal({
  open,
  records,
  selectedIds,
  riskTagsByCustomer,
  currentUser,
  onClose,
  onSubmit,
}: BatchRiskTagModalProps) {
  const [form, setForm] = useState<RiskTagApplyForm>(() => ({
    ...EMPTY_RISK_TAG_FORM,
    tagType: roleToTagCategory(currentUser),
    effectiveFrom: todayDate(),
    effectiveTo: defaultEffectiveTo(),
  }));
  const [error, setError] = useState('');

  const selectedRecords = useMemo(
    () => records.filter((record) => selectedIds.has(record.id)),
    [records, selectedIds],
  );

  useEffect(() => {
    if (!open) return;
    const nextType = roleToTagCategory(currentUser);
    setForm((prev) => {
      const keepTag = prev.tagName && canApplyRiskTagByName(currentUser, prev.tagName);
      const catalog = keepTag ? TAG_CATALOG_MAP[prev.tagName] : undefined;
      return {
        ...prev,
        tagType: nextType,
        tagName: keepTag ? prev.tagName : '',
        riskLevel: keepTag && catalog ? catalog.defaultLevel : '中',
      };
    });
  }, [currentUser, open]);

  if (!open) return null;

  const handleSubmit = () => {
    const validation = validateApplyForm(form);
    if (validation) {
      setError(validation);
      return;
    }
    if (!canApplyRiskTagByName(currentUser, form.tagName)) {
      setError('当前角色无权选择该标签');
      return;
    }
    const eligibleIds = selectedRecords
      .filter((record) => !hasDuplicateActiveTag(riskTagsByCustomer[record.id] ?? [], form.tagName))
      .map((record) => record.id);

    if (eligibleIds.length === 0) {
      setError('所选客户均已存在该标签');
      return;
    }

    const result = onSubmit({ ...form, tagType: roleToTagCategory(currentUser) }, eligibleIds);
    if (result) {
      setError(result);
      return;
    }
    setForm({
      ...EMPTY_RISK_TAG_FORM,
      tagType: roleToTagCategory(currentUser),
      effectiveFrom: todayDate(),
      effectiveTo: defaultEffectiveTo(),
    });
    setError('');
    onClose();
  };

  const skippedCount = selectedRecords.length - selectedRecords.filter(
    (record) => !hasDuplicateActiveTag(riskTagsByCustomer[record.id] ?? [], form.tagName),
  ).length;

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="vm-modal vm-modal-lg cm-batch-risk-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="cm-batch-risk-title"
        data-annotation-id="cm-batch-risk-tag-modal"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="vm-modal-header">
          <div>
            <h2 id="cm-batch-risk-title">批量打标</h2>
            <p>已选 {selectedRecords.length} 个客户 · 操作人 {currentUser.name}（{currentUser.department}）</p>
          </div>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>

        <div className="vm-edit-body">
          {error && <div className="cm-risk-error" role="alert">{error}</div>}

          <div className="cm-batch-selected">
            {selectedRecords.slice(0, 6).map((record) => (
              <span key={record.id} className="cm-batch-chip">{record.name}</span>
            ))}
            {selectedRecords.length > 6 && (
              <span className="cm-batch-chip">+{selectedRecords.length - 6}</span>
            )}
          </div>

          {form.tagName && skippedCount > 0 && (
            <div className="cm-risk-alert">
              其中 {skippedCount} 个客户已存在「{form.tagName}」，提交时将自动跳过。
            </div>
          )}

          <RiskTagApplyFormSection
            form={form}
            currentUser={currentUser}
            onChange={(patch) => setForm((prev) => ({ ...prev, ...patch }))}
          />
        </div>

        <footer className="vm-modal-footer">
          <button type="button" className="vm-btn vm-btn-ghost" onClick={onClose} data-vm-icon="x">取消</button>
          <button type="button" className="vm-btn vm-btn-primary" onClick={handleSubmit} data-vm-icon="send">
            提交批量打标
          </button>
        </footer>
      </div>
    </div>
  );
}
