import { API_BASE_URL } from '../../lib/config';
import React, { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Users, 
  UserPlus, 
  Trash2, 
  X, 
  Check, 
  Search,
  Mail,
  Building2,
  GraduationCap,
  ShieldCheck
} from 'lucide-react';
import { useAuth } from '../../context/AuthContext';
import { cn } from '../../lib/utils';
import { Pagination } from './Pagination';

interface StudentUser {
  id: number;
  fullName: string;
  email: string;
  role: string;
  department: string;
  year?: string;
  section?: string;
  regNo?: string;
  phone?: string;
  collegeName?: string;
}

export const ManageStudentsView: React.FC = () => {
  const { user } = useAuth();
  const [students, setStudents] = useState<StudentUser[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [formData, setFormData] = useState({
    fullName: '',
    email: '',
    regNo: '',
  });

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

  const fetchStudents = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/admin/users');
      if (response.ok) {
        const data = await response.json();
        // Filter only students belonging to this Class Incharge's class
        const classStudents = data.filter((u: any) => 
          u.role === 'STUDENT' &&
          u.department?.trim().toLowerCase() === user?.inchargeClass?.trim().toLowerCase() &&
          u.year?.trim().toLowerCase() === user?.inchargeBatch?.trim().toLowerCase() &&
          u.section?.trim().toLowerCase() === user?.inchargeSection?.trim().toLowerCase()
        );
        setStudents(classStudents);
      }
    } catch (error) {
      console.error('Failed to fetch students:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleOpenModal = () => {
    setFormData({
      fullName: '',
      email: '',
      regNo: '',
    });
    setIsModalOpen(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Prepare the student payload mapped to this class incharge's class
    const payload = {
      fullName: formData.fullName.trim(),
      email: formData.email.trim().toLowerCase(),
      role: 'STUDENT',
      department: user?.inchargeClass,
      year: user?.inchargeBatch,
      section: user?.inchargeSection,
      regNo: formData.regNo.trim() || 'REG-' + Math.floor(100000 + Math.random() * 900000),
      password: 'student123', // default password
      collegeName: 'Rajalakshmi Institute of Technology',
      gender: 'Male',
      phone: ''
    };

    try {
      const response = await fetch(API_BASE_URL + '/api/admin/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      if (response.ok) {
        fetchStudents();
        setIsModalOpen(false);
      } else {
        const err = await response.json();
        alert(err.message || 'Failed to add student');
      }
    } catch (error) {
      console.error('Operation failed:', error);
      alert('An error occurred during submission.');
    }
  };

  const handleDelete = async (id: number) => {
    if (window.confirm('Are you sure you want to remove this student from your class?')) {
      try {
        const response = await fetch(`${API_BASE_URL}/api/admin/users/${id}`, {
          method: 'DELETE'
        });
        if (response.ok) {
          setStudents(prev => prev.filter(u => u.id !== id));
        } else {
          alert('Failed to delete student');
        }
      } catch (error) {
        console.error('Delete failed:', error);
      }
    }
  };

  const filteredStudents = students
    .filter(u => 
      u.fullName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      u.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (u.regNo && u.regNo.toLowerCase().includes(searchTerm.toLowerCase()))
    )
    .sort((a, b) => b.id - a.id);

  const currentStudents = filteredStudents.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  return (
    <div className="space-y-8">
      {/* Header Info */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h2 className="text-3xl font-black text-text-dark tracking-tight">Manage Students</h2>
          <p className="text-text-muted font-medium">Add and manage students in your assigned class.</p>
        </div>
        
        <button 
          onClick={handleOpenModal}
          className="flex items-center gap-2 bg-brand-navy text-white px-6 py-3 rounded-xl font-black text-[10px] uppercase tracking-widest premium-shadow hover:scale-105 transition-all"
        >
          <UserPlus className="w-4 h-4" />
          Add Student
        </button>
      </div>

      {/* Class Profile Card */}
      <div className="bg-white p-6 rounded-[2rem] border border-slate-100 premium-shadow flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 bg-brand-glow text-brand-indigo rounded-2xl flex items-center justify-center">
            <GraduationCap className="w-6 h-6" />
          </div>
          <div>
            <p className="text-[10px] font-black uppercase tracking-widest text-text-muted">Assigned Class Profile</p>
            <h3 className="text-lg font-black text-text-dark">
              {user?.inchargeClass} &bull; {user?.inchargeBatch} &bull; Section {user?.inchargeSection}
            </h3>
          </div>
        </div>
        <div className="px-4 py-2 bg-emerald-50 text-emerald-600 border border-emerald-100 rounded-2xl text-xs font-black uppercase tracking-widest">
          Incharge Mode
        </div>
      </div>

      {/* Students List */}
      <div className="bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden">
        <div className="p-6 border-b border-slate-50 flex items-center justify-between gap-4">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
            <input 
              type="text" 
              placeholder="Search by name, email or roll no..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full bg-slate-50 border-transparent rounded-xl py-2 pl-10 pr-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
            />
          </div>
          <div className="text-[10px] font-black uppercase tracking-widest text-text-muted">
            Total Class Strength: {students.length}
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-slate-50/50">
                <th className="px-8 py-5 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">Student Details</th>
                <th className="px-8 py-5 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">Roll No / Reg No</th>
                <th className="px-8 py-5 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">College</th>
                <th className="px-8 py-5 text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {isLoading ? (
                <tr>
                  <td colSpan={4} className="text-center py-10 text-xs font-bold text-text-muted">
                    Loading student data...
                  </td>
                </tr>
              ) : currentStudents.length === 0 ? (
                <tr>
                  <td colSpan={4} className="text-center py-10 text-xs font-bold text-text-muted italic">
                    No students registered in this class.
                  </td>
                </tr>
              ) : (
                currentStudents.map((stud) => (
                  <tr key={stud.id} className="group hover:bg-slate-50/50 transition-colors">
                    <td className="px-8 py-5">
                      <div className="flex items-center gap-4">
                        <div className="w-10 h-10 rounded-full bg-brand-glow flex items-center justify-center text-brand-indigo font-black text-xs">
                          {stud.fullName.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase()}
                        </div>
                        <div className="flex flex-col">
                          <span className="font-bold text-text-dark text-sm">{stud.fullName}</span>
                          <span className="text-xs text-text-muted">{stud.email}</span>
                        </div>
                      </div>
                    </td>
                    <td className="px-8 py-5 text-sm font-bold text-text-secondary">
                      {stud.regNo || 'N/A'}
                    </td>
                    <td className="px-8 py-5 text-sm font-bold text-text-secondary">
                      {stud.collegeName || 'Rajalakshmi Institute of Technology'}
                    </td>
                    <td className="px-8 py-5">
                      <button 
                        onClick={() => handleDelete(stud.id)}
                        className="p-2 bg-slate-50 hover:bg-red-50 text-slate-400 hover:text-red-500 rounded-xl transition-all opacity-0 group-hover:opacity-100"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        
        {filteredStudents.length > 0 && (
          <Pagination 
            currentPage={currentPage}
            totalItems={filteredStudents.length}
            itemsPerPage={itemsPerPage}
            onPageChange={setCurrentPage}
            onItemsPerPageChange={(val) => {
              setItemsPerPage(val);
              setCurrentPage(1);
            }}
            itemsPerPageOptions={[5, 10, 20]}
          />
        )}
      </div>

      {/* Add Student Modal */}
      <AnimatePresence>
        {isModalOpen && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsModalOpen(false)}
              className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.9, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.9, y: 20 }}
              className="relative w-full max-w-md bg-white rounded-[2.5rem] premium-shadow overflow-hidden flex flex-col"
            >
              <form onSubmit={handleSubmit} className="flex flex-col">
                <div className="p-8 bg-brand-navy text-white flex justify-between items-start shrink-0">
                  <div>
                    <h3 className="text-2xl font-black tracking-tight">Add Student</h3>
                    <p className="text-white/60 text-xs font-medium mt-1">Register student for {user?.inchargeClass} &bull; Sec {user?.inchargeSection}.</p>
                  </div>
                  <button 
                    type="button"
                    onClick={() => setIsModalOpen(false)}
                    className="p-2 hover:bg-white/10 rounded-xl transition-all"
                  >
                    <X className="w-6 h-6" />
                  </button>
                </div>

                <div className="p-8 space-y-5">
                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Student Name</label>
                    <input 
                      type="text"
                      required
                      value={formData.fullName}
                      onChange={(e) => setFormData({...formData, fullName: e.target.value})}
                      placeholder="E.g. John Doe"
                      className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
                    />
                  </div>

                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">College Email ID</label>
                    <div className="relative">
                      <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" />
                      <input 
                        type="email"
                        required
                        value={formData.email}
                        onChange={(e) => setFormData({...formData, email: e.target.value})}
                        placeholder="john.doe@ritchennai.edu.in"
                        className="w-full bg-slate-50 border-transparent rounded-xl py-3 pl-12 pr-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-2 block">Register / Roll Number (Optional)</label>
                    <input 
                      type="text"
                      value={formData.regNo}
                      onChange={(e) => setFormData({...formData, regNo: e.target.value})}
                      placeholder="E.g. 211822104001"
                      className="w-full bg-slate-50 border-transparent rounded-xl py-3 px-4 text-sm focus:bg-white focus:border-brand-indigo transition-all"
                    />
                  </div>
                </div>

                <div className="shrink-0 w-full">
                  <button 
                    type="submit"
                    className="w-full bg-brand-navy hover:bg-[#0c365c] text-white py-5 font-black text-xs uppercase tracking-[0.2em] transition-all flex items-center justify-center"
                  >
                    Add Student to Class
                  </button>
                </div>
              </form>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
};
