"use client"

import type { JSX } from "react"
import { useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { useTranslations } from "next-intl"
import { Plus, CalendarRange } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { usePermission } from "@/shared/hooks/use-permission"
import { Permissions } from "@/shared/types/permissions"
import { formatDate } from "@/shared/lib/utils"

import { CoursePlanProgress } from "./course-plan-progress"
import { isCoursePlanStatus } from "../types"
import type { CoursePlanListItem, CoursePlanStatus } from "../types"

const STATUS_VARIANT: Record<CoursePlanStatus, "default" | "secondary" | "outline"> = {
  planning: "secondary",
  active: "default",
  completed: "outline",
  paused: "outline",
}

const STATUS_VALUES = ["planning", "active", "completed", "paused"] as const

type Filter = "all" | CoursePlanStatus

export function CoursePlanList({
  plans,
  canManage,
  createHref,
  detailBaseHref,
  initialStatus,
}: {
  plans: CoursePlanListItem[]
  canManage?: boolean
  createHref?: string
  detailBaseHref?: string
  initialStatus?: Filter
}): JSX.Element {
  const t = useTranslations("coursePlans")
  const router = useRouter()
  const { hasPermission } = usePermission()
  const canManageResolved = canManage ?? hasPermission(Permissions.COURSE_PLAN_MANAGE)
  const [filter, setFilter] = useState<Filter>(initialStatus ?? "all")

  const filtered = useMemo(() => {
    if (filter === "all") return plans
    return plans.filter((p) => p.status === filter)
  }, [plans, filter])

  const handleFilterChange = (value: string): void => {
    const next: Filter = value === "all" || isCoursePlanStatus(value) ? value : "all"
    setFilter(next)
    const params = new URLSearchParams()
    if (next !== "all") params.set("status", next)
    const qs = params.toString()
    router.replace(qs ? `?${qs}` : "?")
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <Select value={filter} onValueChange={handleFilterChange}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder={t("filter.placeholder")} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">{t("filter.all")}</SelectItem>
            {STATUS_VALUES.map((s) => (
              <SelectItem key={s} value={s}>
                {t(`status.${s}`)}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        {canManageResolved && createHref ? (
          <Button asChild>
            <Link href={createHref}>
              <Plus className="mr-2 h-4 w-4" aria-hidden="true" />
              {t("list.new")}
            </Link>
          </Button>
        ) : null}
      </div>

      {filtered.length === 0 ? (
        <EmptyState
          title={t("list.empty")}
          description={plans.length === 0 ? t("list.empty") : t("list.emptyFiltered")}
          icon={CalendarRange}
          className="h-auto border-none shadow-none"
        />
      ) : (
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filtered.map((plan) => {
            const href = detailBaseHref ? `${detailBaseHref}/${plan.id}` : undefined
            const card = (
              <Card className="h-full transition-colors hover:bg-accent/50">
                <CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0">
                  <CardTitle className="line-clamp-2 text-base">
                    {plan.subjectName ?? t("list.unknownSubject")}
                  </CardTitle>
                  <Badge variant={STATUS_VARIANT[plan.status]} className="shrink-0">
                    {t(`status.${plan.status}`)}
                  </Badge>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
                    <Badge variant="outline">{plan.className ?? t("list.noClass")}</Badge>
                    <span>{t("list.semester", { semester: plan.semester })}</span>
                    {plan.teacherName ? <span>· {plan.teacherName}</span> : null}
                  </div>
                  <CoursePlanProgress
                    completedHours={plan.completedHours}
                    totalHours={plan.totalHours}
                    showDetails={false}
                  />
                  <p className="text-xs text-muted-foreground">
                    {t("list.created", { date: formatDate(plan.createdAt) })}
                  </p>
                </CardContent>
              </Card>
            )

            return href ? (
              <Link key={plan.id} href={href} className="block h-full">
                {card}
              </Link>
            ) : (
              <div key={plan.id}>{card}</div>
            )
          })}
        </div>
      )}
    </div>
  )
}
