import { useState, useEffect } from 'react';
import api from '../store/auth';
import { UserPlus, Edit, Trash2 } from 'lucide-react';

export default function Students() {
  const [students, setStudents] = useState<any[]>([]);
  const [classes, setClasses] = useState<any[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [form, setForm] = useState({ email: '', password: '', first_name: '', last_name: '', phone: '' });
  const [enrollForm, setEnrollForm] = useState({ student_id: '', class_id: '', roll_number: '' });

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

  const loadData = () => {
    api.get('/users?role=student').then(res => setStudents(res.data));
    api.get('/classes').then(res => setClasses(res.data));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await api.post('/users', { ...form, role: 'student' });
      setShowModal(false);
      setForm({ email: '', password: '', first_name: '', last_name: '', phone: '' });
      loadData();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Error creating student');
    }
  };

  const handleEnroll = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await api.post('/enrollments', enrollForm);
      setEnrollForm({ student_id: '', class_id: '', roll_number: '' });
      alert('Student enrolled successfully!');
    } catch (err) {
      alert('Error enrolling student');
    }
  };

  const deleteStudent = async (id: number) => {
    if (!confirm('Delete this student?')) return;
    await api.delete(`/users/${id}`);
    loadData();
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">Students</h1>
        <button className="btn btn-primary" onClick={() => setShowModal(true)}>
          <UserPlus size={18} /> Add Student
        </button>
      </div>

      <div className="grid grid-2 mb-6">
        <div className="card">
          <h3 className="card-title mb-4">Enroll Student</h3>
          <form onSubmit={handleEnroll}>
            <div className="form-group">
              <label className="form-label">Select Student</label>
              <select className="form-select" value={enrollForm.student_id} onChange={e => setEnrollForm({...enrollForm, student_id: e.target.value})} required>
                <option value="">Choose student...</option>
                {students.map(s => (
                  <option key={s.id} value={s.id}>{s.first_name} {s.last_name}</option>
                ))}
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">Class</label>
              <select className="form-select" value={enrollForm.class_id} onChange={e => setEnrollForm({...enrollForm, class_id: e.target.value})} required>
                <option value="">Choose class...</option>
                {classes.map(c => (
                  <option key={c.id} value={c.id}>{c.name} {c.section}</option>
                ))}
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">Roll Number</label>
              <input className="form-input" value={enrollForm.roll_number} onChange={e => setEnrollForm({...enrollForm, roll_number: e.target.value})} />
            </div>
            <button type="submit" className="btn btn-primary">Enroll</button>
          </form>
        </div>
      </div>

      <div className="card">
        <div className="table-container">
          <table>
            <thead>
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {students.map(student => (
                <tr key={student.id}>
                  <td className="font-medium">{student.first_name} {student.last_name}</td>
                  <td>{student.email}</td>
                  <td>{student.phone || '-'}</td>
                  <td>
                    <button className="btn btn-danger btn-sm" onClick={() => deleteStudent(student.id)}>
                      <Trash2 size={14} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {showModal && (
        <div className="modal-overlay" onClick={() => setShowModal(false)}>
          <div className="modal" onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h2 className="modal-title">Add New Student</h2>
              <button className="modal-close" onClick={() => setShowModal(false)}>×</button>
            </div>
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <label className="form-label">Email</label>
                <input className="form-input" type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} required />
              </div>
              <div className="form-group">
                <label className="form-label">Password</label>
                <input className="form-input" type="password" value={form.password} onChange={e => setForm({...form, password: e.target.value})} required />
              </div>
              <div className="form-group">
                <label className="form-label">First Name</label>
                <input className="form-input" value={form.first_name} onChange={e => setForm({...form, first_name: e.target.value})} required />
              </div>
              <div className="form-group">
                <label className="form-label">Last Name</label>
                <input className="form-input" value={form.last_name} onChange={e => setForm({...form, last_name: e.target.value})} required />
              </div>
              <div className="form-group">
                <label className="form-label">Phone</label>
                <input className="form-input" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} />
              </div>
              <button type="submit" className="btn btn-primary w-full">Create Student</button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}