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

export default function CreateContractPage() {
  const router = useRouter();
  const user = useUser();

  // Form state
  const [form, setForm] = useState({
    project_name: '',
    project_leader: '',
    sign_date: '',
    partner_id: '',
    contract_content: '',
    cooperate_start: '',
    cooperate_end: '',
    contract_amount: '',
    estimated_profit: '',
    payment_type: 'receive',
  });

  // Supervisors list
  const [supervisors, setSupervisors] = useState([]);

  // Partner search
  const [partners, setPartners] = useState([]);
  const [partnerSearch, setPartnerSearch] = useState('');
  const [partnerDropdownOpen, setPartnerDropdownOpen] = useState(false);
  const [selectedPartnerName, setSelectedPartnerName] = useState('');
  const partnerRef = useRef(null);

  // File upload
  const [files, setFiles] = useState([]);
  const [dragging, setDragging] = useState(false);
  const fileInputRef = useRef(null);

  // Config
  const [profitPercentage, setProfitPercentage] = useState(0);
  const [profitEdited, setProfitEdited] = useState(false);

  // UI state
  const [submitting, setSubmitting] = useState(false);
  const [errors, setErrors] = useState({});
  const [toast, setToast] = useState(null);

  // Fetch partners
  useEffect(() => {
    authFetch('/api/partners')
      .then(r => r.json())
      .then(data => {
        setPartners(data.partners || data || []);
      })
      .catch(() => {});
  }, []);

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

  // Default supervisor selection based on user's department
  useEffect(() => {
    if (supervisors.length > 0 && user && !form.project_leader) {
      const defaultSupervisor = supervisors.find(s => s.department_id === user.department_id);
      if (defaultSupervisor) {
        setForm(prev => ({ ...prev, project_leader: defaultSupervisor.real_name }));
      } else {
        setForm(prev => ({ ...prev, project_leader: supervisors[0]?.real_name || '' }));
      }
    }
  }, [supervisors, user]);

  // Fetch config for profit percentage
  useEffect(() => {
    authFetch('/api/config')
      .then(r => r.json())
      .then(data => {
        const pct = data.profit_percentage || data.config?.profit_percentage || 0;
        setProfitPercentage(Number(pct));
      })
      .catch(() => {});
  }, []);

  // Auto-calculate profit when amount changes
  useEffect(() => {
    if (form.payment_type !== 'pay' && !profitEdited && form.contract_amount && profitPercentage > 0) {
      const profit = (Number(form.contract_amount) * profitPercentage / 100).toFixed(2);
      setForm(prev => ({ ...prev, estimated_profit: profit }));
    }
  }, [form.contract_amount, profitPercentage, profitEdited, form.payment_type]);

  // 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 showToast = (message, type = 'success') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000);
  };

  const handleChange = (field, value) => {
    setForm(prev => {
      const updated = { ...prev, [field]: value };
      if (field === 'payment_type' && value === 'pay') {
        updated.estimated_profit = '';
      }
      return updated;
    });
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: null }));
    }
  };

  const handleProfitChange = (value) => {
    setProfitEdited(true);
    handleChange('estimated_profit', value);
  };

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

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

  // File handling
  const handleFiles = useCallback((newFiles) => {
    const fileArray = Array.from(newFiles);
    setFiles(prev => [...prev, ...fileArray]);
  }, []);

  const removeFile = (index) => {
    setFiles(prev => prev.filter((_, i) => i !== index));
  };

  const handleDragOver = (e) => {
    e.preventDefault();
    setDragging(true);
  };

  const handleDragLeave = (e) => {
    e.preventDefault();
    setDragging(false);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setDragging(false);
    if (e.dataTransfer.files.length > 0) {
      handleFiles(e.dataTransfer.files);
    }
  };

  // Upload files after contract creation
  const uploadFiles = async (contractId) => {
    for (const file of files) {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('contract_id', contractId);
      try {
        await authFetch('/api/upload', {
          method: 'POST',
          body: formData,
        });
      } catch (err) {
        console.error('文件上传失败:', err);
      }
    }
  };

  // Validate and submit
  const validate = () => {
    const newErrors = {};
    if (!form.project_name.trim()) newErrors.project_name = '请输入项目名称';
    if (!form.partner_id) newErrors.partner_id = '请选择合作单位';
    if (!form.contract_amount || Number(form.contract_amount) <= 0) newErrors.contract_amount = '请输入合同金额';

    // Validate cooperation duration range
    if (!form.cooperate_start || !form.cooperate_end) {
      newErrors.contract_years = '请选择完整的合作时间范围';
    } else if (form.cooperate_start > form.cooperate_end) {
      newErrors.contract_years = '开始时间不能晚于结束时间';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!validate()) return;

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

      const res = await authFetch('/api/contracts', {
        method: 'POST',
        body: JSON.stringify(body),
      });
      const data = await res.json();

      if (!res.ok) {
        showToast(data.error || '创建失败', 'error');
        setSubmitting(false);
        return;
      }

      const contractId = data.id || data.contract?.id;

      // Upload files if any
      if (files.length > 0 && contractId) {
        await uploadFiles(contractId);
      }

      showToast('合同创建成功！');
      setTimeout(() => {
        router.push(`/dashboard/contracts/${contractId}`);
      }, 800);
    } catch (err) {
      showToast(err.message || '提交失败，请重试', 'error');
      setSubmitting(false);
    }
  };

  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';
  };

  if (user && user.role !== 'employee') {
    return (
      <div className="animate-fadeIn" style={{ maxWidth: 600, margin: '40px auto' }}>
        <div className="card" style={{ padding: 40, textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 16 }}>⚠️</div>
          <h2 style={{ fontSize: 20, fontWeight: 600, marginBottom: 8 }}>暂无访问权限</h2>
          <p style={{ color: 'var(--gray-500)', marginBottom: 24 }}>仅员工角色可新建合同流转任务。</p>
          <button className="btn btn-primary" onClick={() => router.push('/dashboard/contracts')}>
            返回合同列表
          </button>
        </div>
      </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>
      )}

      <div className="page-header">
        <div>
          <h1 className="page-title">新建合同流转任务</h1>
          <p className="page-subtitle">填写合同信息并提交审批</p>
        </div>
      </div>

      <form onSubmit={handleSubmit}>
        {/* 基本信息 */}
        <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"
                  placeholder="请输入项目名称"
                  value={form.project_name}
                  onChange={e => handleChange('project_name', e.target.value)}
                />
                {errors.project_name && <div className="form-error">{errors.project_name}</div>}
              </div>
              <div className="form-group">
                <label className="form-label">项目负责人</label>
                <select
                  className="form-select"
                  value={form.project_leader}
                  onChange={e => handleChange('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={form.sign_date}
                  onChange={e => handleChange('sign_date', e.target.value)}
                />
              </div>
            </div>
          </div>
        </div>

        {/* 合作单位 */}
        <div className="card" style={{ marginBottom: 20 }}>
          <div className="card-header">
            <h3 className="card-title">🏢 合作单位 <span className="required">*</span></h3>
          </div>
          <div className="card-body">
            <div className="form-group" ref={partnerRef}>
              {form.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={() => {
                      setForm(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">
                      {filteredPartners.length > 0 ? (
                        filteredPartners.map(p => (
                          <div
                            key={p.id}
                            className={`search-select-option ${form.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>
              )}
              {errors.partner_id && <div className="form-error">{errors.partner_id}</div>}
            </div>
          </div>
        </div>

        {/* 合同详情 */}
        <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={form.contract_content}
                onChange={e => handleChange('contract_content', e.target.value)}
                rows={4}
              />
            </div>
            <div className="form-group">
              <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={form.cooperate_start}
                  onChange={e => handleChange('cooperate_start', e.target.value)}
                />
                <span style={{ color: 'var(--gray-400)' }}>至</span>
                <input
                  type="date"
                  className="form-input"
                  value={form.cooperate_end}
                  onChange={e => handleChange('cooperate_end', e.target.value)}
                />
              </div>
              {errors.contract_years && <div className="form-error">{errors.contract_years}</div>}
            </div>
          </div>
        </div>

        {/* 金额信息 */}
        <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="number"
                  className="form-input"
                  placeholder="请输入合同金额"
                  min="0"
                  step="0.01"
                  value={form.contract_amount}
                  onChange={e => handleChange('contract_amount', e.target.value)}
                />
                {errors.contract_amount && <div className="form-error">{errors.contract_amount}</div>}
              </div>
              {/* <div className="form-group">
                <label className="form-label">预估利润（元）</label>
                <div style={{ position: 'relative' }}>
                  <input
                    type="number"
                    className="form-input"
                    placeholder={form.payment_type === 'pay' ? '付款合同无利润' : '自动计算'}
                    min="0"
                    step="0.01"
                    value={form.estimated_profit}
                    onChange={e => handleProfitChange(e.target.value)}
                    disabled={form.payment_type === 'pay'}
                  />
                  {form.payment_type !== 'pay' && profitPercentage > 0 && !profitEdited && (
                    <div className="form-hint">
                      按默认比例 {profitPercentage}% 自动计算，可手动修改
                    </div>
                  )}
                  {form.payment_type !== 'pay' && profitEdited && (
                    <div className="form-hint">
                      <span
                        style={{ color: 'var(--primary)', cursor: 'pointer' }}
                        onClick={() => {
                          setProfitEdited(false);
                          if (form.contract_amount && profitPercentage > 0) {
                            const profit = (Number(form.contract_amount) * profitPercentage / 100).toFixed(2);
                            setForm(prev => ({ ...prev, estimated_profit: profit }));
                          }
                        }}
                      >
                        恢复自动计算
                      </span>
                    </div>
                  )}
                </div>
              </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="payment_type"
                      value="receive"
                      checked={form.payment_type === 'receive'}
                      onChange={e => handleChange('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="payment_type"
                      value="pay"
                      checked={form.payment_type === 'pay'}
                      onChange={e => handleChange('payment_type', e.target.value)}
                      style={{ accentColor: 'var(--primary)' }}
                    />
                    付款
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 附件上传 */}
        <div className="card" style={{ marginBottom: 20 }}>
          <div className="card-header">
            <h3 className="card-title">📎 附件上传</h3>
          </div>
          <div className="card-body">
            <div
              className={`upload-area ${dragging ? 'dragging' : ''}`}
              onDragOver={handleDragOver}
              onDragLeave={handleDragLeave}
              onDrop={handleDrop}
              onClick={() => fileInputRef.current?.click()}
            >
              <div className="upload-icon">📁</div>
              <div className="upload-text">点击或拖拽文件到此处上传</div>
              <div className="upload-hint">支持各种文件格式</div>
              <input
                ref={fileInputRef}
                type="file"
                multiple
                style={{ display: 'none' }}
                onChange={e => {
                  if (e.target.files.length > 0) {
                    handleFiles(e.target.files);
                    e.target.value = '';
                  }
                }}
              />
            </div>
            {files.length > 0 && (
              <div className="file-list">
                {files.map((file, index) => (
                  <div key={index} className="file-item">
                    <span className="file-item-name">
                      📄 {file.name}
                      <span style={{ color: 'var(--gray-400)', fontSize: 12 }}>
                        ({formatFileSize(file.size)})
                      </span>
                    </span>
                    <button
                      type="button"
                      className="file-item-remove"
                      onClick={() => removeFile(index)}
                    >
                      ✕
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* 操作按钮 */}
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12, marginTop: 24 }}>
          <button
            type="button"
            className="btn btn-ghost"
            onClick={() => router.back()}
          >
            取消
          </button>
          <button
            type="submit"
            className="btn btn-primary btn-lg"
            disabled={submitting}
          >
            {submitting ? '提交中...' : '✨ 提交审批'}
          </button>
        </div>
      </form>
    </div>
  );
}
