import { useEffect, useState } from 'react';
import { Plus, Building2, Pencil, Trash2 } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '../api/axios';
import Modal from '../components/Modal';
import { formatCurrency } from '../utils/format';

const empty = { name: '', code: '', description: '', headName: '', budget: 0 };

export default function Departments() {
  const [departments, setDepartments] = useState([]);
  const [modal, setModal] = useState(false);
  const [form, setForm] = useState(empty);
  const [editId, setEditId] = useState(null);

  const load = () => api.get('/departments').then((res) => setDepartments(res.data));

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

  const openCreate = () => {
    setForm(empty);
    setEditId(null);
    setModal(true);
  };

  const openEdit = (d) => {
    setForm(d);
    setEditId(d._id);
    setModal(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editId) {
        await api.put(`/departments/${editId}`, form);
        toast.success('Department updated');
      } else {
        await api.post('/departments', form);
        toast.success('Department created');
      }
      setModal(false);
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Error');
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('Delete this department?')) return;
    try {
      await api.delete(`/departments/${id}`);
      toast.success('Deleted');
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Cannot delete');
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="font-display text-2xl font-bold text-slate-800">Departments</h1>
          <p className="text-slate-500">Organize staff by academic and admin units</p>
        </div>
        <button onClick={openCreate} className="btn-primary">
          <Plus className="h-4 w-4" /> Add Department
        </button>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {departments.map((d) => (
          <div
            key={d._id}
            className="group relative overflow-hidden rounded-2xl border border-slate-100 bg-white p-6 shadow-card transition hover:shadow-lg hover:border-brand-200"
          >
            <div className="absolute -right-6 -top-6 h-24 w-24 rounded-full bg-brand-50 transition group-hover:bg-brand-100" />
            <div className="relative">
              <div className="mb-4 flex items-start justify-between">
                <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 to-brand-600 text-white shadow-lg shadow-brand-500/30">
                  <Building2 className="h-6 w-6" />
                </div>
                <div className="flex gap-1">
                  <button onClick={() => openEdit(d)} className="rounded-lg p-2 text-slate-400 hover:bg-slate-100 hover:text-brand-600">
                    <Pencil className="h-4 w-4" />
                  </button>
                  <button onClick={() => handleDelete(d._id)} className="rounded-lg p-2 text-slate-400 hover:bg-red-50 hover:text-red-600">
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>
              <h3 className="font-display text-lg font-semibold text-slate-800">{d.name}</h3>
              <span className="mt-1 inline-block rounded-md bg-brand-50 px-2 py-0.5 text-xs font-semibold text-brand-700">
                {d.code}
              </span>
              <p className="mt-3 text-sm text-slate-500 line-clamp-2">{d.description || 'No description'}</p>
              <div className="mt-4 flex items-center justify-between border-t border-slate-100 pt-4 text-sm">
                <span className="text-slate-500">{d.employeeCount || 0} staff</span>
                <span className="font-semibold text-slate-700">{formatCurrency(d.budget)}</span>
              </div>
              {d.headName && (
                <p className="mt-2 text-xs text-slate-400">Head: {d.headName}</p>
              )}
            </div>
          </div>
        ))}
      </div>

      <Modal open={modal} onClose={() => setModal(false)} title={editId ? 'Edit Department' : 'New Department'}>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="mb-1 block text-sm font-medium">Name</label>
            <input className="input-field" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">Code</label>
            <input className="input-field uppercase" value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value.toUpperCase() })} required maxLength={6} />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">Head Name</label>
            <input className="input-field" value={form.headName} onChange={(e) => setForm({ ...form, headName: e.target.value })} />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">Annual Budget</label>
            <input type="number" className="input-field" value={form.budget} onChange={(e) => setForm({ ...form, budget: Number(e.target.value) })} />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">Description</label>
            <textarea className="input-field" rows={3} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
          </div>
          <div className="flex justify-end gap-3">
            <button type="button" onClick={() => setModal(false)} className="btn-secondary">Cancel</button>
            <button type="submit" className="btn-primary">{editId ? 'Update' : 'Create'}</button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
