"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { useAuth } from "@/contexts/auth-context";
import { Calendar, Users, ClipboardList, BookOpen } from "lucide-react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";

export function GuruDashboard() {
  const { user } = useAuth();
  const [data, setData] = useState<{
    totalJamHariIni: number;
    waliKelas: { namaRombel: string } | null;
    jadwalHariIni: any[];
    jadwalSeminggu: any[];
  } | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const today = new Date().toLocaleDateString("id-ID", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  });

  useEffect(() => {
    const fetchDashboard = async () => {
      try {
        const response = await fetch("/api/dashboard/guru");
        const result = await response.json();
        if (result.success) {
          setData(result.data);
        }
      } catch (error) {
        console.error("Failed to fetch dashboard data", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchDashboard();
  }, []);

  return (
    <div className="flex flex-1 flex-col gap-6 p-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Selamat Datang, {user?.name || "Guru"}</h1>
        <p className="text-muted-foreground">Dashboard Pengajar - {today}</p>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Jadwal Hari Ini</CardTitle>
            <Calendar className="text-muted-foreground h-4 w-4" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{isLoading ? "..." : data?.totalJamHariIni || 0} Sesi</div>
            <p className="text-muted-foreground text-xs">
              {data?.jadwalHariIni?.length ? "Kelas aktif hari ini" : "Tidak ada jadwal"}
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Wali Kelas</CardTitle>
            <Users className="text-muted-foreground h-4 w-4" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{isLoading ? "..." : data?.waliKelas?.namaRombel || "-"}</div>
            <p className="text-muted-foreground text-xs">{data?.waliKelas ? "Kelas Anda" : "Anda bukan wali kelas"}</p>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
        <Card className="col-span-4">
          <CardHeader>
            <CardTitle>Jadwal Mengajar</CardTitle>
            <CardDescription>Jadwal pelajaran Anda.</CardDescription>
          </CardHeader>
          <CardContent>
            <Tabs defaultValue="hari-ini" className="w-full">
              <TabsList className="mb-4">
                <TabsTrigger value="hari-ini">Hari Ini</TabsTrigger>
                <TabsTrigger value="seminggu">Seminggu</TabsTrigger>
              </TabsList>

              <TabsContent value="hari-ini">
                {isLoading ? (
                  <div className="p-4 text-center">Loading...</div>
                ) : data?.jadwalHariIni && data.jadwalHariIni.length > 0 ? (
                  <div className="space-y-4">
                    {data.jadwalHariIni.map((jadwal: any) => (
                      <div
                        key={jadwal.id}
                        className="flex items-center justify-between border-b pb-4 last:border-0 last:pb-0"
                      >
                        <div className="space-y-1">
                          <p className="text-sm leading-none font-medium">{jadwal.mapel}</p>
                          <p className="text-muted-foreground text-sm">{jadwal.rombel}</p>
                        </div>
                        <div className="bg-muted rounded border px-2 py-1 text-sm font-medium">{jadwal.jam}</div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="flex h-[200px] items-center justify-center rounded-md border border-dashed">
                    <p className="text-muted-foreground">Tidak ada jadwal hari ini</p>
                  </div>
                )}
              </TabsContent>

              <TabsContent value="seminggu">
                {isLoading ? (
                  <div className="p-4 text-center">Loading...</div>
                ) : data?.jadwalSeminggu && data.jadwalSeminggu.length > 0 ? (
                  <div className="max-h-[300px] space-y-4 overflow-y-auto pr-2">
                    {data.jadwalSeminggu.map((jadwal: any) => (
                      <div
                        key={jadwal.id}
                        className="flex items-center justify-between border-b pb-4 last:border-0 last:pb-0"
                      >
                        <div className="space-y-1">
                          <Badge variant="outline" className="mb-1">
                            {jadwal.hari}
                          </Badge>
                          <p className="text-sm leading-none font-medium">{jadwal.mapel}</p>
                          <p className="text-muted-foreground text-sm">{jadwal.rombel}</p>
                        </div>
                        <div className="bg-muted rounded border px-2 py-1 text-sm font-medium">{jadwal.jam}</div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="flex h-[200px] items-center justify-center rounded-md border border-dashed">
                    <p className="text-muted-foreground">Belum ada jadwal</p>
                  </div>
                )}
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>

        <Card className="col-span-3">
          <CardHeader>
            <CardTitle>Akses Cepat</CardTitle>
            <CardDescription>Menu yang sering digunakan</CardDescription>
          </CardHeader>
          <CardContent className="grid gap-4">
            <Link href="/dashboard/jadwal-mengajar">
              <Button variant="outline" className="w-full justify-start gap-2">
                <Calendar className="h-4 w-4" />
                Lihat Jadwal Lengkap
              </Button>
            </Link>
            <Link href="/dashboard/administrasi-guru">
              <Button variant="outline" className="w-full justify-start gap-2">
                <ClipboardList className="h-4 w-4" />
                Administrasi Guru
              </Button>
            </Link>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
