"use client";

import { useState, useEffect, useMemo } from "react";
import { useParams, useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { ArrowLeft, Mail } from "lucide-react";
import { formatDate } from "@/lib/utils";
import { LibreChatUser, LibreChatBalance } from "@/lib/types";
import { useCollection } from "@/hooks/useCollection";

// Couleurs prédéfinies pour les référents
const REFERENT_COLORS: Record<string, string> = {
  "Emmanuel WATHELE": "#3B82F6",
  "IHECS": "#10B981",
};

export default function CoursDetailPage() {
  const params = useParams();
  const router = useRouter();
  const referent = decodeURIComponent(params.referent as string);
  const cours = decodeURIComponent(params.cours as string);

  const [students, setStudents] = useState<LibreChatUser[]>([]);
  const [loading, setLoading] = useState(true);

  // Charger tous les balances
  const { data: balances = [] } = useCollection<LibreChatBalance>("balances", {
    limit: 1000,
  });

  // Créer une map des crédits par utilisateur
  const creditsMap = useMemo(() => {
    const map = new Map<string, number>();
    balances.forEach((balance) => {
      map.set(balance.user, balance.tokenCredits || 0);
    });
    return map;
  }, [balances]);

  useEffect(() => {
    const fetchStudents = async () => {
      try {
        const response = await fetch(
          "/api/collections/users?page=1&limit=1000&filter={}"
        );
        const result = await response.json();

        if (result.data) {
          // Filtrer les étudiants pour ce référent et ce cours
          const filtered = result.data.filter(
            (user: { referent?: string; cours?: string }) =>
              user.referent === referent && user.cours === cours
          );
          setStudents(filtered);
        }
      } catch (error) {
        console.error("Erreur lors du chargement des étudiants:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchStudents();
  }, [referent, cours]);

  const couleur = REFERENT_COLORS[referent] || "#6B7280";

  if (loading) {
    return (
      <div className="space-y-6">
        <Button
          variant="ghost"
          onClick={() => router.push("/referents")}
          className="mb-4"
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          Retour aux référents
        </Button>
        <Card>
          <CardContent className="p-6">
            <div className="space-y-4">
              {Array.from({ length: 5 }).map((_, i) => (
                <div key={i} className="h-16 bg-muted animate-pulse rounded" />
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Button
        variant="ghost"
        onClick={() => router.push("/referents")}
        className="mb-4"
      >
        <ArrowLeft className="h-4 w-4 mr-2" />
        Retour aux référents
      </Button>

      <div className="flex items-center gap-3">
        <div
          className="w-6 h-6 rounded-full flex-shrink-0"
          style={{ backgroundColor: couleur }}
        />
        <div>
          <h1 className="text-3xl font-bold tracking-tight">{referent}</h1>
          <p className="text-muted-foreground">{cours}</p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>
              Étudiants ({students.length})
            </CardTitle>
          </div>
        </CardHeader>
        <CardContent>
          {students.length === 0 ? (
            <div className="text-center py-12">
              <p className="text-sm text-gray-500">
                Aucun étudiant dans ce cours
              </p>
            </div>
          ) : (
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Nom</TableHead>
                    <TableHead>Email</TableHead>
                    <TableHead>Rôle</TableHead>
                    <TableHead>Crédits</TableHead>
                    <TableHead>Créé le</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {students.map((student) => (
                    <TableRow key={student._id}>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <div
                            className="w-2 h-2 rounded-full"
                            style={{ backgroundColor: couleur }}
                          />
                          <span className="font-medium">
                            {student.prenom} {student.nom}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Mail className="h-4 w-4 text-gray-400" />
                          <span className="text-sm">{student.email}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant={student.role === "ADMIN" ? "default" : "secondary"}>
                          {student.role}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm">
                          {(creditsMap.get(student._id) || 0).toLocaleString()} tokens
                        </span>
                      </TableCell>
                      <TableCell className="text-sm text-gray-500">
                        {formatDate(student.createdAt)}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
