import { Card, CardContent } from "@/components/ui/card";
import { useTimetable } from "@/hooks/queries";
import type { TimetableSession } from "@/types";

const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] as const;
const hours = ["08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00"];

const SESSION_COLOR = "hsl(192, 82%, 32%)";

function isStart(sessions: TimetableSession[], day: string, hour: string) {
  return sessions.find(s => s.day === day && s.start_time === hour);
}

function getSessionAt(sessions: TimetableSession[], day: string, hour: string) {
  return sessions.find(s => s.day === day && s.start_time <= hour && s.end_time > hour);
}

export default function TeacherTimetable() {
  const { data: timetableSessions = [], isLoading } = useTimetable();
  if (isLoading) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;

  const mySessions = timetableSessions;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">My Timetable</h1>
        <p className="text-muted-foreground">Your weekly teaching schedule.</p>
      </div>

      <Card>
        <CardContent className="pt-6 overflow-x-auto">
          <div className="min-w-[700px]">
            <div className="grid grid-cols-6 gap-1">
              <div className="text-xs font-medium text-muted-foreground p-2" />
              {days.map(d => <div key={d} className="text-xs font-semibold text-center p-2 bg-muted rounded">{d}</div>)}
            </div>
            {hours.map(hour => (
              <div key={hour} className="grid grid-cols-6 gap-1 min-h-[48px]">
                <div className="text-xs text-muted-foreground p-2 flex items-start">{hour}</div>
                {days.map(day => {
                  const session = isStart(mySessions, day, hour);
                  const occupied = getSessionAt(mySessions, day, hour);
                  if (session) {
                    return (
                      <div key={day} className="rounded-md p-2 text-xs text-white" style={{ backgroundColor: SESSION_COLOR }}>
                        <p className="font-semibold">{session.course_name}</p>
                        <p className="opacity-80">{session.batch_name}</p>
                        <p className="opacity-70">{session.room}</p>
                      </div>
                    );
                  }
                  if (occupied) return <div key={day} />;
                  return <div key={day} className="border border-dashed border-border/50 rounded-md" />;
                })}
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
