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

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 DepartmentsPage() {
  const user = useUser();

  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(true);

  // 模态框
  const [showModal, setShowModal] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [name, setName] = useState('');
  const [nameError, setNameError] = useState('');
  const [saving, setSaving] = useState(false);

  // 删除确认
  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 loadDepartments = useCallback(async () => {
    setLoading(true);
    try {
      const res = await authFetch('/api/departments');
      const data = await res.json();
      setDepartments(data.departments || data || []);
    } catch (err) {
      showToast('加载部门列表失败', 'error');
    } finally {
      setLoading(false);
    }
  }, [showToast]);

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

  // 权限检查
  if (user && user.role !== 'admin') {
    return (
      <div className="animate-fadeIn">
        <div className="empty-state">
          <div className="empty-state-icon">🔒</div>
          <p className="empty-state-text">仅系统管理员可访问此页面</p>
        </div>
      </div>
    );
  }

  const openCreateModal = () => {
    setName('');
    setEditingId(null);
    setNameError('');
    setShowModal(true);
  };

  const openEditModal = (dept) => {
    setName(dept.name || '');
    setEditingId(dept.id);
    setNameError('');
    setShowModal(true);
  };

  const closeModal = () => {
    setShowModal(false);
    setEditingId(null);
    setName('');
    setNameError('');
  };

  const handleSubmit = async () => {
    if (!name.trim()) {
      setNameError('部门名称不能为空');
      return;
    }
    setNameError('');
    setSaving(true);
    try {
      const url = editingId ? `/api/departments/${editingId}` : '/api/departments';
      const method = editingId ? 'PUT' : 'POST';
      const res = await authFetch(url, {
        method,
        body: JSON.stringify({ name: name.trim() }),
      });

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

      showToast(editingId ? '部门已更新' : '部门已创建', 'success');
      closeModal();
      loadDepartments();
    } catch (err) {
      showToast(err.message, 'error');
    } finally {
      setSaving(false);
    }
  };

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

  const formatDate = (dateStr) => {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleDateString('zh-CN');
  };

  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="card">
        <div className="card-body" style={{ padding: 0 }}>
          {loading ? (
            <div className="loading-overlay">
              <div className="loading-spinner"></div>
            </div>
          ) : departments.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 style={{ width: '180px' }}>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {departments.map((dept) => (
                    <tr key={dept.id}>
                      <td style={{ fontWeight: 600 }}>{dept.name}</td>
                      <td>{formatDate(dept.created_at)}</td>
                      <td>
                        <div style={{ display: 'flex', gap: '8px' }}>
                          <button className="btn btn-outline btn-sm" onClick={() => openEditModal(dept)}>
                            ✏️ 编辑
                          </button>
                          <button className="btn btn-danger btn-sm" onClick={() => setDeleteTarget(dept)}>
                            🗑️ 删除
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {/* 新增/编辑模态框 */}
      {showModal && (
        <div className="modal-overlay" onClick={closeModal}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '420px' }}>
            <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={name}
                  onChange={(e) => { setName(e.target.value); setNameError(''); }}
                  placeholder="请输入部门名称"
                  onKeyDown={(e) => { if (e.key === 'Enter') handleSubmit(); }}
                  autoFocus
                />
                {nameError && <p className="form-error">{nameError}</p>}
              </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>
  );
}
