import { useState, useEffect } from 'react';
import api from '../store/auth';
import { 
  ChevronRight, Save, Download, Calendar as CalendarIcon, 
  Users, BookOpen, Clock, UserCheck, UserX, AlertCircle, 
  Info, Search, MoreHorizontal
} from 'lucide-react';

export default function Attendance() {
  const [students, setStudents] = useState<any[]>([]);
  const [classes, setClasses] = useState<any[]>([]);
  const [attendance, setAttendance] = useState<any[]>([]);
  const [selectedClass, setSelectedClass] = useState('');
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
  const [records, setRecords] = useState<Record<number, string>>({});

  useEffect(() => {
    api.get('/users?role=student').then(res => setStudents(res.data));
    api.get('/classes').then(res => setClasses(res.data));
    loadAttendance();
  }, [selectedClass, selectedDate]);

  const loadAttendance = () => {
    const params: any = { date: selectedDate };
    if (selectedClass) params.class_id = selectedClass;
    api.get('/attendance', { params }).then(res => {
      setAttendance(res.data);
      const rec: Record<number, string> = {};
      res.data.forEach((a: any) => { rec[a.student_id] = a.status; });
      setRecords(rec);
    });
  };

  const handleStatusChange = (studentId: number, status: string) => {
    setRecords({ ...records, [studentId]: status });
  };

  const saveAttendance = async () => {
    const entries = Object.entries(records).map(([studentId, status]) => ({
      student_id: parseInt(studentId),
      class_id: students.find((s: any) => s.id === parseInt(studentId))?.enrollment?.class_id || 1,
      date: selectedDate,
      status
    })).filter(r => r.status);

    await api.post('/attendance/bulk', { records: entries });
    alert('Attendance saved!');
    loadAttendance();
  };

  const selectedClassName = classes.find(c => c.id.toString() === selectedClass)?.name || 'All Classes';

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-10">
      {/* Module Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">Attendance Marking</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Academic Year 2024-25</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Daily Register</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all shadow-sm active:scale-95">
            <Download size={18} />
            Export PDF
          </button>
          <button
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
            onClick={saveAttendance}
          >
            <Save size={18} />
            Submit Attendance
          </button>
        </div>
      </div>

      {/* Filters Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-card border border-border rounded-2xl p-4 shadow-sm group hover:border-primary transition-colors cursor-pointer relative">
          <label className="block text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-2">Class Section</label>
          <div className="flex items-center justify-between">
            <span className="text-lg font-black text-text truncate">{selectedClassName}</span>
            <BookOpen size={18} className="text-text-muted group-hover:text-primary transition-colors" />
          </div>
          <select 
            className="absolute inset-0 opacity-0 cursor-pointer" 
            value={selectedClass} 
            onChange={e => setSelectedClass(e.target.value)}
          >
            <option value="">All Classes</option>
            {classes.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </div>

        <div className="bg-card border border-border rounded-2xl p-4 shadow-sm group hover:border-primary transition-colors cursor-pointer relative">
          <label className="block text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-2">Selected Date</label>
          <div className="flex items-center justify-between">
            <span className="text-lg font-black text-text">
              {new Date(selectedDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
            </span>
            <CalendarIcon size={18} className="text-text-muted group-hover:text-primary transition-colors" />
          </div>
          <input 
            type="date" 
            className="absolute inset-0 opacity-0 cursor-pointer" 
            value={selectedDate} 
            onChange={e => setSelectedDate(e.target.value)} 
          />
        </div>

        <div className="bg-card border border-border rounded-2xl p-4 shadow-sm">
          <label className="block text-[0.6rem] font-black uppercase tracking-widest text-text-muted mb-2">Period / Session</label>
          <div className="flex items-center justify-between">
            <span className="text-lg font-black text-text">Morning Session</span>
            <Clock size={18} className="text-text-muted" />
          </div>
        </div>

        <div className="bg-slate-900 border border-transparent rounded-2xl p-4 shadow-lg shadow-blue-900/10">
          <label className="block text-[0.6rem] font-black uppercase tracking-widest text-white/40 mb-2">Active Proctor</label>
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-full bg-primary flex items-center justify-center text-white font-bold text-xs shadow-inner">
              AD
            </div>
            <span className="text-[0.9rem] font-bold text-white tracking-tight truncate">Administrator</span>
          </div>
        </div>
      </div>

      {/* Attendance Table */}
      <div className="bg-card border border-border rounded-3xl shadow-sm overflow-hidden border-collapse">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-muted/50 border-b border-border">
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Student Name</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest text-center">Present</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest text-center">Absent</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest text-center">Late</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest text-center">Excused</th>
                <th className="px-6 py-4 text-[0.65rem] font-black text-primary uppercase tracking-widest">Remarks</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {students.map((student, idx) => (
                <tr key={student.id} className="hover:bg-muted/30 transition-colors group">
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <div className="w-9 h-9 rounded-xl bg-muted overflow-hidden flex-shrink-0 border border-border shadow-inner group-hover:scale-105 transition-transform">
                        <img 
                          src={`https://i.pravatar.cc/150?u=${student.id}`} 
                          alt={student.first_name} 
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <div>
                        <div className="text-[0.9rem] font-bold text-text">{student.first_name} {student.last_name}</div>
                        <div className="text-[0.65rem] text-text-muted font-black tracking-tighter uppercase">ID: STU-2024-{student.id.toString().padStart(3, '0')}</div>
                      </div>
                    </div>
                  </td>
                  
                  {['present', 'absent', 'late', 'excused'].map(status => (
                    <td key={status} className="px-6 py-4 text-center">
                      <label className="inline-flex items-center justify-center cursor-pointer group/radio relative">
                        <input 
                          type="radio" 
                          name={`att_${student.id}`}
                          className="sr-only"
                          checked={records[student.id] === status}
                          onChange={() => handleStatusChange(student.id, status)}
                        />
                        <div className={`
                          w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all duration-200
                          ${records[student.id] === status 
                            ? status === 'present' ? 'border-emerald-500 bg-emerald-500 shadow-md shadow-emerald-500/20' 
                            : status === 'absent' ? 'border-rose-500 bg-rose-500 shadow-md shadow-rose-500/20' 
                            : status === 'late' ? 'border-amber-500 bg-amber-500 shadow-md shadow-amber-500/20'
                            : 'border-blue-600 bg-blue-600 shadow-md shadow-blue-600/20'
                            : 'border-border bg-card group-hover/radio:border-text-muted'
                          }
                        `}>
                          {records[student.id] === status && (
                            status === 'present' ? <UserCheck size={12} className="text-white" />
                            : status === 'absent' ? <UserX size={12} className="text-white" />
                            : <Clock size={12} className="text-white" />
                          )}
                        </div>
                      </label>
                    </td>
                  ))}

                  <td className="px-6 py-4">
                    <div className="relative group/input">
                      <input 
                        className={`
                          w-full bg-muted/20 border border-border rounded-lg px-3 py-1.5 text-xs font-medium focus:outline-none focus:ring-2 focus:ring-primary/10 focus:border-primary transition-all placeholder:text-text-muted/50
                          ${records[student.id] === 'absent' ? 'text-rose-600' : 'text-text'}
                        `}
                        placeholder="Add note..." 
                        type="text"
                      />
                    </div>
                  </td>
                </tr>
              ))}
              {students.length === 0 && (
                <tr>
                  <td colSpan={6} className="py-20 text-center">
                    <Users size={40} className="mx-auto text-muted mb-4" />
                    <p className="text-text-muted font-bold uppercase tracking-widest text-xs">No students found in this section</p>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Legend & Summary */}
      <div className="flex flex-col sm:flex-row justify-between items-center gap-6 px-4">
        <div className="flex flex-wrap gap-6">
          {[
            { label: 'Present', color: 'emerald' },
            { label: 'Absent', color: 'rose' },
            { label: 'Late', color: 'amber' },
            { label: 'Excused', color: 'blue' },
          ].map(item => (
            <div key={item.label} className="flex items-center gap-2">
              <div className={`w-3 h-3 rounded-full bg-${item.color}-500 shadow-sm shadow-${item.color}-500/20`}></div>
              <span className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{item.label}</span>
            </div>
          ))}
        </div>
        <div className="bg-muted/50 px-6 py-3 rounded-2xl border border-border flex items-center gap-6 shadow-inner">
          <div className="text-center">
            <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Marked</p>
            <p className="text-lg font-black text-primary leading-none">{Object.keys(records).length}</p>
          </div>
          <div className="w-px h-8 bg-border"></div>
          <div className="text-center">
            <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Pending</p>
            <p className="text-lg font-black text-text-muted/50 leading-none">{Math.max(0, students.length - Object.keys(records).length)}</p>
          </div>
        </div>
      </div>
    </div>
  );
}