"use client"

import { useState, useTransition } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import { Plus, Pencil, Lock, Unlock, Shuffle, Trash2 } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { usePermission } from "@/shared/hooks/use-permission"
import type { ActionState } from "@/shared/types/action-state"
import { Permissions } from "@/shared/types/permissions"

import {
  ELECTIVE_STATUS_BADGE_VARIANTS,
  ELECTIVE_STATUS_LABEL_KEYS,
  SELECTION_MODE_LABEL_KEYS,
} from "../constants"
import type { ElectiveCourseWithDetails } from "../types"
import {
  deleteElectiveCourseAction,
  openSelectionAction,
  closeSelectionAction,
  runLotteryAction,
} from "../actions"

export function ElectiveCourseList({
  courses,
  createHref,
  editBaseHref,
  canManage,
}: {
  courses: ElectiveCourseWithDetails[]
  createHref?: string
  editBaseHref?: string
  canManage?: boolean
}) {
  const router = useRouter()
  const t = useTranslations("elective")
  const { hasPermission } = usePermission()
  const manageResolved = canManage ?? hasPermission(Permissions.ELECTIVE_MANAGE)
  const [pendingId, setPendingId] = useState<string | null>(null)
  const [isPending, startTransition] = useTransition()

  const runAction = async <T,>(
    action: (prevState: ActionState<T> | null, formData: FormData) => Promise<ActionState<T>>,
    courseId: string,
    successMsg: string
  ) => {
    setPendingId(courseId)
    startTransition(async () => {
      const formData = new FormData()
      formData.set("courseId", courseId)
      const res = await action(null, formData)
      if (res.success) {
        toast.success(res.message ?? successMsg)
        router.refresh()
      } else {
        toast.error(res.message ?? t("errors.unexpected"))
      }
      setPendingId(null)
    })
  }

  const handleDelete = (courseId: string) => {
    setPendingId(courseId)
    startTransition(async () => {
      const formData = new FormData()
      formData.set("courseId", courseId)
      const res = await deleteElectiveCourseAction(null, formData)
      if (res.success) {
        toast.success(res.message ?? t("actions.delete"))
        router.refresh()
      } else {
        toast.error(res.message ?? t("errors.unexpected"))
      }
      setPendingId(null)
    })
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <p className="text-sm text-muted-foreground">
          {courses.length} {t("title.adminList")}
        </p>
        {manageResolved && createHref ? (
          <Button asChild>
            <Link href={createHref}>
              <Plus className="mr-2 h-4 w-4" />
              {t("actions.create")}
            </Link>
          </Button>
        ) : null}
      </div>

      {courses.length === 0 ? (
        <EmptyState
          title={t("list.empty")}
          description={t("list.emptyDescription")}
          icon={Plus}
          className="h-auto border-none shadow-none"
        />
      ) : (
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
          {courses.map((course) => {
            const isFull = course.enrolledCount >= course.capacity
            const isPendingThis = isPending && pendingId === course.id
            return (
              <Card key={course.id} className="flex h-full flex-col">
                <CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0">
                  <CardTitle className="line-clamp-2 text-base">{course.name}</CardTitle>
                  <Badge variant={ELECTIVE_STATUS_BADGE_VARIANTS[course.status]} className="shrink-0">
                    {t(ELECTIVE_STATUS_LABEL_KEYS[course.status])}
                  </Badge>
                </CardHeader>
                <CardContent className="flex flex-1 flex-col gap-3">
                  <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
                    {course.subjectName ? (
                      <Badge variant="outline">{course.subjectName}</Badge>
                    ) : null}
                    {course.gradeName ? (
                      <Badge variant="outline">{course.gradeName}</Badge>
                    ) : null}
                    <span>{t("fields.credit")}: {course.credit}</span>
                  </div>

                  {course.description ? (
                    <p className="line-clamp-2 text-sm text-muted-foreground">
                      {course.description}
                    </p>
                  ) : null}

                  <div className="grid grid-cols-2 gap-2 text-xs">
                    <div>
                      <span className="text-muted-foreground">{t("fields.teacher")}:</span>{" "}
                      <span className="font-medium">{course.teacherName ?? "—"}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">{t("fields.selectionMode")}:</span>{" "}
                      <span className="font-medium">
                        {t(SELECTION_MODE_LABEL_KEYS[course.selectionMode])}
                      </span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">{t("fields.capacity")}:</span>{" "}
                      <span className="font-medium">
                        {course.enrolledCount}/{course.capacity}
                        {isFull ? ` (${t("student.capacityFull")})` : ""}
                      </span>
                    </div>
                    {course.classroom ? (
                      <div>
                        <span className="text-muted-foreground">{t("fields.classroom")}:</span>{" "}
                        <span className="font-medium">{course.classroom}</span>
                      </div>
                    ) : null}
                  </div>

                  {course.schedule ? (
                    <p className="text-xs text-muted-foreground">
                      <span className="font-medium">{t("fields.schedule")}:</span> {course.schedule}
                    </p>
                  ) : null}

                  {manageResolved ? (
                    <div className="mt-auto flex flex-wrap gap-2 pt-2">
                      {editBaseHref ? (
                        <Button
                          asChild
                          variant="outline"
                          size="sm"
                        >
                          <Link href={`${editBaseHref}/${course.id}/edit`}>
                            <Pencil className="mr-1 h-3 w-3" />
                            {t("actions.edit")}
                          </Link>
                        </Button>
                      ) : null}
                      {course.status === "draft" || course.status === "closed" ? (
                        <Button
                          variant="outline"
                          size="sm"
                          disabled={isPendingThis}
                          onClick={() => runAction(openSelectionAction, course.id, t("actions.openSelection"))}
                        >
                          <Unlock className="mr-1 h-3 w-3" />
                          {t("actions.openSelection")}
                        </Button>
                      ) : null}
                      {course.status === "open" ? (
                        <Button
                          variant="outline"
                          size="sm"
                          disabled={isPendingThis}
                          onClick={() => runAction(closeSelectionAction, course.id, t("actions.closeSelection"))}
                        >
                          <Lock className="mr-1 h-3 w-3" />
                          {t("actions.closeSelection")}
                        </Button>
                      ) : null}
                      {course.selectionMode === "lottery" && course.status !== "draft" ? (
                        <Button
                          variant="outline"
                          size="sm"
                          disabled={isPendingThis}
                          onClick={() => runAction(runLotteryAction, course.id, t("actions.runLottery"))}
                        >
                          <Shuffle className="mr-1 h-3 w-3" />
                          {t("actions.runLottery")}
                        </Button>
                      ) : null}
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-destructive hover:text-destructive"
                        disabled={isPendingThis}
                        onClick={() => handleDelete(course.id)}
                      >
                        <Trash2 className="mr-1 h-3 w-3" />
                        {t("actions.delete")}
                      </Button>
                    </div>
                  ) : null}
                </CardContent>
              </Card>
            )
          })}
        </div>
      )}
    </div>
  )
}
