"use client";

import * as React from "react";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Search, Download, Printer, ArrowUpDown } from "lucide-react";

interface SubjectCol {
  id: string;
  name: string;
  code: string;
  teacherName: string;
}

interface StudentGradeRow {
  id: string;
  nis: string;
  fullName: string;
  scores: Record<string, number>;
  total: number;
  average: number;
  rank: number;
}

interface HomeroomGradesClientProps {
  className: string;
  subjects: SubjectCol[];
  students: StudentGradeRow[];
}

export function HomeroomGradesClient({
  className,
  subjects,
  students,
}: HomeroomGradesClientProps) {
  const [search, setSearch] = React.useState("");
  const [sortBy, setSortBy] = React.useState<"nis" | "rank" | "name">("nis");

  const filtered = React.useMemo(() => {
    let result = students.filter(
      (s) =>
        s.fullName.toLowerCase().includes(search.toLowerCase()) ||
        s.nis.includes(search)
    );

    if (sortBy === "rank") {
      result.sort((a, b) => a.rank - b.rank);
    } else if (sortBy === "name") {
      result.sort((a, b) => a.fullName.localeCompare(b.fullName));
    } else {
      result.sort((a, b) => a.nis.localeCompare(b.nis));
    }

    return result;
  }, [students, search, sortBy]);

  const handleExportCsv = () => {
    const headers = ["Ranking", "NIS", "Nama Lengkap", ...subjects.map((s) => s.code), "Total Nilai", "Rata-rata"];
    const rows = filtered.map((st) => [
      st.rank,
      st.nis,
      `"${st.fullName.replace(/"/g, '""')}"`,
      ...subjects.map((sub) => st.scores[sub.id] || 0),
      st.total,
      st.average,
    ]);

    const csvContent = [headers.join(","), ...rows.map((r) => r.join(","))].join("\n");
    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.setAttribute("href", url);
    link.setAttribute("download", `rekap_nilai_kelas_${className}_${Date.now()}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="space-y-4">
      {/* Action Bar */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col sm:flex-row items-center justify-between gap-3">
            <div className="relative w-full sm:w-80">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
              <Input
                placeholder="Cari siswa atau NIS..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-9 text-xs"
              />
            </div>

            <div className="flex items-center gap-2 w-full sm:w-auto">
              <div className="flex items-center gap-1.5 text-xs text-slate-600">
                <ArrowUpDown className="h-3.5 w-3.5 text-slate-400" />
                <select
                  value={sortBy}
                  onChange={(e: any) => setSortBy(e.target.value)}
                  className="bg-white border border-slate-300 rounded-lg px-2.5 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="nis">Urutkan: NIS</option>
                  <option value="rank">Urutkan: Ranking</option>
                  <option value="name">Urutkan: Nama</option>
                </select>
              </div>

              <Button
                variant="outline"
                size="sm"
                onClick={handleExportCsv}
                className="text-xs"
              >
                <Download className="h-3.5 w-3.5 mr-1" />
                Ekspor CSV
              </Button>

              <Button
                variant="outline"
                size="sm"
                onClick={() => window.print()}
                className="text-xs"
              >
                <Printer className="h-3.5 w-3.5 mr-1" />
                Cetak
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Grade Matrix Table */}
      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-xs text-left border-collapse">
              <thead className="bg-slate-50 text-slate-700 font-semibold border-b border-slate-200">
                <tr>
                  <th className="py-3 px-3 border-r border-slate-200 w-12 text-center">Rank</th>
                  <th className="py-3 px-3 border-r border-slate-200 w-20">NIS</th>
                  <th className="py-3 px-4 border-r border-slate-200 min-w-[180px]">
                    Nama Lengkap Siswa
                  </th>
                  {subjects.map((sub) => (
                    <th
                      key={sub.id}
                      className="py-3 px-2 border-r border-slate-200 text-center min-w-[70px]"
                      title={`${sub.name} (${sub.teacherName})`}
                    >
                      <div className="font-bold text-slate-800 truncate">{sub.code}</div>
                    </th>
                  ))}
                  <th className="py-3 px-3 border-r border-slate-200 text-center font-bold text-slate-900 bg-slate-100/60">
                    Total
                  </th>
                  <th className="py-3 px-3 text-center font-bold text-blue-700 bg-blue-50/50">
                    Rata-rata
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filtered.map((st) => (
                  <tr key={st.id} className="hover:bg-slate-50/80 transition-colors">
                    <td className="py-2.5 px-3 text-center border-r border-slate-100 font-bold">
                      <span
                        className={`inline-flex items-center justify-center h-6 w-6 rounded-full text-[11px] ${
                          st.rank === 1
                            ? "bg-amber-100 text-amber-800 font-extrabold border border-amber-300"
                            : st.rank === 2
                            ? "bg-slate-200 text-slate-700 font-bold"
                            : st.rank === 3
                            ? "bg-amber-50 text-amber-700 font-bold border border-amber-200"
                            : "text-slate-500"
                        }`}
                      >
                        {st.rank}
                      </span>
                    </td>
                    <td className="py-2.5 px-3 font-mono text-slate-600 border-r border-slate-100">
                      {st.nis}
                    </td>
                    <td className="py-2.5 px-4 font-semibold text-slate-800 border-r border-slate-100 truncate max-w-[200px]">
                      {st.fullName}
                    </td>
                    {subjects.map((sub) => {
                      const score = st.scores[sub.id] ?? 0;
                      return (
                        <td
                          key={sub.id}
                          className="py-2.5 px-2 text-center border-r border-slate-100"
                        >
                          <span
                            className={`font-semibold ${
                              score >= 85
                                ? "text-blue-700"
                                : score >= 75
                                ? "text-emerald-700"
                                : "text-amber-700"
                            }`}
                          >
                            {score}
                          </span>
                        </td>
                      );
                    })}
                    <td className="py-2.5 px-3 text-center font-bold text-slate-900 bg-slate-100/30 border-r border-slate-100">
                      {st.total}
                    </td>
                    <td className="py-2.5 px-3 text-center font-extrabold text-blue-700 bg-blue-50/20">
                      {st.average}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
