"use client";

import * as React from "react";
import Link from "next/link";
import {
  FileCheck,
  Clock,
  CheckCircle2,
  Calendar,
  Award,
  ArrowRight,
  Search,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { formatDateID } from "@/lib/utils";

interface StudentQuizzesClientProps {
  initialQuizzes: any[];
}

export default function StudentQuizzesClient({
  initialQuizzes,
}: StudentQuizzesClientProps) {
  const [search, setSearch] = React.useState("");

  const filtered = initialQuizzes.filter(
    (q) =>
      q.title.toLowerCase().includes(search.toLowerCase()) ||
      q.teacherSubject.subject.name.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="relative w-full sm:w-72">
          <Search className="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
          <input
            type="text"
            placeholder="Cari kuis atau mata pelajaran..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-9 pr-3 py-2 rounded-xl border border-slate-200 text-xs bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <span className="text-xs text-slate-500 font-semibold">
          Total: {filtered.length} Asesmen Tersedia
        </span>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
        {filtered.map((q) => {
          const completedAttempt = q.attempts.find((att: any) => att.isCompleted);
          const inProgressAttempt = q.attempts.find((att: any) => !att.isCompleted);

          return (
            <Card
              key={q.id}
              className="hover:border-blue-400 hover:shadow-md transition-all flex flex-col justify-between group"
            >
              <CardHeader className="pb-2">
                <div className="flex items-center justify-between">
                  <Badge variant="primary">{q.teacherSubject.subject.name}</Badge>
                  <span className="text-xs font-mono font-bold text-slate-600 bg-slate-100 px-2 py-0.5 rounded-full">
                    {q.durationMinutes} Menit
                  </span>
                </div>
                <CardTitle className="text-base text-slate-900 group-hover:text-blue-600 transition-colors mt-2 line-clamp-2">
                  {q.title}
                </CardTitle>
              </CardHeader>

              <CardContent className="space-y-3 pt-2">
                {q.description && (
                  <p className="text-xs text-slate-500 line-clamp-2 leading-relaxed">
                    {q.description}
                  </p>
                )}

                <div className="space-y-1 text-xs text-slate-500 pt-1">
                  <p>Guru: {q.teacherSubject.teacher.fullName}</p>
                  <p>Jumlah Soal: {q.questions?.length || 0} Butir</p>
                  <p>KKM: {q.passingScore} Poin</p>
                  <p className="font-mono text-[11px] text-slate-400">
                    Batas Selesai: {formatDateID(q.endTime, true)}
                  </p>
                </div>

                {/* Attempt Status Badge */}
                {completedAttempt && (
                  <div className="p-3 rounded-xl bg-emerald-50 border border-emerald-200 flex items-center justify-between text-xs">
                    <div>
                      <span className="text-emerald-800 font-bold block">
                        Ujian Selesai
                      </span>
                      <span className="text-[11px] text-emerald-600">
                        {completedAttempt.totalScore >= q.passingScore ? "Lulus KKM" : "Remedial"}
                      </span>
                    </div>
                    <span className="text-2xl font-black text-emerald-700">
                      {completedAttempt.totalScore}
                    </span>
                  </div>
                )}

                {/* Actions */}
                <div className="pt-2 border-t border-slate-100">
                  {completedAttempt ? (
                    <Link href={`/student/quizzes/${q.id}/take`}>
                      <Button size="sm" variant="outline" className="w-full text-xs font-bold">
                        Buka Riwayat Ujian & Pembahasan
                      </Button>
                    </Link>
                  ) : inProgressAttempt ? (
                    <Link href={`/student/quizzes/${q.id}/take`}>
                      <Button size="sm" variant="warning" className="w-full text-xs font-bold animate-pulse">
                        Lanjutkan Ujian (Sedang Berjalan) &rarr;
                      </Button>
                    </Link>
                  ) : (
                    <Link href={`/student/quizzes/${q.id}/take`}>
                      <Button size="sm" variant="gold" className="w-full text-xs font-bold">
                        Mulai Ujian CBT
                        <ArrowRight className="ml-1.5 h-3.5 w-3.5" />
                      </Button>
                    </Link>
                  )}
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>
    </div>
  );
}
