import React, { useMemo, useRef } from 'react';
import { Upload, X } from 'lucide-react';
import type { MockUser, RiskTagApplyForm, RiskTagAttachment } from '../types/riskTag';
import { TAG_CATALOG_MAP, TAG_GROUPS } from '../utils/riskTagConstants';
import { canApplyRiskTag, roleToTagCategory } from '../utils/permissions';
import { formatNow, nextId } from '../utils/riskTagStore';

interface RiskTagApplyFormSectionProps {
  form: RiskTagApplyForm;
  currentUser: MockUser;
  onChange: (patch: Partial<RiskTagApplyForm>) => void;
  disabledTagNames?: string[];
}

export function RiskTagApplyFormSection({
  form,
  currentUser,
  onChange,
  disabledTagNames = [],
}: RiskTagApplyFormSectionProps) {
  const inputRef = useRef<HTMLInputElement>(null);

  const tagType = roleToTagCategory(currentUser);

  const selectableGroups = useMemo(
    () => TAG_GROUPS.map((group) => ({
      ...group,
      tags: group.tagNames
        .map((name) => TAG_CATALOG_MAP[name])
        .filter((tag) => tag && canApplyRiskTag(currentUser, tag)),
    })).filter((group) => group.tags.length > 0),
    [currentUser],
  );

  const handleTagNameChange = (tagName: string) => {
    const catalog = TAG_CATALOG_MAP[tagName];
    onChange({
      tagName,
      tagType,
      riskLevel: catalog?.defaultLevel ?? '中',
    });
  };

  const handleUpload = (file: File) => {
    const attachment: RiskTagAttachment = {
      id: nextId('att'),
      name: file.name,
      size: `${Math.max(1, Math.round(file.size / 1024))} KB`,
      uploadedAt: formatNow(),
    };
    onChange({ attachments: [...form.attachments, attachment] });
  };

  const removeAttachment = (id: string) => {
    onChange({ attachments: form.attachments.filter((item) => item.id !== id) });
  };

  const needsApproval = form.riskLevel === '高' || form.riskLevel === '极高';
  const levelLocked = Boolean(form.tagName);

  return (
    <div className="cm-risk-form">
      <div className="cm-risk-form-grid">
        <label className="cm-form-field cm-risk-form-full">
          <span className="cm-form-label">标签名称 <span className="cm-required">*</span></span>
          <select
            className="vm-input"
            value={form.tagName}
            onChange={(e) => handleTagNameChange(e.target.value)}
          >
            <option value="">请选择标签</option>
            {selectableGroups.map((group) => (
              <optgroup key={group.groupName} label={group.groupName}>
                {group.tags.map((item) => (
                  <option
                    key={item.tagName}
                    value={item.tagName}
                    disabled={disabledTagNames.includes(item.tagName)}
                  >
                    {item.tagName}
                    {disabledTagNames.includes(item.tagName) ? '（已存在）' : ''}
                  </option>
                ))}
              </optgroup>
            ))}
          </select>
          {selectableGroups.length === 0 && (
            <span className="cm-form-hint">当前角色无可选标签，请切换法务/财务/运维/风控角色</span>
          )}
        </label>
        <label className="cm-form-field">
          <span className="cm-form-label">标签类型 <span className="cm-required">*</span></span>
          <select
            className="vm-input cm-input-disabled"
            value={tagType}
            disabled
            aria-readonly="true"
          >
            <option value={tagType}>{tagType}</option>
          </select>
        </label>
        <label className="cm-form-field">
          <span className="cm-form-label">风险级别 <span className="cm-required">*</span></span>
          <select
            className={`vm-input ${levelLocked ? 'cm-input-disabled' : ''}`}
            value={form.riskLevel}
            disabled={levelLocked}
            aria-readonly={levelLocked}
            onChange={(e) => onChange({ riskLevel: e.target.value as RiskTagApplyForm['riskLevel'] })}
          >
            <option value={form.riskLevel}>{form.riskLevel}</option>
          </select>
          {levelLocked && (
            <span className="cm-form-hint">根据标签规范自动带出</span>
          )}
        </label>
        <label className="cm-form-field">
          <span className="cm-form-label">生效时间 <span className="cm-required">*</span></span>
          <input
            type="date"
            className="vm-input"
            value={form.effectiveFrom}
            onChange={(e) => onChange({ effectiveFrom: e.target.value })}
          />
        </label>
        <label className="cm-form-field">
          <span className="cm-form-label">有效期至 <span className="cm-required">*</span></span>
          <input
            type="date"
            className="vm-input"
            value={form.effectiveTo}
            onChange={(e) => onChange({ effectiveTo: e.target.value })}
          />
        </label>
      </div>

      <label className="cm-form-field cm-risk-form-full">
        <span className="cm-form-label">原因说明 <span className="cm-required">*</span></span>
        <textarea
          className="vm-input cm-textarea"
          rows={3}
          value={form.reason}
          placeholder="请说明打标依据，供法务/财务/风控审批留痕（至少 10 字）"
          onChange={(e) => onChange({ reason: e.target.value })}
        />
      </label>

      <div className="cm-form-field cm-risk-form-full">
        <span className="cm-form-label">附件（选填）</span>
        <button
          type="button"
          className="vm-upload-zone cm-risk-upload"
          onClick={() => inputRef.current?.click()}
        >
          <Upload size={20} aria-hidden />
          <p>上传审批依据、合同、对账单等</p>
          <p className="hint">支持 .pdf、.jpg、.png、.xlsx</p>
          <input
            ref={inputRef}
            type="file"
            accept=".pdf,.jpg,.jpeg,.png,.xlsx,.xls"
            className="sr-only"
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) handleUpload(file);
              e.target.value = '';
            }}
          />
        </button>
        {form.attachments.length > 0 && (
          <ul className="cm-risk-attachments">
            {form.attachments.map((file) => (
              <li key={file.id}>
                <span>{file.name}</span>
                <span className="cm-muted">{file.size}</span>
                <button type="button" className="vm-btn vm-btn-link" onClick={() => removeAttachment(file.id)}>
                  移除
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>

      {needsApproval && (
        <div className="cm-risk-alert">
          高风险标签提交后将进入<strong>审批流程</strong>，需法务或风控人员确认后才会在列表生效。
        </div>
      )}
    </div>
  );
}

interface RiskTagDetailCardProps {
  tag: import('../types/riskTag').CustomerRiskTag;
  onClose?: () => void;
}

export function RiskTagDetailCard({ tag, onClose }: RiskTagDetailCardProps) {
  const groupName = TAG_CATALOG_MAP[tag.tagName]?.groupName;

  return (
    <div className="cm-risk-detail-card">
      <div className="cm-risk-detail-head">
        <div>
          <h4>{tag.tagName}</h4>
          <span className={`cm-risk-status cm-risk-status--${tag.status}`}>{tag.status}</span>
        </div>
        {onClose && (
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭详情">
            <X size={16} aria-hidden />
          </button>
        )}
      </div>
      <dl className="cm-risk-detail-list">
        {groupName && <div><dt>标签分类</dt><dd>{groupName}</dd></div>}
        <div><dt>标签类型</dt><dd>{tag.tagType}</dd></div>
        <div><dt>风险级别</dt><dd>{tag.riskLevel}</dd></div>
        <div><dt>生效时间</dt><dd>{tag.effectiveFrom}</dd></div>
        <div><dt>有效期至</dt><dd>{tag.effectiveTo}</dd></div>
        <div><dt>操作人</dt><dd>{tag.operator}</dd></div>
        <div><dt>提交时间</dt><dd>{tag.createdAt}</dd></div>
        {tag.approver && <div><dt>审批人</dt><dd>{tag.approver}</dd></div>}
        {tag.approvedAt && <div><dt>审批时间</dt><dd>{tag.approvedAt}</dd></div>}
        {tag.rejectReason && <div><dt>驳回原因</dt><dd>{tag.rejectReason}</dd></div>}
        <div className="cm-risk-detail-full"><dt>原因说明</dt><dd>{tag.reason}</dd></div>
        {tag.attachments.length > 0 && (
          <div className="cm-risk-detail-full">
            <dt>附件</dt>
            <dd>
              <ul className="cm-risk-attachments">
                {tag.attachments.map((file) => (
                  <li key={file.id}>{file.name}（{file.size}）</li>
                ))}
              </ul>
            </dd>
          </div>
        )}
      </dl>
    </div>
  );
}
