"use client"

import { useMemo, useState } from "react"
import { useRouter } from "next/navigation"
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 type { CoursePlanListItem, CoursePlanStatus } from "../types"

const STATUS_LABEL: Record<CoursePlanStatus, string> = {
  planning: "Planning",
  active: "Active",
  completed: "Completed",
  paused: "Paused",
}

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

type Filter = "all" | CoursePlanStatus

const FILTER_OPTIONS: { value: Filter; label: string }[] = [
  { value: "all", label: "All" },
  { value: "planning", label: "Planning" },
  { value: "active", label: "Active" },
  { value: "completed", label: "Completed" },
  { value: "paused", label: "Paused" },
]

export function CoursePlanList({
  plans,
  canManage,
  createHref,
  detailBaseHref,
  initialStatus,
}: {
  plans: CoursePlanListItem[]
  canManage?: boolean
  createHref?: string
  detailBaseHref?: string
  initialStatus?: Filter
}) {
  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) => {
    setFilter(value as Filter)
    const params = new URLSearchParams()
    if (value !== "all") params.set("status", value)
    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="Filter by status" />
          </SelectTrigger>
          <SelectContent>
            {FILTER_OPTIONS.map((opt) => (
              <SelectItem key={opt.value} value={opt.value}>
                {opt.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        {canManageResolved && createHref ? (
          <Button asChild>
            <a href={createHref}>
              <Plus className="mr-2 h-4 w-4" />
              New Course Plan
            </a>
          </Button>
        ) : null}
      </div>

      {filtered.length === 0 ? (
        <EmptyState
          title="No course plans"
          description={
            plans.length === 0
              ? "There are no course plans yet."
              : "No course plans match the current filter."
          }
          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 ?? "Unknown Subject"}
                  </CardTitle>
                  <Badge variant={STATUS_VARIANT[plan.status]} className="shrink-0">
                    {STATUS_LABEL[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 ?? "No class"}</Badge>
                    <span>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">
                    Created {formatDate(plan.createdAt)}
                  </p>
                </CardContent>
              </Card>
            )

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