import React, { useEffect, useMemo, useState } from 'react';
import { Clock, Plus, Tag, X } from 'lucide-react';
import type { CustomerRecord } from '../types';
import type {
  CustomerRiskTag,
  MockUser,
  RiskTagApplyForm,
  RiskTagOperationLog,
} from '../types/riskTag';
import { canApproveRiskTag, canApplyRiskTagByName, canRemoveRiskTag, roleToTagCategory } from '../utils/permissions';
import { TAG_CATALOG_MAP } from '../utils/riskTagConstants';
import { EMPTY_RISK_TAG_FORM } from '../types/riskTag';
import {
  defaultEffectiveTo,
  formatNow,
  hasDuplicateActiveTag,
  todayDate,
  validateApplyForm,
} from '../utils/riskTagStore';
import { RiskTagApplyFormSection, RiskTagDetailCard } from './RiskTagForm';

type DrawerTab = 'tags' | 'add' | 'logs';

interface RiskTagDrawerProps {
  open: boolean;
  record: CustomerRecord | null;
  tags: CustomerRiskTag[];
  logs: RiskTagOperationLog[];
  currentUser: MockUser;
  onClose: () => void;
  onApply: (form: RiskTagApplyForm) => string | null;
  onRemove: (tagId: string, reason: string) => string | null;
  onApprove: (tagId: string, approved: boolean, rejectReason?: string) => string | null;
}

