import { useState, useEffect } from 'react';
import { useStudentStore } from '@/stores/studentStore';
import { useBatchStore } from '@/stores/batchStore';
import { useAttendanceStore } from '@/stores/attendanceStore';
import { useUIStore } from '@/stores/uiStore';
import { Avatar } from '@/components/common';
import { format } from 'date-fns';
import { Loader2, Sun, CalendarX } from 'lucide-react';

export default function AttendanceMarkingScreen() {
  const { students } = useStudentStore();
  const { batches } = useBatchStore();
  const { selectedDate, selectedBatch, stats, isMarking, isHoliday, holidayReason, markAttendance, markHoliday, removeHoliday } = useAttendanceStore();
  const { showToast } = useUIStore();
  const [date, setDate] = useState(selectedDate);
  const [batchId, setBatchId] = useState(selectedBatch);
  const [attendanceMap, setAttendanceMap] = useState<Record<number, boolean>>({});

  const batchStudents = students.filter(s => s.isActive && s.batchId === batchId);

  useEffect(() => {
    const map: Record<number, boolean> = {};
    batchStudents.forEach(s => { map[s.id] = true; });
    setAttendanceMap(map);
  }, [batchId]);

  const handleToggle = (studentId: number) => {
    setAttendanceMap(prev => ({ ...prev, [studentId]: !prev[studentId] }));
  };

  const handleSubmit = async () => {
    const records = batchStudents.map(s => ({
      studentId: s.id,
      batchId: batchId,
      date,
      status: (attendanceMap[s.id] ? 'present' : 'absent') as 'present' | 'absent',
    }));
    await markAttendance(records);
    showToast({ type: 'success', message: `Attendance saved! ${records.filter(r => r.status === 'present').length} present, ${records.filter(r => r.status === 'absent').length} absent` });
  };

  const handleHoliday = async () => {
    await markHoliday(date, batchId, 'Holiday');
    showToast({ type: 'success', message: `Marked as Holiday for ${batchStudents.length} students!` });
  };

  const handleRemoveHoliday = () => {
    removeHoliday(date, batchId);
    showToast({ type: 'info', message: 'Holiday removed. Mark attendance now.' });
  };

  const presentCount = batchStudents.filter(s => attendanceMap[s.id]).length;
  const absentCount = batchStudents.length - presentCount;

  return (
    <div className="px-4 pt-4 pb-4">
      {/* Filters */}
      <div className="grid grid-cols-2 gap-3 mb-4">
        <div>
          <label className="text-xs font-semibold text-gray-500 mb-1 block">Date</label>
          <input type="date" value={date} onChange={e => setDate(e.target.value)}
            className="w-full h-11 px-3 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500" />
        </div>
        <div>
          <label className="text-xs font-semibold text-gray-500 mb-1 block">Batch</label>
          <select value={batchId} onChange={e => setBatchId(parseInt(e.target.value))}
            className="w-full h-11 px-3 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500">
            {batches.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
          </select>
        </div>
      </div>

      {/* Holiday Button */}
      {!isHoliday ? (
        <button onClick={handleHoliday}
          className="w-full h-11 mb-4 bg-amber-100 text-amber-700 font-semibold rounded-xl flex items-center justify-center gap-2 active:scale-[0.98] transition-transform border border-amber-200">
          <Sun className="w-4 h-4" /> Mark Holiday for All
        </button>
      ) : (
        <div className="w-full h-11 mb-4 bg-amber-500 text-white font-semibold rounded-xl flex items-center justify-center gap-2 border border-amber-600">
          <Sun className="w-4 h-4" /> HOLIDAY
          <button onClick={handleRemoveHoliday} className="ml-3 px-2 py-0.5 bg-white/20 rounded text-[10px]">Undo</button>
        </div>
      )}

      {/* Stats Bar */}
      <div className="bg-white rounded-xl p-3 card-shadow flex items-center justify-between mb-4 sticky top-0 z-10">
        <span className="text-xs text-gray-500">Total: <strong className="text-gray-800">{batchStudents.length}</strong></span>
        {isHoliday ? (
          <span className="text-xs text-amber-600 font-bold">HOLIDAY</span>
        ) : (
          <>
            <span className="text-xs text-emerald-600">Present: <strong>{presentCount}</strong></span>
            <span className="text-xs text-red-500">Absent: <strong>{absentCount}</strong></span>
          </>
        )}
      </div>

      {/* Select All / None - hidden on holiday */}
      {!isHoliday && (
        <div className="flex gap-3 mb-3">
          <button onClick={() => {
            const map: Record<number, boolean> = {};
            batchStudents.forEach(s => map[s.id] = true);
            setAttendanceMap(map);
          }} className="text-xs font-medium text-orange-500">Select All</button>
          <button onClick={() => {
            const map: Record<number, boolean> = {};
            batchStudents.forEach(s => map[s.id] = false);
            setAttendanceMap(map);
          }} className="text-xs font-medium text-gray-400">Deselect All</button>
        </div>
      )}

      {/* Student List */}
      <div className="space-y-2">
        {batchStudents.map(student => {
          const isPresent = attendanceMap[student.id] ?? true;
          return (
            <div key={student.id}
              className={`flex items-center justify-between bg-white rounded-xl p-3 card-shadow transition-colors ${
                isHoliday ? 'opacity-50' : !isPresent ? 'border-l-4 border-red-400' : ''
              } ${isHoliday ? 'border-l-4 border-amber-400' : ''}`}>
              <div className="flex items-center gap-3">
                <Avatar name={student.fullName} size="sm" />
                <div>
                  <p className="text-sm font-semibold text-gray-900">{student.fullName}</p>
                  <p className="text-[10px] text-gray-400">{student.studentId}</p>
                </div>
              </div>
              {isHoliday ? (
                <span className="px-2 py-1 bg-amber-100 text-amber-600 text-[10px] font-bold rounded-full">HOLIDAY</span>
              ) : (
                <button onClick={() => handleToggle(student.id)}
                  className={`w-12 h-7 rounded-full p-0.5 transition-all duration-200 ${isPresent ? 'bg-orange-500' : 'bg-gray-300'}`}>
                  <div className={`w-6 h-6 rounded-full bg-white shadow-sm transition-transform duration-200 ${isPresent ? 'translate-x-5' : 'translate-x-0'}`} />
                </button>
              )}
            </div>
          );
        })}
      </div>

      {batchStudents.length === 0 && (
        <div className="text-center py-12 text-gray-400 text-sm">No students in this batch</div>
      )}

      {/* Submit - hidden on holiday */}
      {!isHoliday && (
        <div className="fixed bottom-20 left-4 right-4 z-40">
          <button onClick={handleSubmit} disabled={isMarking || batchStudents.length === 0}
            className="w-full h-12 brand-gradient text-white font-semibold rounded-xl button-shadow flex items-center justify-center gap-2 disabled:opacity-50 active:scale-[0.98] transition-transform">
            {isMarking ? <Loader2 className="w-5 h-5 animate-spin" /> : `Save Attendance (${presentCount} present, ${absentCount} absent)`}
          </button>
        </div>
      )}
    </div>
  );
}
