import React, { useEffect, useState } from 'react';
import axios from 'axios';
import PageLayout from '../components/PageLayout';

function Students() {
  const [students, setStudents] = useState([]);
  const [user, setUser] = useState(null);
  const [name, setName] = useState('');
  const [studentClass, setStudentClass] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [editId, setEditId] = useState(null);
  const [message, setMessage] = useState('');

  const headers = {
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  };

  const clearForm = () => {
    setName('');
    setStudentClass('');
    setEmail('');
    setPhone('');
    setEditId(null);
  };

  const handleGet = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/student/getstudent', { headers });
      setStudents(res.data);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    const stored = localStorage.getItem('user');
    if (stored) setUser(JSON.parse(stored));
    handleGet();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editId) {
        await axios.put(
          `http://localhost:5001/api/student/updatestudent/${editId}`,
          { name, studentClass, email, phone },
          { headers }
        );
        setMessage('Updated successfully');
      } else {
        await axios.post(
          'http://localhost:5001/api/student/addstudent',
          { name, studentClass, email, phone },
          { headers }
        );
        setMessage('Added successfully');
      }
      clearForm();
      handleGet();
    } catch (error) {
      console.log(error);
      setMessage('Something went wrong');
    }
  };

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:5001/api/student/deletestudent/${id}`, { headers });
      handleGet();
    } catch (error) {
      console.log(error);
    }
  };

  const handleEdit = (student) => {
    setName(student.name);
    setStudentClass(student.studentClass);
    setEmail(student.email);
    setPhone(student.phone);
    setEditId(student._id);
  };

  const isAdmin = user && user.role === 'admin';

  return (
    <PageLayout title="Student management">
      {message && <p className="lms-alert-success">{message}</p>}

      {isAdmin && (
        <form onSubmit={handleSubmit} className="lms-form-panel mb-6">
          <input
            type="text"
            placeholder="Student name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="lms-input"
            required
          />
          <input
            type="text"
            placeholder="Class"
            value={studentClass}
            onChange={(e) => setStudentClass(e.target.value)}
            className="lms-input"
            required
          />
          <input
            type="text"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="lms-input"
            required
          />
          <input
            type="text"
            placeholder="Phone"
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            className="lms-input"
            required
          />
          <button type="submit" className="lms-btn-primary">
            {editId ? 'Update' : 'Add student'}
          </button>
        </form>
      )}

      <div className="space-y-3">
        {students.map((student) => (
          <div key={student._id} className="lms-list-item">
            <p className="font-medium text-white">{student.name}</p>
            <p className="mt-1 text-sm text-slate-400">Class: {student.studentClass}</p>
            <p className="text-sm text-slate-400">{student.email} · {student.phone}</p>
            {isAdmin && (
              <div className="mt-3 flex gap-4 text-sm">
                <button type="button" onClick={() => handleEdit(student)} className="text-blue-400 hover:text-blue-300">
                  Edit
                </button>
                <button type="button" onClick={() => handleDelete(student._id)} className="text-red-400 hover:text-red-300">
                  Delete
                </button>
              </div>
            )}
          </div>
        ))}
      </div>
    </PageLayout>
  );
}

export default Students;
