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

const EMPTY_FORM = {
  name: '',
  short_name: '',
  english_name: '',
  website: '',
  address: '',
  description: '',
};

function Toast({ message, type, onClose }) {
  useEffect(() => {
    const timer = setTimeout(onClose, 3000);
    return () => clearTimeout(timer);
  }, [onClose]);
  return (
    <div className={`toast toast-${type}`}>
      {type === 'success' ? '✅' : type === 'error' ? '❌' : 'ℹ️'} {message}
    </div>
  );
}

export default function PartnersPage() {
  const user = useUser();

  const [partners, setPartners] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');

  // 模态框状态
  const [showModal, setShowModal] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState({ ...EMPTY_FORM });
  const [saving, setSaving] = useState(false);
  const [formErrors, setFormErrors] = useState({});

  // 删除确认
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [deleting, setDeleting] = useState(false);

  // Toast
  const [toasts, setToasts] = useState([]);
  const showToast = useCallback((message, type = 'info') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
  }, []);
  const removeToast = useCallback((id) => {
    setToasts(prev => prev.filter(t => t.id !== id));
  }, []);

  // 加载数据
  const loadPartners = useCallback(async (keyword = '') => {
    setLoading(true);
    try {
      const params = keyword ? `?search=${encodeURIComponent(keyword)}` : '';
      const res = await authFetch(`/api/partners${params}`);
      const data = await res.json();
      setPartners(data.partners || data || []);
    } catch (err) {
      showToast('加载合作单位失败', 'error');
    } finally {
      setLoading(false);
    }
  }, [showToast]);

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

  // 搜索
  const handleSearch = () => {
    loadPartners(search);
  };

  // 打开新增模态框
  const openCreateModal = () => {
    setForm({ ...EMPTY_FORM });
    setEditingId(null);
    setFormErrors({});
    setShowModal(true);
  };

  // 打开编辑模态框
  const openEditModal = (partner) => {
    setForm({
      name: partner.name || '',
      short_name: partner.short_name || '',
      english_name: partner.english_name || '',
      website: partner.website || '',
      address: partner.address || '',
      description: partner.description || '',
    });
    setEditingId(partner.id);
    setFormErrors({});
    setShowModal(true);
  };

  // 关闭模态框
  const closeModal = () => {
    setShowModal(false);
    setEditingId(null);
    setForm({ ...EMPTY_FORM });
    setFormErrors({});
  };

  // 验证表单
  const validateForm = () => {
    const errors = {};
    if (!form.name.trim()) errors.name = '企业名称不能为空';
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 提交表单
  const handleSubmit = async () => {
    if (!validateForm()) return;
    setSaving(true);
    try {
      const url = editingId ? `/api/partners/${editingId}` : '/api/partners';
      const method = editingId ? 'PUT' : 'POST';
      const res = await authFetch(url, {
        method,
        body: JSON.stringify(form),
      });

      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || '操作失败');
      }

      showToast(editingId ? '合作单位已更新' : '合作单位已创建', 'success');
      closeModal();
      loadPartners(search);
    } catch (err) {
      showToast(err.message, 'error');
    } finally {
      setSaving(false);
    }
  };

  // 删除
  const handleDelete = async () => {
    if (!deleteTarget) return;
    setDeleting(true);
    try {
      const res = await authFetch(`/api/partners/${deleteTarget.id}`, { method: 'DELETE' });
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || '删除失败');
      }
      showToast('合作单位已删除', 'success');
      setDeleteTarget(null);
      loadPartners(search);
    } catch (err) {
      showToast(err.message, 'error');
    } finally {
      setDeleting(false);
    }
  };

  return (
    <div className="animate-fadeIn">
      {/* Toast */}
      <div className="toast-container">
        {toasts.map(t => (
          <Toast key={t.id} message={t.message} type={t.type} onClose={() => removeToast(t.id)} />
        ))}
      </div>

      <div className="page-header">
        <div>
          <h1 className="page-title">合作单位管理</h1>
          <p className="page-subtitle">管理合同相关的合作企业信息</p>
        </div>
        <button className="btn btn-primary" onClick={openCreateModal}>
          ➕ 新增合作单位
        </button>
      </div>

      {/* 搜索栏 */}
      <div className="filter-bar">
        <input
          type="text"
          className="form-input"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="搜索企业名称、简称..."
          onKeyDown={(e) => { if (e.key === 'Enter') handleSearch(); }}
          style={{ minWidth: '280px' }}
        />
        <div className="filter-actions">
          <button className="btn btn-primary btn-sm" onClick={handleSearch}>
            🔍 搜索
          </button>
          <button className="btn btn-ghost btn-sm" onClick={() => { setSearch(''); loadPartners(''); }}>
            🔄 重置
          </button>
        </div>
      </div>

      {/* 数据表格 */}
      <div className="card">
        <div className="card-body" style={{ padding: 0 }}>
          {loading ? (
            <div className="loading-overlay">
              <div className="loading-spinner"></div>
            </div>
          ) : partners.length === 0 ? (
            <div className="empty-state">
              <div className="empty-state-icon">🏢</div>
              <p className="empty-state-text">暂无合作单位数据</p>
            </div>
          ) : (
            <div className="table-container">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>企业名称</th>
                    <th>简称</th>
                    <th>英文名称</th>
                    <th>官网</th>
                    <th>地址</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {partners.map((p) => (
                    <tr key={p.id}>
                      <td style={{ fontWeight: 600 }}>{p.name}</td>
                      <td>{p.short_name || '-'}</td>
                      <td>{p.english_name || '-'}</td>
                      <td>
                        {p.website ? (
                          <a href={p.website} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--primary)' }}>
                            {p.website}
                          </a>
                        ) : '-'}
                      </td>
                      <td>{p.address || '-'}</td>
                      <td>
                        <div style={{ display: 'flex', gap: '8px' }}>
                          <button className="btn btn-outline btn-sm" onClick={() => openEditModal(p)}>
                            ✏️ 编辑
                          </button>
                          <button className="btn btn-danger btn-sm" onClick={() => setDeleteTarget(p)}>
                            🗑️ 删除
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {/* 新增/编辑模态框 */}
      {showModal && (
        <div className="modal-overlay" onClick={closeModal}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h3 className="modal-title">{editingId ? '编辑合作单位' : '新增合作单位'}</h3>
              <button className="modal-close" onClick={closeModal}>✕</button>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label className="form-label">
                  企业名称 <span className="required">*</span>
                </label>
                <input
                  type="text"
                  className="form-input"
                  value={form.name}
                  onChange={(e) => setForm(prev => ({ ...prev, name: e.target.value }))}
                  placeholder="请输入企业全称"
                />
                {formErrors.name && <p className="form-error">{formErrors.name}</p>}
              </div>

              <div className="form-group">
                <label className="form-label">简称</label>
                <input
                  type="text"
                  className="form-input"
                  value={form.short_name}
                  onChange={(e) => setForm(prev => ({ ...prev, short_name: e.target.value }))}
                  placeholder="请输入企业简称"
                />
              </div>

              <div className="form-group">
                <label className="form-label">英文名称</label>
                <input
                  type="text"
                  className="form-input"
                  value={form.english_name}
                  onChange={(e) => setForm(prev => ({ ...prev, english_name: e.target.value }))}
                  placeholder="请输入英文名称"
                />
              </div>

              <div className="form-group">
                <label className="form-label">官网</label>
                <input
                  type="url"
                  className="form-input"
                  value={form.website}
                  onChange={(e) => setForm(prev => ({ ...prev, website: e.target.value }))}
                  placeholder="https://example.com"
                />
              </div>

              <div className="form-group">
                <label className="form-label">地址</label>
                <input
                  type="text"
                  className="form-input"
                  value={form.address}
                  onChange={(e) => setForm(prev => ({ ...prev, address: e.target.value }))}
                  placeholder="请输入企业地址"
                />
              </div>

              <div className="form-group">
                <label className="form-label">描述</label>
                <textarea
                  className="form-textarea"
                  value={form.description}
                  onChange={(e) => setForm(prev => ({ ...prev, description: e.target.value }))}
                  placeholder="请输入企业描述（可选）"
                  rows={3}
                />
              </div>
            </div>
            <div className="modal-footer">
              <button className="btn btn-ghost" onClick={closeModal}>取消</button>
              <button className="btn btn-primary" onClick={handleSubmit} disabled={saving}>
                {saving ? '⏳ 保存中...' : '💾 保存'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 删除确认模态框 */}
      {deleteTarget && (
        <div className="modal-overlay" onClick={() => setDeleteTarget(null)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '420px' }}>
            <div className="modal-header">
              <h3 className="modal-title">确认删除</h3>
              <button className="modal-close" onClick={() => setDeleteTarget(null)}>✕</button>
            </div>
            <div className="modal-body">
              <p style={{ fontSize: '15px', color: 'var(--text-dark-secondary)', lineHeight: 1.6 }}>
                确定要删除合作单位 <strong style={{ color: 'var(--danger)' }}>{deleteTarget.name}</strong> 吗？
                此操作不可撤销。
              </p>
            </div>
            <div className="modal-footer">
              <button className="btn btn-ghost" onClick={() => setDeleteTarget(null)}>取消</button>
              <button className="btn btn-danger" onClick={handleDelete} disabled={deleting}>
                {deleting ? '⏳ 删除中...' : '🗑️ 确认删除'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
