'use client';
import { useState, useEffect, useRef, useCallback } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { useUser } from '../../layout';
import { authFetch, STATUS_NAMES, ROLE_NAMES } from '@/lib/auth-client';

export default function ContractDetailPage() {
  const router = useRouter();
  const params = useParams();
  const user = useUser();
  const contractId = params.id;

  const [contract, setContract] = useState(null);
  const [loading, setLoading] = useState(true);
  const [toast, setToast] = useState(null);

  // Approval state
  const [opinion, setOpinion] = useState('');
  const [approving, setApproving] = useState(false);

  // Resubmit state
  const [editing, setEditing] = useState(false);
  const [editForm, setEditForm] = useState({});
  const [editFiles, setEditFiles] = useState([]);
  const [editDragging, setEditDragging] = useState(false);
  const editFileInputRef = useRef(null);
  const [resubmitting, setResubmitting] = useState(false);

  // Partners for resubmit
  const [partners, setPartners] = useState([]);
  const [supervisors, setSupervisors] = useState([]);
  const [partnerSearch, setPartnerSearch] = useState('');
  const [selectedPartnerName, setSelectedPartnerName] = useState('');
  const [partnerDropdownOpen, setPartnerDropdownOpen] = useState(false);
  const partnerRef = useRef(null);

  const showToast = (message, type = 'success') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000);
  };

  const fetchContract = useCallback(async () => {
    try {
      const res = await authFetch(`/api/contracts/${contractId}`);
      const data = await res.json();
      if (!res.ok) {
        showToast(data.error || '加载失败', 'error');
        return;
      }
      setContract(data.contract || data);
    } catch (err) {
      showToast('加载合同详情失败', 'error');
    } finally {
      setLoading(false);
    }
  }, [contractId]);

  useEffect(() => {
    fetchContract();
  }, [fetchContract]);

  // Load partners and supervisors for resubmit
  useEffect(() => {
    if (editing) {
      authFetch('/api/partners')
        .then(r => r.json())
        .then(data => setPartners(data.partners || data || []))
        .catch(() => {});

      authFetch('/api/users')
        .then(r => r.json())
        .then(data => {
          const list = (data || []).filter(u => u.role === 'supervisor' && u.status === 1);
          setSupervisors(list);
        })
        .catch(() => {});
    }
  }, [editing]);

  // Close partner dropdown on outside click
  useEffect(() => {
    const handleClick = (e) => {
      if (partnerRef.current && !partnerRef.current.contains(e.target)) {
        setPartnerDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  const formatDate = (dateStr) => {
    if (!dateStr) return '-';
    const d = new Date(dateStr);
    return d.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
  };

  const formatDateTime = (dateStr) => {
    if (!dateStr) return '';
    const d = new Date(dateStr);
    return d.toLocaleString('zh-CN', {
      year: 'numeric', month: '2-digit', day: '2-digit',
      hour: '2-digit', minute: '2-digit'
    });
  };

  const formatCurrency = (amount) => {
    if (amount === null || amount === undefined) return '-';
    return Number(amount).toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' });
  };

  // Can current user approve?
  const canApprove = () => {
    if (!contract || !user) return false;
    const { status, department_id } = contract;
    const { role, department_id: userDeptId } = user;
    if (status === 'pending_supervisor' && role === 'supervisor' && userDeptId === department_id) return true;
    if (status === 'pending_finance' && role === 'finance') return true;
    if (status === 'pending_secretary' && role === 'secretary') return true;
    return false;
  };

  // Can resubmit?
  const canResubmit = () => {
    if (!contract || !user) return false;
    return contract.status === 'rejected' && user.id === contract.creator_id;
  };

  // Approve/Reject
  const handleApproval = async (approved) => {
    setApproving(true);
    try {
      const res = await authFetch(`/api/contracts/${contractId}/approve`, {
        method: 'POST',
        body: JSON.stringify({ approved, opinion }),
      });
      const data = await res.json();
      if (!res.ok) {
        showToast(data.error || '操作失败', 'error');
      } else {
        showToast(approved ? '已通过审批' : '已驳回');
        setOpinion('');
        fetchContract();
      }
    } catch (err) {
      showToast('操作失败，请重试', 'error');
    } finally {
      setApproving(false);
    }
  };

  // Start editing for resubmit
  const startEditing = () => {
    let start = '';
    let end = '';
    if (contract.contract_years && contract.contract_years.includes(' ~ ')) {
      const parts = contract.contract_years.split(' ~ ');
      start = parts[0] || '';
      end = parts[1] || '';
    }

    setEditForm({
      project_name: contract.project_name || '',
      project_leader: contract.project_leader || '',
      sign_date: contract.sign_date ? contract.sign_date.substring(0, 10) : '',
      partner_id: contract.partner_id || '',
      contract_content: contract.contract_content || '',
      cooperate_start: start,
      cooperate_end: end,
      contract_amount: contract.contract_amount || '',
      estimated_profit: contract.estimated_profit || '',
      payment_type: contract.payment_type || 'receive',
    });
    setSelectedPartnerName(contract.partner_name || '');
    setPartnerSearch(contract.partner_name || '');
    setEditing(true);
  };

  const handleEditChange = (field, value) => {
    setEditForm(prev => {
      const updated = { ...prev, [field]: value };
      if (field === 'payment_type' && value === 'pay') {
        updated.estimated_profit = '';
      }
      return updated;
    });
  };

  // Resubmit
  const handleResubmit = async () => {
    if (!editForm.project_name?.trim()) {
      showToast('请输入项目名称', 'error');
      return;
    }
    if (!editForm.partner_id) {
      showToast('请选择合作单位', 'error');
      return;
    }
    if (!editForm.contract_amount || Number(editForm.contract_amount) <= 0) {
      showToast('请输入合同金额', 'error');
      return;
    }
    if (!editForm.cooperate_start || !editForm.cooperate_end) {
      showToast('请选择完整的合作时间范围', 'error');
      return;
    }
    if (editForm.cooperate_start > editForm.cooperate_end) {
      showToast('合作开始时间不能晚于结束时间', 'error');
      return;
    }

    setResubmitting(true);
    try {
      const body = {
        project_name: editForm.project_name,
        project_leader: editForm.project_leader || null,
        sign_date: editForm.sign_date || null,
        partner_id: editForm.partner_id,
        contract_content: editForm.contract_content || null,
        contract_years: editForm.cooperate_start && editForm.cooperate_end ? `${editForm.cooperate_start} ~ ${editForm.cooperate_end}` : null,
        contract_amount: Number(editForm.contract_amount),
        estimated_profit: editForm.estimated_profit === '' || editForm.estimated_profit === null || editForm.estimated_profit === undefined ? null : Number(editForm.estimated_profit),
        payment_type: editForm.payment_type,
      };

      const res = await authFetch(`/api/contracts/${contractId}`, {
        method: 'PUT',
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok) {
        showToast(data.error || '重新提交失败', 'error');
      } else {
        // Upload new files if any
        for (const file of editFiles) {
          const formData = new FormData();
          formData.append('file', file);
          formData.append('contract_id', contractId);
          await authFetch('/api/upload', { method: 'POST', body: formData });
        }
        showToast('已重新提交审批');
        setEditing(false);
        setEditFiles([]);
        fetchContract();
      }
    } catch (err) {
      showToast('提交失败，请重试', 'error');
    } finally {
      setResubmitting(false);
    }
  };

  const editFilteredPartners = partners.filter(p =>
    (p.name || '').toLowerCase().includes(partnerSearch.toLowerCase())
  );

  const selectPartner = (partner) => {
    setEditForm(prev => ({ ...prev, partner_id: partner.id }));
    setSelectedPartnerName(partner.name);
    setPartnerSearch(partner.name);
    setPartnerDropdownOpen(false);
  };

  // File handling for resubmit
  const handleEditFiles = (newFiles) => {
    setEditFiles(prev => [...prev, ...Array.from(newFiles)]);
  };

  const formatFileSize = (bytes) => {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
  };

  // Timeline step state
  const getStepState = (stepIndex) => {
    if (!contract) return 'pending';
    const { status, supervisor_approved, finance_approved, secretary_approved } = contract;

    switch (stepIndex) {
      case 0: // 提交
        return 'completed';
      case 1: // 初审
        if (supervisor_approved === 1) return 'completed';
        if (supervisor_approved === 0) return 'rejected';
        if (status === 'pending_supervisor') return 'current';
        if (['pending_finance', 'pending_secretary', 'approved'].includes(status)) return 'completed';
        return 'pending';
      case 2: // 财务审核
        if (finance_approved === 1) return 'completed';
        if (finance_approved === 0) return 'rejected';
        if (status === 'pending_finance') return 'current';
        if (['pending_secretary', 'approved'].includes(status)) return 'completed';
        return 'pending';
      case 3: // 终审
        if (secretary_approved === 1) return 'completed';
        if (secretary_approved === 0) return 'rejected';
        if (status === 'pending_secretary') return 'current';
        if (status === 'approved') return 'completed';
        return 'pending';
      default:
        return 'pending';
    }
  };

  const getLineState = (stepIndex) => {
    const currentState = getStepState(stepIndex);
    const nextState = getStepState(stepIndex + 1);
    if (currentState === 'completed' && nextState === 'completed') return 'completed';
    if (currentState === 'completed' && nextState === 'current') return 'active';
    return '';
  };

  const getStepIcon = (state) => {
    switch (state) {
      case 'completed': return '✓';
      case 'rejected': return '✕';
      case 'current': return '⋯';
      default: return '';
    }
  };

  const timelineSteps = [
    {
      label: '提交',
      approver: contract?.creator_name,
      time: contract?.created_at,
    },
    {
      label: '初审',
      approver: contract?.supervisor_name,
      time: contract?.supervisor_time,
    },
    {
      label: '财务审核',
      approver: contract?.finance_name,
      time: contract?.finance_time,
    },
    {
      label: '终审',
      approver: contract?.secretary_name,
      time: contract?.secretary_time,
    },
  ];

  if (loading) {
    return (
      <div className="loading-overlay">
        <div className="loading-spinner"></div>
      </div>
    );
  }

  if (!contract) {
    return (
      <div className="empty-state">
        <div className="empty-state-icon">📋</div>
        <div className="empty-state-text">合同不存在或已被删除</div>
        <button className="btn btn-primary" style={{ marginTop: 16 }} onClick={() => router.push('/dashboard/contracts')}>
          返回列表
        </button>
      </div>
    );
  }

  return (
    <div className="animate-fadeIn">
      {/* Toast */}
      {toast && (
        <div className="toast-container">
          <div className={`toast toast-${toast.type}`}>
            {toast.type === 'success' ? '✅' : '❌'} {toast.message}
          </div>
        </div>
      )}

      {/* Header */}
      <div className="page-header">
        <div>
          <h1 className="page-title">{contract.project_name}</h1>
          <p className="page-subtitle">合同编号：{contract.contract_no || contract.id}</p>
        </div>
        <div style={{ display: 'flex', gap: 12 }}>
          <span className={`status-badge status-${contract.status}`}>
            {STATUS_NAMES[contract.status] || contract.status}
          </span>
          <button className="btn btn-outline" onClick={() => router.push('/dashboard/contracts')}>
            ← 返回列表
          </button>
        </div>
      </div>

      {/* Approval Timeline */}
      <div className="card" style={{ marginBottom: 20 }}>
        <div className="card-header">
          <h3 className="card-title">📊 审批流程</h3>
        </div>
        <div className="card-body">
          <div className="approval-timeline">
            {timelineSteps.map((step, index) => {
              const state = getStepState(index);
              return (
                <div key={index} style={{ display: 'flex', alignItems: 'center' }}>
                  <div className="timeline-step">
                    <div className={`timeline-dot ${state}`}>
                      {state === 'pending' ? (index + 1) : getStepIcon(state)}
                    </div>
                    <div className="timeline-label">{step.label}</div>
                    {(state === 'completed' || state === 'rejected') && step.approver && (
                      <div className="timeline-info">
                        {step.approver}
                        {step.time && <br />}
                        {step.time && formatDateTime(step.time)}
                      </div>
                    )}
                    {state === 'current' && (
                      <div className="timeline-info" style={{ color: 'var(--primary)' }}>
                        等待审批中...
                      </div>
                    )}
                  </div>
                  {index < timelineSteps.length - 1 && (
                    <div className={`timeline-line ${getLineState(index)}`}></div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Contract Details */}
      <div className="card" style={{ marginBottom: 20 }}>
        <div className="card-header">
          <h3 className="card-title">📋 合同详情</h3>
        </div>
        <div className="card-body">
          <div className="detail-grid">
            <div className="detail-item">
              <div className="detail-label">项目名称</div>
              <div className="detail-value">{contract.project_name || '-'}</div>
            </div>
            <div className="detail-item">
              <div className="detail-label">项目负责人</div>
              <div className="detail-value">{contract.project_leader || '-'}</div>
            </div>
            <div className="detail-item">
              <div className="detail-label">合作单位</div>
              <div className="detail-value">{contract.partner_name || '-'}</div>
            </div>
            <div className="detail-item">
              <div className="detail-label">签订时间</div>
              <div className="detail-value">{formatDate(contract.sign_date)}</div>
            </div>
            <div className="detail-item">
              <div className="detail-label">合同金额</div>
              <div className="detail-value" style={{ color: 'var(--primary)', fontWeight: 700, fontSize: 18 }}>
                {formatCurrency(contract.contract_amount)}
              </div>
            </div>
            {/* <div className="detail-item">
              <div className="detail-label">预估利润</div>
              <div className="detail-value">
                {contract.payment_type === 'pay' ? '-' : formatCurrency(contract.estimated_profit)}
              </div>
            </div> */}
            <div className="detail-item">
              <div className="detail-label">合作期限</div>
              <div className="detail-value">{contract.contract_years || '-'}</div>
            </div>
            <div className="detail-item">
              <div className="detail-label">收付款类型</div>
              <div className="detail-value">{contract.payment_type === 'receive' ? '收款' : contract.payment_type === 'pay' ? '付款' : '-'}</div>
            </div>
            <div className="detail-item">
              <div className="detail-label">提交人</div>
              <div className="detail-value">{contract.creator_name || '-'}</div>
            </div>
            <div className="detail-item">
              <div className="detail-label">所属部门</div>
              <div className="detail-value">{contract.department_name || '-'}</div>
            </div>
            {contract.contract_content && (
              <div className="detail-item full">
                <div className="detail-label">合同内容</div>
                <div className="detail-value" style={{ whiteSpace: 'pre-wrap', lineHeight: 1.8 }}>
                  {contract.contract_content}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Approval Opinions */}
      {contract.opinions && contract.opinions.length > 0 && (
        <div className="card" style={{ marginBottom: 20 }}>
          <div className="card-header">
            <h3 className="card-title">💬 审批意见</h3>
          </div>
          <div className="card-body">
            {contract.opinions.map((op, idx) => (
              <div key={idx} style={{
                padding: '12px 16px',
                background: op.approved ? 'var(--success-light)' : 'var(--danger-light)',
                borderRadius: 'var(--radius-md)',
                marginBottom: 8,
                borderLeft: `3px solid ${op.approved ? 'var(--success)' : 'var(--danger)'}`,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                  <span style={{ fontWeight: 600, fontSize: 14 }}>
                    {op.approver_name} ({ROLE_NAMES[op.role] || op.role})
                  </span>
                  <span style={{ fontSize: 12, color: 'var(--gray-500)' }}>
                    {formatDateTime(op.created_at)}
                  </span>
                </div>
                <div style={{ fontSize: 14, color: 'var(--text-dark-secondary)' }}>
                  {op.approved ? '✅ 通过' : '❌ 驳回'}
                  {op.opinion && ` — ${op.opinion}`}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Attachments */}
      {contract.attachments && contract.attachments.length > 0 && (
        <div className="card" style={{ marginBottom: 20 }}>
          <div className="card-header">
            <h3 className="card-title">📎 附件文件</h3>
          </div>
          <div className="card-body">
            <div className="file-list" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {contract.attachments.map((file, idx) => (
                <AttachmentPreviewItem key={idx} file={file} />
              ))}
            </div>
          </div>
          {/* Custom global CSS for Excel previews */}
          <style dangerouslySetInnerHTML={{ __html: `
            .excel-table-container table {
              border-collapse: collapse;
              width: 100%;
              font-size: 13px;
              background: white;
            }
            .excel-table-container th, .excel-table-container td {
              border: 1px solid var(--gray-200);
              padding: 6px 10px;
              text-align: left;
            }
            .excel-table-container tr:nth-child(even) {
              background-color: var(--gray-50);
            }
            .docx-render-container .docx-preview-rendered {
              font-family: inherit !important;
            }
          `}} />
        </div>
      )}

      {/* Approval Action */}
      {canApprove() && (
        <div className="card" style={{ marginBottom: 20 }}>
          <div className="card-header">
            <h3 className="card-title">✍️ 审批操作</h3>
          </div>
          <div className="card-body">
            <div className="form-group">
              <label className="form-label">审批意见</label>
              <textarea
                className="form-textarea"
                placeholder="请输入审批意见（可选）..."
                value={opinion}
                onChange={e => setOpinion(e.target.value)}
                rows={3}
              />
            </div>
            <div style={{ display: 'flex', gap: 12 }}>
              <button
                className="btn btn-success"
                disabled={approving}
                onClick={() => handleApproval(true)}
              >
                {approving ? '处理中...' : '✅ 通过'}
              </button>
              <button
                className="btn btn-danger"
                disabled={approving}
                onClick={() => handleApproval(false)}
              >
                {approving ? '处理中...' : '❌ 驳回'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Resubmit Area */}
      {canResubmit() && !editing && (
        <div className="card" style={{ marginBottom: 20 }}>
          <div className="card-body" style={{ textAlign: 'center', padding: 32 }}>
            <div style={{ fontSize: 48, marginBottom: 12 }}>📝</div>
            <p style={{ color: 'var(--gray-500)', marginBottom: 16 }}>该合同已被驳回，您可以修改后重新提交</p>
            <button className="btn btn-primary" onClick={startEditing}>
              修改并重新提交
            </button>
          </div>
        </div>
      )}

      {/* Resubmit Edit Form */}
      {canResubmit() && editing && (
        <div className="card" style={{ marginBottom: 20 }}>
          <div className="card-header">
            <h3 className="card-title">📝 修改合同信息</h3>
          </div>
          <div className="card-body">
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 20 }}>
              <div className="form-group">
                <label className="form-label">项目名称 <span className="required">*</span></label>
                <input
                  type="text"
                  className="form-input"
                  value={editForm.project_name}
                  onChange={e => handleEditChange('project_name', e.target.value)}
                />
              </div>
              <div className="form-group">
                <label className="form-label">项目负责人</label>
                <select
                  className="form-select"
                  value={editForm.project_leader}
                  onChange={e => handleEditChange('project_leader', e.target.value)}
                >
                  <option value="">-- 请选择部门主管 --</option>
                  {supervisors.map(s => (
                    <option key={s.id} value={s.real_name}>
                      {s.real_name} ({s.department_name || '无部门'})
                    </option>
                  ))}
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">签订时间</label>
                <input
                  type="date"
                  className="form-input"
                  value={editForm.sign_date}
                  onChange={e => handleEditChange('sign_date', e.target.value)}
                />
              </div>
              <div className="form-group" ref={partnerRef}>
                <label className="form-label">合作单位 <span className="required">*</span></label>
                {editForm.partner_id ? (
                  <div className="selected-partner-card animate-fadeIn" style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    padding: '10px 14px',
                    background: 'var(--gray-50)',
                    border: '1.5px solid var(--gray-200)',
                    borderRadius: 'var(--radius-md)',
                  }}>
                    <span style={{ fontWeight: 600, fontSize: 14 }}>🏢 {selectedPartnerName}</span>
                    <button
                      type="button"
                      className="btn btn-ghost btn-sm"
                      style={{ color: 'var(--danger)', padding: '4px 8px' }}
                      onClick={() => {
                        setEditForm(prev => ({ ...prev, partner_id: '' }));
                        setSelectedPartnerName('');
                        setPartnerSearch('');
                        setPartnerDropdownOpen(true);
                      }}
                    >
                      重新选择
                    </button>
                  </div>
                ) : (
                  <div className="search-select">
                    <input
                      type="text"
                      className="search-select-input"
                      placeholder="搜索合作单位..."
                      value={partnerSearch}
                      onChange={e => {
                        setPartnerSearch(e.target.value);
                        setPartnerDropdownOpen(true);
                      }}
                      onFocus={() => setPartnerDropdownOpen(true)}
                    />
                    {partnerDropdownOpen && (
                      <div className="search-select-dropdown">
                        {editFilteredPartners.length > 0 ? (
                          editFilteredPartners.map(p => (
                            <div
                              key={p.id}
                              className={`search-select-option ${editForm.partner_id === p.id ? 'selected' : ''}`}
                              onClick={() => selectPartner(p)}
                            >
                              {p.name}
                            </div>
                          ))
                        ) : (
                          <div className="search-select-empty">
                            未找到？
                            <a href="/dashboard/partners" onClick={e => { e.preventDefault(); router.push('/dashboard/partners'); }}>
                              前往添加合作单位
                            </a>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                )}
              </div>
              <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                <label className="form-label">合同内容</label>
                <textarea
                  className="form-textarea"
                  value={editForm.contract_content}
                  onChange={e => handleEditChange('contract_content', e.target.value)}
                  rows={4}
                />
              </div>
              <div className="form-group" style={{ gridColumn: '1 / -1' }}>
                <label className="form-label">合作期限 <span className="required">*</span></label>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, maxWidth: 400 }}>
                  <input
                    type="date"
                    className="form-input"
                    value={editForm.cooperate_start}
                    onChange={handleEditChange('cooperate_start', e.target.value)}
                  />
                  <span style={{ color: 'var(--gray-400)' }}>至</span>
                  <input
                    type="date"
                    className="form-input"
                    value={editForm.cooperate_end}
                    onChange={handleEditChange('cooperate_end', e.target.value)}
                  />
                </div>
              </div>
              <div className="form-group">
                <label className="form-label">合同金额（元）<span className="required">*</span></label>
                <input
                  type="number"
                  className="form-input"
                  min="0"
                  step="0.01"
                  value={editForm.contract_amount}
                  onChange={e => handleEditChange('contract_amount', e.target.value)}
                />
              </div>
              <div className="form-group">
                <label className="form-label">预估利润（元）</label>
                <input
                  type="number"
                  className="form-input"
                  placeholder={editForm.payment_type === 'pay' ? '付款合同无利润' : '请输入预估利润'}
                  min="0"
                  step="0.01"
                  value={editForm.estimated_profit}
                  onChange={e => handleEditChange('estimated_profit', e.target.value)}
                  disabled={editForm.payment_type === 'pay'}
                />
              </div>
              <div className="form-group">
                <label className="form-label">收款/付款</label>
                <div style={{ display: 'flex', gap: 24, marginTop: 8 }}>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', fontSize: 14 }}>
                    <input
                      type="radio"
                      name="edit_payment_type"
                      value="receive"
                      checked={editForm.payment_type === 'receive'}
                      onChange={e => handleEditChange('payment_type', e.target.value)}
                      style={{ accentColor: 'var(--primary)' }}
                    />
                    收款
                  </label>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', fontSize: 14 }}>
                    <input
                      type="radio"
                      name="edit_payment_type"
                      value="pay"
                      checked={editForm.payment_type === 'pay'}
                      onChange={e => handleEditChange('payment_type', e.target.value)}
                      style={{ accentColor: 'var(--primary)' }}
                    />
                    付款
                  </label>
                </div>
              </div>
            </div>

            {/* File upload for resubmit */}
            <div className="form-group" style={{ marginTop: 12 }}>
              <label className="form-label">追加附件</label>
              <div
                className={`upload-area ${editDragging ? 'dragging' : ''}`}
                onDragOver={e => { e.preventDefault(); setEditDragging(true); }}
                onDragLeave={e => { e.preventDefault(); setEditDragging(false); }}
                onDrop={e => { e.preventDefault(); setEditDragging(false); handleEditFiles(e.dataTransfer.files); }}
                onClick={() => editFileInputRef.current?.click()}
                style={{ padding: 20 }}
              >
                <div className="upload-text">📁 点击或拖拽文件上传</div>
                <input
                  ref={editFileInputRef}
                  type="file"
                  multiple
                  style={{ display: 'none' }}
                  onChange={e => {
                    if (e.target.files.length > 0) {
                      handleEditFiles(e.target.files);
                      e.target.value = '';
                    }
                  }}
                />
              </div>
              {editFiles.length > 0 && (
                <div className="file-list">
                  {editFiles.map((file, idx) => (
                    <div key={idx} className="file-item">
                      <span className="file-item-name">📄 {file.name} ({formatFileSize(file.size)})</span>
                      <button
                        type="button"
                        className="file-item-remove"
                        onClick={() => setEditFiles(prev => prev.filter((_, i) => i !== idx))}
                      >
                        ✕
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div style={{ display: 'flex', gap: 12, marginTop: 20 }}>
              <button className="btn btn-ghost" onClick={() => setEditing(false)}>
                取消
              </button>
              <button
                className="btn btn-primary"
                disabled={resubmitting}
                onClick={handleResubmit}
              >
                {resubmitting ? '提交中...' : '✨ 修改并重新提交'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function AttachmentPreviewItem({ file }) {
  const originalPath = file.file_path || file.path || file.url || '';
  const ext = originalPath.split('.').pop().toLowerCase();
  
  let path = originalPath;
  if (path.startsWith('/uploads/attachments/')) {
    const fileName = path.replace('/uploads/attachments/', '');
    path = `/api/upload?file=${fileName}`;
  }

  const isImage = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'].includes(ext);
  const isPdf = ext === 'pdf';
  const isWord = ext === 'docx';
  const isExcel = ['xlsx', 'xls'].includes(ext);
  const isText = ['txt', 'csv', 'log', 'json'].includes(ext);

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [textVal, setTextVal] = useState('');
  const [excelHtml, setExcelHtml] = useState('');
  const containerRef = useRef(null);

  // Helper to load external scripts
  const loadScript = (src) => {
    return new Promise((resolve, reject) => {
      if (document.querySelector(`script[src="${src}"]`)) {
        resolve();
        return;
      }
      const script = document.createElement('script');
      script.src = src;
      script.onload = () => resolve();
      script.onerror = (err) => reject(err);
      document.body.appendChild(script);
    });
  };

  useEffect(() => {
    let active = true;
    const fetchAndRender = async () => {
      if (isWord) {
        setLoading(true);
        setError(null);
        try {
          // Load JSZip and docx-preview
          await loadScript('https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js');
          await loadScript('https://unpkg.com/docx-preview@0.1.15/dist/docx-preview.min.js');
          
          const res = await fetch(path);
          if (!res.ok) throw new Error('无法加载文档文件');
          const blob = await res.blob();
          
          if (active && containerRef.current && window.docx) {
            containerRef.current.innerHTML = '';
            await window.docx.renderAsync(blob, containerRef.current, null, {
              className: "docx-preview-rendered",
              inWrapper: false
            });
          }
        } catch (err) {
          console.error(err);
          if (active) setError('Word 文档解析失败，请点击下载查看');
        } finally {
          if (active) setLoading(false);
        }
      } else if (isExcel) {
        setLoading(true);
        setError(null);
        try {
          await loadScript('https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js');
          const res = await fetch(path);
          if (!res.ok) throw new Error('无法加载表格文件');
          const arrayBuffer = await res.arrayBuffer();
          
          if (active && window.XLSX) {
            const workbook = window.XLSX.read(new Uint8Array(arrayBuffer), { type: 'array' });
            const sheetName = workbook.SheetNames[0];
            const sheet = workbook.Sheets[sheetName];
            const html = window.XLSX.utils.sheet_to_html(sheet);
            setExcelHtml(html);
          }
        } catch (err) {
          console.error(err);
          if (active) setError('Excel 表格解析失败，请点击下载查看');
        } finally {
          if (active) setLoading(false);
        }
      } else if (isText) {
        setLoading(true);
        setError(null);
        try {
          const res = await fetch(path);
          if (!res.ok) throw new Error('无法加载文本内容');
          const text = await res.text();
          if (active) setTextVal(text);
        } catch (err) {
          console.error(err);
          if (active) setError('文本读取失败，请点击下载查看');
        } finally {
          if (active) setLoading(false);
        }
      }
    };

    fetchAndRender();
    return () => { active = false; };
  }, [path, isWord, isExcel, isText]);

  return (
    <div style={{ borderBottom: '1px solid var(--gray-100)', paddingBottom: 16, lastChild: { borderBottom: 'none' } }}>
      <div className="file-item" style={{ marginBottom: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span className="file-item-name" style={{ fontWeight: 500 }}>
          📄 {file.original_name || file.file_name || file.name || '附件'}
        </span>
        <a
          href={path}
          target="_blank"
          rel="noopener noreferrer"
          className="btn btn-sm btn-outline"
        >
          下载
        </a>
      </div>
      
      {/* Loading & Error States */}
      {loading && (
        <div style={{ padding: 12, fontSize: 13, color: 'var(--gray-500)', display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="loading-spinner-sm"></span> 正在渲染预览中...
        </div>
      )}
      {error && (
        <div style={{ padding: 10, fontSize: 13, color: 'var(--red-500)', background: 'var(--red-50)' }}>
          ⚠️ {error}
        </div>
      )}

      {/* Preview Area */}
      {!loading && !error && (
        <>
          {isImage && (
            <div className="file-preview animate-fadeIn" style={{
              marginTop: 10,
              padding: 10,
              background: 'var(--gray-50)',
              border: '1px solid var(--gray-200)',
              borderRadius: 'var(--radius-md)',
              textAlign: 'center'
            }}>
              <img
                src={path}
                alt={file.file_name}
                style={{ maxWidth: '100%', maxHeight: 400, borderRadius: 4, objectFit: 'contain' }}
              />
            </div>
          )}
          {isPdf && (
            <div className="file-preview animate-fadeIn" style={{
              marginTop: 10,
              padding: 10,
              background: 'var(--gray-50)',
              border: '1px solid var(--gray-200)',
              borderRadius: 'var(--radius-md)'
            }}>
              <iframe
                src={path}
                title={file.file_name}
                style={{ width: '100%', height: 600, border: 'none', borderRadius: 4 }}
              />
            </div>
          )}
          {isWord && (
            <div className="file-preview animate-fadeIn" style={{
              marginTop: 10,
              padding: '20px 40px',
              background: 'white',
              border: '1px solid var(--gray-200)',
              borderRadius: 'var(--radius-md)',
              maxHeight: 600,
              overflowY: 'auto',
              boxShadow: 'inset 0 0 10px rgba(0,0,0,0.05)'
            }}>
              <div ref={containerRef} className="docx-render-container" />
            </div>
          )}
          {isExcel && excelHtml && (
            <div className="file-preview animate-fadeIn" style={{
              marginTop: 10,
              padding: 16,
              background: 'white',
              border: '1px solid var(--gray-200)',
              borderRadius: 'var(--radius-md)',
              maxHeight: 500,
              overflow: 'auto',
              boxShadow: 'inset 0 0 10px rgba(0,0,0,0.05)'
            }}>
              <div 
                dangerouslySetInnerHTML={{ __html: excelHtml }} 
                className="excel-table-container"
                style={{ overflowX: 'auto' }}
              />
            </div>
          )}
          {isText && textVal && (
            <div className="file-preview animate-fadeIn" style={{
              marginTop: 10,
              padding: 16,
              background: 'var(--gray-50)',
              border: '1px solid var(--gray-200)',
              borderRadius: 'var(--radius-md)',
              maxHeight: 400,
              overflowY: 'auto'
            }}>
              <pre style={{
                margin: 0,
                whiteSpace: 'pre-wrap',
                fontFamily: 'monospace',
                fontSize: 13,
                color: 'var(--gray-800)',
                lineHeight: 1.6
              }}>{textVal}</pre>
            </div>
          )}
          {!isImage && !isPdf && !isWord && !isExcel && !isText && (
            <div style={{ fontSize: 12, color: 'var(--gray-400)', marginTop: 4 }}>
              提示：此格式文件暂不支持直接预览，请点击下载查看。
            </div>
          )}
        </>
      )}
    </div>
  );
}
