"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 { Modal } from "@/components/ui/modal";
import {
  Search,
  Users,
  Eye,
  Phone,
  Mail,
  MapPin,
  Calendar,
  CheckCircle2,
  AlertTriangle,
  Award,
  BookOpen,
} from "lucide-react";

interface StudentData {
  id: string;
  nis: string;
  nisn: string;
  fullName: string;
  gender: string;
  email: string;
  phone: string;
  address: string;
  birthPlace: string;
  birthDate: string | null;
  attendancePercent: number;
  submittedCount: number;
  totalAssignments: number;
  averageGrade: number;
  grades: { subject: string; score: number; letter: string }[];
}

interface HomeroomStudentsClientProps {
  className: string;
  students: StudentData[];
}

export function HomeroomStudentsClient({
  className,
  students,
}: HomeroomStudentsClientProps) {
  const [search, setSearch] = React.useState("");
  const [genderFilter, setGenderFilter] = React.useState("ALL");
  const [selectedStudent, setSelectedStudent] = React.useState<StudentData | null>(null);

  const filtered = students.filter((s) => {
    const matchSearch =
      s.fullName.toLowerCase().includes(search.toLowerCase()) ||
      s.nis.includes(search) ||
      s.nisn.includes(search);
    const matchGender = genderFilter === "ALL" || s.gender === genderFilter;
    return matchSearch && matchGender;
  });

  return (
    <div className="space-y-4">
      {/* Filter and Search Bar */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col sm:flex-row items-center gap-3 justify-between">
            <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 nama, NIS, atau NISN..."
                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">
              <select
                value={genderFilter}
                onChange={(e) => setGenderFilter(e.target.value)}
                className="text-xs bg-white border border-slate-300 rounded-lg px-3 py-2 text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="ALL">Semua Gender</option>
                <option value="MALE">Laki-laki</option>
                <option value="FEMALE">Perempuan</option>
              </select>
              <span className="text-xs text-slate-500 font-medium whitespace-nowrap">
                Total: <strong>{filtered.length}</strong> siswa
              </span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Students Table */}
      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-xs text-left">
              <thead className="bg-slate-50 text-slate-600 font-semibold border-b border-slate-200">
                <tr>
                  <th className="py-3 px-4">No</th>
                  <th className="py-3 px-4">NIS / NISN</th>
                  <th className="py-3 px-4">Nama Lengkap</th>
                  <th className="py-3 px-4">L/P</th>
                  <th className="py-3 px-4">Kehadiran</th>
                  <th className="py-3 px-4">Tugas Selesai</th>
                  <th className="py-3 px-4">Rerata Nilai</th>
                  <th className="py-3 px-4 text-right">Aksi</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filtered.length === 0 ? (
                  <tr>
                    <td colSpan={8} className="py-8 text-center text-slate-500">
                      Tidak ada data siswa yang cocok dengan filter pencarian.
                    </td>
                  </tr>
                ) : (
                  filtered.map((s, idx) => (
                    <tr key={s.id} className="hover:bg-slate-50 transition-colors">
                      <td className="py-3 px-4 text-slate-400 font-mono">{idx + 1}</td>
                      <td className="py-3 px-4 font-mono text-slate-600">
                        <div>{s.nis}</div>
                        <div className="text-[10px] text-slate-400">{s.nisn}</div>
                      </td>
                      <td className="py-3 px-4 font-semibold text-slate-800">
                        {s.fullName}
                      </td>
                      <td className="py-3 px-4">
                        <Badge
                          variant={s.gender === "MALE" ? "info" : "outline"}
                          className="text-[10px] px-1.5 py-0"
                        >
                          {s.gender === "MALE" ? "L" : "P"}
                        </Badge>
                      </td>
                      <td className="py-3 px-4">
                        <span
                          className={`font-semibold ${
                            s.attendancePercent >= 90
                              ? "text-emerald-600"
                              : s.attendancePercent >= 75
                              ? "text-amber-600"
                              : "text-rose-600"
                          }`}
                        >
                          {s.attendancePercent}%
                        </span>
                      </td>
                      <td className="py-3 px-4">
                        <span className="font-medium text-slate-700">
                          {s.submittedCount} / {s.totalAssignments || 5}
                        </span>
                      </td>
                      <td className="py-3 px-4">
                        <span
                          className={`font-bold ${
                            s.averageGrade >= 85
                              ? "text-blue-600"
                              : s.averageGrade >= 75
                              ? "text-emerald-600"
                              : "text-amber-600"
                          }`}
                        >
                          {s.averageGrade}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-right">
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => setSelectedStudent(s)}
                          className="text-xs h-7 text-blue-600 hover:text-blue-800 hover:bg-blue-50"
                        >
                          <Eye className="h-3.5 w-3.5 mr-1" />
                          Rincian
                        </Button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* Detail Modal */}
      {selectedStudent && (
        <Modal
          isOpen={true}
          onClose={() => setSelectedStudent(null)}
          title={`Profil Akademik: ${selectedStudent.fullName}`}
        >
          <div className="space-y-4">
            {/* Header info */}
            <div className="p-4 bg-slate-50 rounded-xl border border-slate-200 flex items-center gap-4">
              <div className="h-14 w-14 rounded-full bg-blue-600/20 text-blue-700 font-extrabold text-xl flex items-center justify-center border border-blue-300 shrink-0">
                {selectedStudent.fullName.substring(0, 2).toUpperCase()}
              </div>
              <div className="flex-1 overflow-hidden">
                <h4 className="font-bold text-slate-900 text-sm truncate">
                  {selectedStudent.fullName}
                </h4>
                <div className="flex flex-wrap items-center gap-2 mt-1">
                  <Badge variant="secondary">Kelas {className}</Badge>
                  <span className="text-xs font-mono text-slate-500">
                    NIS: {selectedStudent.nis}
                  </span>
                  <span className="text-xs font-mono text-slate-500">
                    NISN: {selectedStudent.nisn}
                  </span>
                </div>
              </div>
            </div>

            {/* Metrics */}
            <div className="grid grid-cols-3 gap-3">
              <div className="p-3 bg-blue-50/50 rounded-xl border border-blue-100 text-center">
                <span className="text-[11px] text-blue-600 font-medium">Rata-rata Nilai</span>
                <p className="text-lg font-bold text-blue-700 mt-0.5">
                  {selectedStudent.averageGrade}
                </p>
              </div>
              <div className="p-3 bg-emerald-50/50 rounded-xl border border-emerald-100 text-center">
                <span className="text-[11px] text-emerald-600 font-medium">Presensi</span>
                <p className="text-lg font-bold text-emerald-700 mt-0.5">
                  {selectedStudent.attendancePercent}%
                </p>
              </div>
              <div className="p-3 bg-purple-50/50 rounded-xl border border-purple-100 text-center">
                <span className="text-[11px] text-purple-600 font-medium">Tugas Selesai</span>
                <p className="text-lg font-bold text-purple-700 mt-0.5">
                  {selectedStudent.submittedCount}
                </p>
              </div>
            </div>

            {/* Contact Details */}
            <div className="space-y-2 text-xs">
              <h5 className="font-semibold text-slate-800 flex items-center gap-1.5">
                <Users className="h-3.5 w-3.5 text-blue-600" />
                Informasi Pribadi & Kontak
              </h5>
              <div className="grid grid-cols-2 gap-2 p-3 bg-white rounded-lg border border-slate-200">
                <div className="flex items-center gap-2 text-slate-600">
                  <Mail className="h-3.5 w-3.5 text-slate-400" />
                  <span className="truncate">{selectedStudent.email}</span>
                </div>
                <div className="flex items-center gap-2 text-slate-600">
                  <Phone className="h-3.5 w-3.5 text-slate-400" />
                  <span>{selectedStudent.phone}</span>
                </div>
                <div className="flex items-center gap-2 text-slate-600 col-span-2">
                  <MapPin className="h-3.5 w-3.5 text-slate-400 shrink-0" />
                  <span className="truncate">{selectedStudent.address}</span>
                </div>
              </div>
            </div>

            {/* Subject Grades preview */}
            {selectedStudent.grades.length > 0 && (
              <div className="space-y-2 text-xs">
                <h5 className="font-semibold text-slate-800 flex items-center gap-1.5">
                  <Award className="h-3.5 w-3.5 text-blue-600" />
                  Nilai Mata Pelajaran
                </h5>
                <div className="max-h-40 overflow-y-auto space-y-1.5 pr-1">
                  {selectedStudent.grades.map((g, i) => (
                    <div
                      key={i}
                      className="flex items-center justify-between p-2 bg-slate-50 rounded-lg border border-slate-100"
                    >
                      <span className="font-medium text-slate-700">{g.subject}</span>
                      <div className="flex items-center gap-2">
                        <span className="font-bold text-blue-700">{g.score}</span>
                        <Badge variant="outline" className="text-[10px]">
                          Predikat {g.letter}
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <div className="pt-2 flex justify-end">
              <Button size="sm" onClick={() => setSelectedStudent(null)}>
                Tutup
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}
