import { useState, useEffect } from 'react';
import api from '../store/auth';
import { query, execute } from '../lib/db';
import { v4 as uuidv4 } from 'uuid';
import { Avatar } from '../components/Avatar';
import { 
  ChevronRight, Save, Download, Calendar as CalendarIcon, 
  Users, BookOpen, Clock, UserCheck, UserX, AlertCircle, 
  Info, Search, MoreHorizontal, Cloud, CloudOff
} from 'lucide-react';

/**
 * Normalise API list responses: some endpoints return a flat array, others
 * wrap in `{ users: [...] }`, `{ classes: [...] }`, etc. Always coerce to
 * an array so callers can safely `.map` / `.filter` without crashing.
 */
const unwrapList = (data: any): any[] => {
  if (Array.isArray(data)) return data;
  if (Array.isArray(data?.users)) return data.users;
  if (Array.isArray(data?.classes)) return data.classes;
  if (Array.isArray(data?.records)) return data.records;
  return [];
};

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>>({});
  const [remarks, setRemarks] = useState<Record<number, string>>({});
  const [saving, setSaving] = useState(false);
  const [isOffline, setIsOffline] = useState(false);

  useEffect(() => {
    // Load metadata from Local DB or API
    loadClasses();
    loadStudents();
    
    // Listen for sync completion to refresh data
    const handleSync = () => {
      loadStudents();
      loadAttendance();
    };
    window.addEventListener('sync_complete', handleSync);
    return () => window.removeEventListener('sync_complete', handleSync);
  }, []);

  useEffect(() => {
    loadAttendance();
  }, [selectedClass, selectedDate]);

  const loadClasses = async () => {
    try {
      const local = await query("SELECT * FROM classes");
      if (Array.isArray(local) && local.length > 0) {
        setClasses(local);
        return;
      }
    } catch (e) {
      console.warn('Local classes query failed, trying API:', e);
    }

    try {
      const res = await api.get('/classes');
      setClasses(unwrapList(res.data));
    } catch (e) {
      console.error('Failed to load classes:', e);
      setClasses([]);
    }
  };

  const loadStudents = async () => {
    try {
      const local = await query("SELECT * FROM users WHERE role = 'student'");
      if (Array.isArray(local) && local.length > 0) {
        setStudents(local);
        return;
      }
    } catch (e) {
      console.warn('Local students query failed, trying API:', e);
    }

    try {
      const res = await api.get('/users?role=student');
      setStudents(unwrapList(res.data));
    } catch (e) {
      console.error('Failed to load students:', e);
      setStudents([]);
    }
  };

  const loadAttendance = async () => {
    try {
      let localQuery = 'SELECT * FROM attendance WHERE date = ?';
      const params: any[] = [selectedDate];
      if (selectedClass) {
        localQuery += ' AND class_id = ?';
        params.push(parseInt(selectedClass));
      }
      
      const local = await query(localQuery, params);
      if (Array.isArray(local) && local.length > 0) {
        const rec: Record<number, string> = {};
        local.forEach((a: any) => { if (a && a.student_id) rec[a.student_id] = a.status; });
        setRecords(rec);
        setAttendance(local);
        return;
      }
    } catch (e) {
      console.warn('Local attendance query failed, trying API:', e);
    }

    try {
      const apiParams: any = { date: selectedDate };
      if (selectedClass) apiParams.class_id = selectedClass;
      const res = await api.get('/attendance', { params: apiParams });
      const rows = unwrapList(res.data);
      setAttendance(rows);
      const rec: Record<number, string> = {};
      rows.forEach((a: any) => { if (a && a.student_id) rec[a.student_id] = a.status; });
      setRecords(rec);
    } catch (e) {
      console.error('Failed to load attendance:', e);
      setAttendance([]);
      setRecords({});
      setIsOffline(true);
    }
  };

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

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

    try {
      // 1. Save to Local SQLite for immediate offline feedback
      for (const r of entries) {
        await execute(`
          INSERT INTO attendance (uid, student_id, class_id, date, status, sync_status, updated_at)
          VALUES (?, ?, ?, ?, ?, 'pending', CURRENT_TIMESTAMP)
          ON CONFLICT(uid) DO UPDATE SET status = EXCLUDED.status, sync_status = 'pending', updated_at = CURRENT_TIMESTAMP
        `, [r.uid, r.student_id, r.class_id, r.date, r.status]);
      }

      // 2. Try to sync to Hub immediately (Fire and forget)
      api.post('/attendance/bulk', { records: entries }).catch(() => {
        console.warn('Sync to Hub failed, data saved locally and will sync later.');
        setIsOffline(true);
      });

      alert('Attendance recorded locally! Syncing with network...');
    } catch (err) {
      console.error('Failed to save attendance', err);
      alert('Save failed. Check console for details.');
    }
  };

  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>
          <div className="flex items-center gap-3 mb-1">
            <h2 className="text-3xl font-black text-text tracking-tight uppercase">Attendance</h2>
            <div className={`flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[0.6rem] font-black uppercase tracking-widest ${isOffline ? 'bg-orange-500/10 text-orange-500 border border-orange-500/20' : 'bg-emerald-500/10 text-emerald-500 border border-emerald-500/20'}`}>
              {isOffline ? <CloudOff size={12} /> : <Cloud size={12} />}
              {isOffline ? 'Offline Mode' : 'Connected to Hub'}
            </div>
          </div>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center">
            <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
            onClick={() => {
              if (students.length === 0) return;
              const headers = ['Student', 'ID', 'Date', 'Status'];
              const rows = students.map((s: any) => {
                const status = records[s.id] || '';
                return [s.first_name + ' ' + s.last_name, `STU-2024-${String(s.id).padStart(3, '0')}`, selectedDate, status];
              });
              const csv = [headers, ...rows].map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
              const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
              const url = URL.createObjectURL(blob);
              const a = document.createElement('a');
              a.href = url;
              a.download = `attendance_${selectedDate}.csv`;
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
              URL.revokeObjectURL(url);
            }}
            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-background-alt/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-dark transition-all shadow-lg shadow-primary/10 active:scale-95"
            onClick={saveAttendance}
          >
            <Save size={18} />
            Commit Register
          </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-950 dark:bg-primary/10 border border-primary/20 rounded-2xl p-4 shadow-lg shadow-primary/5">
          <label className="block text-[0.6rem] font-black uppercase tracking-widest text-text-muted/60 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-text 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-background-alt/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/50">
              {students.map((student, idx) => (
                <tr key={student.id} className="hover:bg-background-alt/40 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-background-alt overflow-hidden flex-shrink-0 border border-border shadow-inner group-hover:scale-105 transition-transform flex items-center justify-center">
                        <Avatar 
                          src={`https://api.dicebear.com/9.x/initials/svg?seed=${student.id}`} 
                          firstName={student.first_name} 
                          lastName={student.last_name} 
                        />
                      </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-primary bg-primary shadow-md shadow-primary/20'
                            : 'border-border bg-background 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-background-alt/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-500' : 'text-text'}
                        `}
                        placeholder="Add note..." 
                        type="text"
                        value={remarks[student.id] || ''}
                        onChange={(e) => setRemarks({ ...remarks, [student.id]: e.target.value })}
                      />
                    </div>
                  </td>
                </tr>
              ))}
              {students.length === 0 && (
                <tr>
                  <td colSpan={6} className="py-20 text-center">
                    <Users size={40} className="mx-auto text-text-muted/20 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-background-alt/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>
  );
}