export function RiskTagDrawer({
  open,
  record,
  tags,
  logs,
  currentUser,
  onClose,
  onApply,
  onRemove,
  onApprove,
}: RiskTagDrawerProps) {
  const [tab, setTab] = useState<DrawerTab>('tags');
  const [detailId, setDetailId] = useState<string | null>(null);
  const [form, setForm] = useState<RiskTagApplyForm>(EMPTY_RISK_TAG_FORM);
  const [removeReason, setRemoveReason] = useState('');
  const [removeTargetId, setRemoveTargetId] = useState<string | null>(null);
  const [rejectReason, setRejectReason] = useState('');
  const [approveTargetId, setApproveTargetId] = useState<string | null>(null);
  const [error, setError] = useState('');

  const detailTag = useMemo(
    () => tags.find((tag) => tag.id === detailId) ?? null,
    [tags, detailId],
  );

  const customerLogs = useMemo(
    () => logs.filter((log) => log.customerId === record?.id),
    [logs, record?.id],
  );

  const disabledTagNames = useMemo(
    () => tags
      .filter((tag) => tag.status === '生效中' || tag.status === '待审批' || tag.status === '待确认')
      .map((tag) => tag.tagName),
    [tags],
  );

  /** 顶部切换操作角色时，同步打标表单中的标签类型与可选标签 */
  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 || !record) return null;

  const resetAddForm = () => {
    setForm({
      ...EMPTY_RISK_TAG_FORM,
      tagType: roleToTagCategory(currentUser),
      effectiveFrom: todayDate(),
      effectiveTo: defaultEffectiveTo(),
    });
    setError('');
  };

  const handleSubmitApply = () => {
    const validation = validateApplyForm(form);
    if (validation) {
      setError(validation);
      return;
    }
    if (hasDuplicateActiveTag(tags, form.tagName)) {
      setError('该客户已存在同名有效标签');
      return;
    }
    const result = onApply({ ...form, tagType: roleToTagCategory(currentUser) });
    if (result) {
      setError(result);
      return;
    }
    resetAddForm();
    setTab('tags');
  };

  const handleConfirmRemove = () => {
    if (!removeTargetId) return;
    if (removeReason.trim().length < 5) {
      setError('移除原因至少 5 个字');
      return;
    }
    const result = onRemove(removeTargetId, removeReason.trim());
    if (result) {
      setError(result);
      return;
    }
    setRemoveTargetId(null);
    setRemoveReason('');
    setError('');
  };

  const handleConfirmApprove = (approved: boolean) => {
    if (!approveTargetId) return;
    if (!approved && !rejectReason.trim()) {
      setError('请填写驳回原因');
      return;
    }
    const result = onApprove(approveTargetId, approved, rejectReason.trim() || undefined);
    if (result) {
      setError(result);
      return;
    }
    setApproveTargetId(null);
    setRejectReason('');
    setError('');
  };

  return (
    <div className="cm-drawer-backdrop" role="presentation" onClick={onClose}>
      <aside
        className="cm-drawer"
        role="dialog"
        aria-modal="true"
        aria-labelledby="cm-risk-drawer-title"
        data-annotation-id="cm-risk-tag-drawer"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="cm-drawer-header">
          <div>
            <h2 id="cm-risk-drawer-title">风险标签管理</h2>
            <p>{record.name}（{record.code}）</p>
          </div>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>

        <nav className="cm-drawer-tabs" aria-label="标签管理分区">
          <button type="button" className={tab === 'tags' ? 'is-active' : ''} onClick={() => setTab('tags')}>
            <Tag size={14} aria-hidden /> 当前标签
          </button>
          <button type="button" className={tab === 'add' ? 'is-active' : ''} onClick={() => { setTab('add'); resetAddForm(); }}>
            <Plus size={14} aria-hidden /> 新增标签
          </button>
          <button type="button" className={tab === 'logs' ? 'is-active' : ''} onClick={() => setTab('logs')}>
            <Clock size={14} aria-hidden /> 操作日志
          </button>
        </nav>

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

          {tab === 'tags' && (
            <div className="cm-risk-tag-list">
              {tags.length === 0 && <p className="cm-muted">暂无风险标签，可切换到「新增标签」打标。</p>}
              {tags.map((tag) => (
                <article key={tag.id} className="cm-risk-tag-item">
                  <div className="cm-risk-tag-item-head">
                    <div>
                      <strong>{tag.tagName}</strong>
                      <span className="cm-risk-tag-meta">{tag.tagType} · {tag.riskLevel}</span>
                    </div>
                    <span className={`cm-risk-status cm-risk-status--${tag.status}`}>{tag.status}</span>
                  </div>
                  <p className="cm-risk-tag-reason">{tag.reason}</p>
                  <div className="cm-risk-tag-item-actions">
                    <button type="button" className="vm-btn vm-btn-link" onClick={() => setDetailId(tag.id)}>
                      查看详情
                    </button>
                    {tag.status === '待审批' && canApproveRiskTag(currentUser) && (
                      <>
                        <button type="button" className="vm-btn vm-btn-link" onClick={() => { setApproveTargetId(tag.id); setRejectReason(''); setError(''); }}>
                          审批
                        </button>
                      </>
                    )}
                    {tag.status === '生效中' && canRemoveRiskTag(currentUser, tag.tagType) && (
                      <button
                        type="button"
                        className="vm-btn vm-btn-link cm-link-danger"
                        onClick={() => { setRemoveTargetId(tag.id); setRemoveReason(''); setError(''); }}
                      >
                        移除
                      </button>
                    )}
                  </div>
                </article>
              ))}
            </div>
          )}

          {tab === 'add' && (
            <RiskTagApplyFormSection
              form={form}
              currentUser={currentUser}
              onChange={(patch) => setForm((prev) => ({ ...prev, ...patch }))}
              disabledTagNames={disabledTagNames}
            />
          )}

          {tab === 'logs' && (
            <ol className="cm-risk-log-list">
              {customerLogs.length === 0 && <li className="cm-muted">暂无操作日志</li>}
              {customerLogs.map((log) => (
                <li key={log.id}>
                  <div className="cm-risk-log-head">
                    <strong>{log.action}</strong>
                    <time>{log.createdAt}</time>
                  </div>
                  <p>{log.detail}</p>
                  <span className="cm-muted">{log.operator} · {log.tagName}</span>
                </li>
              ))}
            </ol>
          )}
        </div>

        <footer className="cm-drawer-footer">
          {tab === 'add' ? (
            <>
              <button type="button" className="vm-btn vm-btn-ghost" data-vm-icon="x" onClick={() => { setTab('tags'); resetAddForm(); }}>取消</button>
              <button type="button" className="vm-btn vm-btn-primary" onClick={handleSubmitApply} data-vm-icon="send">提交打标</button>
            </>
          ) : (
            <button type="button" className="vm-btn vm-btn-ghost" onClick={onClose} data-vm-icon="x">关闭</button>
          )}
        </footer>

        {detailTag && (
          <div className="cm-drawer-subpanel">
            <RiskTagDetailCard tag={detailTag} onClose={() => setDetailId(null)} />
          </div>
        )}

        {removeTargetId && (
          <div className="cm-drawer-overlay-panel">
            <h3>移除标签</h3>
            <p className="cm-modal-hint">移除操作将写入审计日志，并同步更新列表展示。</p>
            <textarea
              className="vm-input cm-textarea"
              rows={3}
              value={removeReason}
              placeholder="请填写移除原因（至少 5 字）"
              onChange={(e) => setRemoveReason(e.target.value)}
            />
            <div className="cm-drawer-overlay-actions">
              <button type="button" className="vm-btn vm-btn-ghost" onClick={() => setRemoveTargetId(null)} data-vm-icon="x">取消</button>
              <button type="button" className="vm-btn vm-btn-primary cm-link-danger-btn" onClick={handleConfirmRemove} data-vm-icon="trash">确认移除</button>
            </div>
          </div>
        )}

        {approveTargetId && (
          <div className="cm-drawer-overlay-panel">
            <h3>审批标签</h3>
            <p className="cm-modal-hint">高风险标签需法务/风控确认后方可生效。</p>
            <textarea
              className="vm-input cm-textarea"
              rows={2}
              value={rejectReason}
              placeholder="若驳回，请填写原因"
              onChange={(e) => setRejectReason(e.target.value)}
            />
            <div className="cm-drawer-overlay-actions">
              <button type="button" className="vm-btn vm-btn-ghost" onClick={() => setApproveTargetId(null)} data-vm-icon="x">取消</button>
              <button type="button" className="vm-btn vm-btn-ghost" onClick={() => handleConfirmApprove(false)} data-vm-icon="x">驳回</button>
              <button type="button" className="vm-btn vm-btn-primary" onClick={() => handleConfirmApprove(true)} data-vm-icon="send">通过</button>
            </div>
          </div>
        )}
      </aside>
    </div>
  );
}
