"use client";

import { useEffect, useState } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Loader2, Calendar, Clock, BookOpen, User } from "lucide-react";
import { toast } from "sonner";

interface ScheduleItem {
  id: string;
  hari: string;
  jamMulai: string;
  jamSelesai: string;
  mapel: { namaMapel: string };
  guru: { nama: string };
}

const HARI_ORDER: Record<string, number> = {
  SENIN: 1,
  nSENIN: 1,
  SELASA: 2,
  RABU: 3,
  KAMIS: 4,
  JUMAT: 5,
  SABTU: 6,
  MINGGU: 7,
};

const DAY_NAMES = ["MINGGU", "SENIN", "SELASA", "RABU", "KAMIS", "JUMAT", "SABTU"];

export function ScheduleView() {
  const [schedule, setSchedule] = useState<ScheduleItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [rombelName, setRombelName] = useState("");

  useEffect(() => {
    fetchSchedule();
  }, []);

  const fetchSchedule = async () => {
    try {
      const res = await fetch("/api/siswa/schedule");
      const data = await res.json();
      if (data.success) {
        // Sort by Day then Time
        const sorted = data.data.sort((a: ScheduleItem, b: ScheduleItem) => {
          const dayA = HARI_ORDER[a.hari.toUpperCase()] || 99;
          const dayB = HARI_ORDER[b.hari.toUpperCase()] || 99;
          if (dayA !== dayB) return dayA - dayB;
          return a.jamMulai.localeCompare(b.jamMulai);
        });
        setSchedule(sorted);
        setRombelName(data.rombels?.namaRombel || "-");
      } else {
        toast.error(data.message || "Gagal memuat jadwal");
      }
    } catch (error) {
      console.error(error);
      toast.error("Terjadi kesalahan sistem");
    } finally {
      setLoading(false);
    }
  };

  const getTodaySchedule = () => {
    const todayIndex = new Date().getDay(); // 0-6
    const todayName = DAY_NAMES[todayIndex];
    return schedule.filter((s) => s.hari.toUpperCase() === todayName);
  };

  const groupedSchedule = schedule.reduce(
    (acc, curr) => {
      const day = curr.hari.toUpperCase();
      if (!acc[day]) acc[day] = [];
      acc[day].push(curr);
      return acc;
    },
    {} as Record<string, ScheduleItem[]>,
  );

  if (loading) {
    return (
      <div className="flex justify-center p-8">
        <Loader2 className="text-primary h-8 w-8 animate-spin" />
      </div>
    );
  }

  if (schedule.length === 0) {
    return <div className="text-muted-foreground p-8 text-center">Belum ada jadwal pelajaran.</div>;
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="flex items-center gap-2 text-xl font-bold">
          <Calendar className="h-5 w-5" />
          Jadwal Pelajaran - {rombelName}
        </h2>
      </div>

      <Tabs defaultValue="daily" className="w-full">
        <TabsList className="grid w-full max-w-[400px] grid-cols-2">
          <TabsTrigger value="daily">Harian (Hari Ini)</TabsTrigger>
          <TabsTrigger value="weekly">Mingguan</TabsTrigger>
        </TabsList>

        <TabsContent value="daily" className="mt-4">
          <div className="space-y-4">
            <h3 className="mb-2 text-lg font-semibold">Jadwal Hari Ini ({DAY_NAMES[new Date().getDay()]})</h3>
            {getTodaySchedule().length > 0 ? (
              getTodaySchedule().map((item) => <ScheduleCard key={item.id} item={item} />)
            ) : (
              <p className="text-muted-foreground italic">Tidak ada jadwal hari ini.</p>
            )}
          </div>
        </TabsContent>

        <TabsContent value="weekly" className="mt-4">
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {Object.keys(HARI_ORDER)
              .sort((a, b) => HARI_ORDER[a] - HARI_ORDER[b])
              .map((day) => {
                if (!groupedSchedule[day]) return null;
                return (
                  <Card key={day} className="h-full">
                    <CardHeader className="bg-muted/50 pb-2">
                      <CardTitle className="text-center text-base font-bold">{day}</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3 pt-4">
                      {groupedSchedule[day].map((item) => (
                        <div key={item.id} className="border-b pb-2 text-sm last:border-0 last:pb-0">
                          <div className="flex justify-between font-semibold">
                            <span>{item.mapel.namaMapel}</span>
                            <Badge variant="outline" className="text-xs">
                              {item.jamMulai} - {item.jamSelesai}
                            </Badge>
                          </div>
                          <p className="text-muted-foreground mt-1 flex items-center gap-1 text-xs">
                            <User className="h-3 w-3" /> {item.guru.nama}
                          </p>
                        </div>
                      ))}
                    </CardContent>
                  </Card>
                );
              })}
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}

function ScheduleCard({ item }: { item: ScheduleItem }) {
  return (
    <Card>
      <CardContent className="flex flex-col justify-between gap-4 p-4 md:flex-row md:items-center">
        <div className="flex items-start gap-3">
          <div className="bg-primary/10 text-primary rounded-lg p-2">
            <BookOpen className="h-6 w-6" />
          </div>
          <div>
            <h4 className="text-lg font-bold">{item.mapel.namaMapel}</h4>
            <p className="text-muted-foreground flex items-center gap-1 text-sm">
              <User className="h-4 w-4" /> {item.guru.nama}
            </p>
          </div>
        </div>
        <div className="bg-muted flex w-fit items-center gap-2 rounded-full px-3 py-1 text-sm font-medium">
          <Clock className="h-4 w-4" />
          {item.jamMulai} - {item.jamSelesai}
        </div>
      </CardContent>
    </Card>
  );
}
