import { useEffect, useState } from 'react';
import { Plus, Search, Pencil, Trash2, GraduationCap } from 'lucide-react';
import { Link } from 'react-router-dom';
import toast from 'react-hot-toast';
import api from '../api/axios';
import Modal from '../components/Modal';
import { formatCurrency, statusColors } from '../utils/format';

const GRADES = ['Grade 6', 'Grade 7', 'Grade 8', 'Grade 9', 'Grade 10', 'Grade 11', 'Grade 12'];
const SECTIONS = ['A', 'B', 'C', 'D'];

const emptyForm = {
  studentId: '',
  firstName: '',
  lastName: '',
  email: '',
  phone: '',
  grade: 'Grade 10',
  section: 'A',
  parentName: '',
  parentPhone: '',
  enrollmentDate: new Date().toISOString().slice(0, 10),
  status: 'active',
  tuitionFee: 0,
};

export default function Students() {
  const [students, setStudents] = useState([]);
  const [search, setSearch] = useState('');
  const [modal, setModal] = useState(false);
  const [form, setForm] = useState(emptyForm);
  const [editId, setEditId] = useState(null);
  const [loading, setLoading] = useState(true);

  const load = () => {
    api
      .get('/students', { params: { search: search || undefined } })
      .then((res) => setStudents(res.data))
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    const t = setTimeout(load, 300);
    return () => clearTimeout(t);
  }, [search]);

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

  const openEdit = (s) => {
    setForm({
      ...s,
      enrollmentDate: s.enrollmentDate?.slice(0, 10),
    });
    setEditId(s._id);
    setModal(true);
  };

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

  const handleDelete = async (id) => {
    if (!confirm('Delete this student and all their payments?')) return;
    try {
      await api.delete(`/students/${id}`);
      toast.success('Deleted');
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Delete failed');
    }
  };

  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">Students</h1>
          <p className="text-slate-500">Manage enrolled students and tuition balances</p>
        </div>
        <button onClick={openCreate} className="btn-primary">
          <Plus className="h-4 w-4" /> Add Student
        </button>
      </div>

      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
        <input
          className="input-field pl-10"
          placeholder="Search students..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {loading ? (
          [...Array(3)].map((_, i) => (
            <div key={i} className="h-48 animate-pulse rounded-2xl bg-slate-200" />
          ))
        ) : students.length === 0 ? (
          <p className="col-span-full py-12 text-center text-slate-400">No students found</p>
        ) : (
          students.map((s) => (
            <div
              key={s._id}
              className="group rounded-2xl border border-slate-100 bg-white p-5 shadow-card transition hover:border-violet-200 hover:shadow-lg"
            >
              <div className="flex items-start justify-between">
                <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-violet-500 to-purple-600 text-white">
                  <GraduationCap className="h-6 w-6" />
                </div>
                <div className="flex gap-1">
                  <button
                    onClick={() => openEdit(s)}
                    className="rounded-lg p-2 text-slate-400 hover:bg-violet-50 hover:text-violet-600"
                  >
                    <Pencil className="h-4 w-4" />
                  </button>
                  <button
                    onClick={() => handleDelete(s._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="mt-3 font-display font-semibold text-slate-800">
                {s.firstName} {s.lastName}
              </h3>
              <p className="text-xs text-slate-400">{s.studentId}</p>
              <div className="mt-2 flex gap-2">
                <span className="rounded-md bg-violet-50 px-2 py-0.5 text-xs font-medium text-violet-700">
                  {s.grade} · {s.section}
                </span>
                <span className={`rounded-full px-2 py-0.5 text-xs font-medium capitalize ${statusColors[s.status]}`}>
                  {s.status}
                </span>
              </div>
              <div className="mt-4 grid grid-cols-3 gap-2 border-t border-slate-100 pt-4 text-center text-xs">
                <div>
                  <p className="text-slate-400">Tuition</p>
                  <p className="font-semibold text-slate-700">{formatCurrency(s.tuitionFee)}</p>
                </div>
                <div>
                  <p className="text-slate-400">Paid</p>
                  <p className="font-semibold text-emerald-600">{formatCurrency(s.totalPaid)}</p>
                </div>
                <div>
                  <p className="text-slate-400">Balance</p>
                  <p className={`font-semibold ${s.balance > 0 ? 'text-amber-600' : 'text-emerald-600'}`}>
                    {formatCurrency(s.balance)}
                  </p>
                </div>
              </div>
              <Link
                to={`/student-payments?student=${s._id}`}
                className="mt-4 block w-full rounded-xl bg-violet-50 py-2 text-center text-sm font-medium text-violet-700 transition hover:bg-violet-100"
              >
                Record payment
              </Link>
            </div>
          ))
        )}
      </div>

      <Modal open={modal} onClose={() => setModal(false)} title={editId ? 'Edit Student' : 'Add Student'} wide>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="mb-1 block text-sm font-medium">Student ID</label>
              <input className="input-field" value={form.studentId} onChange={(e) => setForm({ ...form, studentId: e.target.value })} required disabled={!!editId} />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Enrollment Date</label>
              <input type="date" className="input-field" value={form.enrollmentDate} onChange={(e) => setForm({ ...form, enrollmentDate: e.target.value })} required />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">First Name</label>
              <input className="input-field" value={form.firstName} onChange={(e) => setForm({ ...form, firstName: e.target.value })} required />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Last Name</label>
              <input className="input-field" value={form.lastName} onChange={(e) => setForm({ ...form, lastName: e.target.value })} required />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Grade</label>
              <select className="input-field" value={form.grade} onChange={(e) => setForm({ ...form, grade: e.target.value })}>
                {GRADES.map((g) => (
                  <option key={g} value={g}>{g}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Section</label>
              <select className="input-field" value={form.section} onChange={(e) => setForm({ ...form, section: e.target.value })}>
                {SECTIONS.map((sec) => (
                  <option key={sec} value={sec}>{sec}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Annual Tuition Fee</label>
              <input type="number" className="input-field" value={form.tuitionFee} onChange={(e) => setForm({ ...form, tuitionFee: Number(e.target.value) })} required />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Status</label>
              <select className="input-field" value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}>
                <option value="active">Active</option>
                <option value="graduated">Graduated</option>
                <option value="withdrawn">Withdrawn</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Parent Name</label>
              <input className="input-field" value={form.parentName} onChange={(e) => setForm({ ...form, parentName: e.target.value })} />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Parent Phone</label>
              <input className="input-field" value={form.parentPhone} onChange={(e) => setForm({ ...form, parentPhone: e.target.value })} />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Email</label>
              <input type="email" className="input-field" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium">Phone</label>
              <input className="input-field" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
            </div>
          </div>
          <div className="flex justify-end gap-3 pt-2">
            <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>
  );
}
