"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { useQueryState, parseAsString } from "nuqs"
import { Search, UserPlus, ChevronDown, Check } from "lucide-react"
import { toast } from "sonner"

import { Input } from "@/shared/components/ui/input"
import { Button } from "@/shared/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
  DropdownMenuLabel,
} from "@/shared/components/ui/dropdown-menu"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/components/ui/dialog"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { Label } from "@/shared/components/ui/label"
import type { TeacherClass } from "../types"
import { enrollStudentByEmailAction } from "../actions"

export function StudentsFilters({ classes, defaultClassId }: { classes: TeacherClass[], defaultClassId?: string }) {
  const [search, setSearch] = useQueryState("q", parseAsString.withDefault("").withOptions({ shallow: false, throttleMs: 500 }))
  const [classId, setClassId] = useQueryState("classId", parseAsString.withDefault(defaultClassId || "all").withOptions({ shallow: false }))
  const [status, setStatus] = useQueryState("status", parseAsString.withDefault("all").withOptions({ shallow: false }))

  const router = useRouter()
  const t = useTranslations("classes")
  const [open, setOpen] = useState(false)
  const [isWorking, setIsWorking] = useState(false)

  const effectiveClassId = classId === "all" && defaultClassId ? defaultClassId : classId

  const [enrollClassId, setEnrollClassId] = useState(effectiveClassId !== "all" ? effectiveClassId : (classes[0]?.id ?? ""))

  const [prevOpen, setPrevOpen] = useState(open)
  if (open !== prevOpen) {
    setPrevOpen(open)
    if (open) {
      setEnrollClassId(effectiveClassId !== "all" ? effectiveClassId : (classes[0]?.id ?? ""))
    }
  }

  const handleEnroll = async (formData: FormData): Promise<void> => {
    setIsWorking(true)
    try {
      const res = await enrollStudentByEmailAction(enrollClassId, null, formData)
      if (res.success) {
        toast.success(res.message)
        setOpen(false)
        router.refresh()
      } else {
        toast.error(res.message || t("list.failedCreate"))
      }
    } catch {
      toast.error(t("list.failedCreate"))
    } finally {
      setIsWorking(false)
    }
  }

  const selectedClass = classes.find(c => c.id === classId)
  const classLabel = classId === "all" ? t("filters.allClasses") : (selectedClass?.name || t("filters.unknownClass"))

  const statusLabel = status === "all" ? t("filters.allStatuses") : (status === "active" ? t("students.status.active") : t("students.status.inactive"))

  return (
    <div className="flex items-center justify-between py-2">
      <div className="flex items-center gap-2">
        {/* Search - Minimal */}
        <div className="relative group">
          <Search className="text-muted-foreground absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 group-hover:text-foreground transition-colors" />
          <Input
            placeholder={t("students.searchPlaceholder")}
            className="pl-8 h-8 w-[180px] text-xs bg-transparent border-transparent hover:bg-muted/50 focus-visible:bg-background focus-visible:ring-1 focus-visible:ring-ring focus-visible:border-input transition-all"
            value={search}
            onChange={(e) => setSearch(e.target.value || null)}
          />
        </div>

        <div className="h-4 w-[1px] bg-border mx-1" />

        {/* Class Filter - Compact */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="sm" className="h-8 gap-1 px-2 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/50">
              <span className="truncate max-w-[120px]">{classLabel}</span>
              <ChevronDown className="h-3 w-3 opacity-50" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="start" className="w-[200px]">
            <DropdownMenuLabel className="text-xs text-muted-foreground font-normal">Filter by Class</DropdownMenuLabel>
            <DropdownMenuItem 
              onClick={() => setClassId("all")} 
              className="text-xs flex items-center justify-between"
            >
              {t("filters.allClasses")}
              {classId === "all" && <Check className="h-3 w-3" />}
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            {classes.map((c) => (
              <DropdownMenuItem 
                key={c.id} 
                onClick={() => setClassId(c.id)} 
                className="text-xs flex items-center justify-between"
              >
                <span className="truncate">{c.name}</span>
                {classId === c.id && <Check className="h-3 w-3" />}
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>

        {/* Status Filter - Compact */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="sm" className="h-8 gap-1 px-2 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/50">
              {statusLabel}
              <ChevronDown className="h-3 w-3 opacity-50" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="start">
            <DropdownMenuLabel className="text-xs text-muted-foreground font-normal">{t("filters.filterByStatus")}</DropdownMenuLabel>
            <DropdownMenuItem onClick={() => setStatus(null)} className="text-xs flex items-center justify-between">
              {t("filters.allStatuses")}
              {status === "all" && <Check className="h-3 w-3" />}
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => setStatus("active")} className="text-xs flex items-center justify-between">
              {t("students.status.active")}
              {status === "active" && <Check className="h-3 w-3" />}
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => setStatus("inactive")} className="text-xs flex items-center justify-between">
              {t("students.status.inactive")}
              {status === "inactive" && <Check className="h-3 w-3" />}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      <Dialog
        open={open}
        onOpenChange={(v) => {
          if (isWorking) return
          setOpen(v)
        }}
      >
        <DialogTrigger asChild>
          <Button size="sm" className="h-8 gap-1.5 text-xs px-3" disabled={classes.length === 0}>
            <UserPlus className="size-3.5" />
            {t("filters.addStudent")}
          </Button>
        </DialogTrigger>
        <DialogContent className="sm:max-w-[520px]">
          <DialogHeader>
            <DialogTitle>{t("filters.addStudent")}</DialogTitle>
            <DialogDescription>{t("filters.enrollStudentDescription")}</DialogDescription>
          </DialogHeader>
          <form action={handleEnroll}>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">{t("filters.class")}</Label>
                <div className="col-span-3">
                  <Select value={enrollClassId} onValueChange={setEnrollClassId}>
                    <SelectTrigger>
                      <SelectValue placeholder={t("filters.selectClass")} />
                    </SelectTrigger>
                    <SelectContent>
                      {classes.map((c) => (
                        <SelectItem key={c.id} value={c.id}>
                          {c.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="student-email" className="text-right">
                  {t("filters.email")}
                </Label>
                <Input
                  id="student-email"
                  name="email"
                  type="email"
                  className="col-span-3"
                  placeholder={t("filters.emailPlaceholder")}
                  required
                />
              </div>
            </div>
            <DialogFooter>
              <Button type="submit" disabled={isWorking || !enrollClassId}>
                {isWorking ? t("form.adding") : t("form.add")}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  )
}

