"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { MoreHorizontal, UserCheck, UserX } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { Avatar, AvatarFallback, AvatarImage } from "@/shared/components/ui/avatar"
import { Card, CardContent, CardFooter, CardHeader } from "@/shared/components/ui/card"
import { cn, formatDate, getInitials } from "@/shared/lib/utils"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { ConfirmDeleteDialog } from "@/shared/components/ui/confirm-delete-dialog"
import type { ClassStudent } from "../types"
import { setStudentEnrollmentStatusAction } from "../actions"

export function StudentsTable({ students }: { students: ClassStudent[] }) {
  const router = useRouter()
  const t = useTranslations("classes")
  const [workingKey, setWorkingKey] = useState<string | null>(null)
  const [removeTarget, setRemoveTarget] = useState<ClassStudent | null>(null)

  const setStatus = async (student: ClassStudent, status: "active" | "inactive") => {
    const key = `${student.classId}:${student.id}`
    setWorkingKey(key)
    try {
      const res = await setStudentEnrollmentStatusAction(student.classId, student.id, status)
      if (res.success) {
        toast.success(res.message)
        router.refresh()
      } else {
        toast.error(res.message)
      }
    } catch {
      toast.error(t("list.failedStatus"))
    } finally {
      setWorkingKey(null)
    }
  }

  return (
    <>
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
        {students.map((s) => (
          <Card key={`${s.classId}:${s.id}`} className="overflow-hidden">
            <CardHeader className="flex flex-row items-center gap-4 space-y-0 p-4 pb-2">
              <div className="relative">
                <Avatar className="h-10 w-10 border">
                  <AvatarImage src={s.image || undefined} alt={s.name} />
                  <AvatarFallback>{getInitials(s.name)}</AvatarFallback>
                </Avatar>
                <span className={cn(
                  "absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-background",
                  s.status === "active" ? "bg-emerald-500" : "bg-muted-foreground"
                )} />
              </div>
              <div className="flex flex-col flex-1 overflow-hidden">
                <div className="flex items-start justify-between">
                  <div className="flex flex-col overflow-hidden mr-2">
                    <span className="truncate font-semibold text-sm">{s.name}</span>
                    <span className="truncate text-xs text-muted-foreground">{s.email}</span>
                  </div>
                  <div className="flex flex-col items-end gap-0.5 text-xs text-muted-foreground shrink-0">
                    <span className="text-[10px] font-medium text-foreground/80">
                      {s.className}
                    </span>
                    <span className="text-[10px]">
                      {formatDate(s.joinedAt, "en-GB")}
                    </span>
                  </div>
                </div>
              </div>
            </CardHeader>
            <CardContent className="p-4 pt-0">
              {s.subjectScores && Object.keys(s.subjectScores).length > 0 ? (
                <div className="flex flex-col gap-2">
                  <div className="flex flex-wrap gap-1.5">
                    {Object.entries(s.subjectScores).slice(0, 4).map(([subject, score]) => (
                      <div key={subject} className="flex items-center gap-1.5 rounded-md bg-muted/50 px-2 py-1 text-xs border border-muted/50">
                        <span className="font-medium text-muted-foreground/80">{subject}</span>
                        {score !== null ? (
                          <span className={cn(
                            "font-bold",
                            score >= 90 ? "text-emerald-600" :
                            score >= 80 ? "text-primary" :
                            score >= 60 ? "text-yellow-600" : "text-destructive"
                          )}>
                            {score}
                          </span>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </div>
                    ))}
                    {Object.keys(s.subjectScores).length > 4 && (
                      <div className="flex items-center justify-center rounded-md bg-muted/50 px-2 py-1 text-xs text-muted-foreground font-medium border border-muted/50">
                        +{Object.keys(s.subjectScores).length - 4}
                      </div>
                    )}
                  </div>
                </div>
              ) : (
                <div className="flex items-center justify-center h-[32px] rounded-md bg-muted/20 border border-dashed border-muted">
                  <span className="text-xs text-muted-foreground/50 italic">No recent scores</span>
                </div>
              )}
            </CardContent>
            <CardFooter className="flex items-center justify-between border-t bg-muted/50 p-2">
              <Button variant="ghost" size="sm" className="h-7 text-xs text-muted-foreground" asChild>
                <a href={`mailto:${s.email}`}>Email</a>
              </Button>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="icon" className="h-7 w-7" disabled={workingKey !== null}>
                    <MoreHorizontal className="size-4 text-muted-foreground" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  {s.status !== "active" ? (
                    <DropdownMenuItem onClick={() => setStatus(s, "active")} disabled={workingKey !== null}>
                      <UserCheck className="mr-2 size-4" />
                      {t("students.actions.setActive")}
                    </DropdownMenuItem>
                  ) : (
                    <DropdownMenuItem onClick={() => setStatus(s, "inactive")} disabled={workingKey !== null}>
                      <UserX className="mr-2 size-4" />
                      {t("students.actions.setInactive")}
                    </DropdownMenuItem>
                  )}
                  <DropdownMenuSeparator />
                  <DropdownMenuItem
                    onClick={() => setRemoveTarget(s)}
                    className="text-destructive focus:text-destructive"
                    disabled={s.status === "inactive" || workingKey !== null}
                  >
                    <UserX className="mr-2 size-4" />
                    {t("students.actions.remove")}
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </CardFooter>
          </Card>
        ))}
      </div>

      <ConfirmDeleteDialog
        open={Boolean(removeTarget)}
        onOpenChange={(open) => {
          if (workingKey !== null) return
          if (!open) setRemoveTarget(null)
        }}
        title={t("students.removeTitle")}
        confirmText={t("students.actions.remove")}
        description={
          removeTarget ? t("students.removeDescription", { name: removeTarget.name }) : null
        }
        onConfirm={() => {
          if (!removeTarget) return
          setRemoveTarget(null)
          setStatus(removeTarget, "inactive")
        }}
        isWorking={workingKey !== null}
      />
    </>
  )
}
