"use client"

import { useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { useQueryState, parseAsString } from "nuqs"
import { Plus } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/components/ui/dialog"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import type { TeacherClass } from "../types"
import { createClassScheduleItemAction } from "../actions"

export function ScheduleFilters({ classes }: { classes: TeacherClass[] }) {
  const [classId, setClassId] = useQueryState("classId", parseAsString.withDefault("all").withOptions({ shallow: false }))

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

  const defaultClassId = useMemo(() => (classId !== "all" ? classId : classes[0]?.id ?? ""), [classId, classes])
  const [createClassId, setCreateClassId] = useState(defaultClassId)
  const [weekday, setWeekday] = useState<string>("1")
  const [prevOpen, setPrevOpen] = useState(open)

  if (open !== prevOpen) {
    setPrevOpen(open)
    if (open) {
      setCreateClassId(defaultClassId)
      setWeekday("1")
    }
  }

  const handleCreate = async (formData: FormData): Promise<void> => {
    setIsWorking(true)
    try {
      formData.set("classId", createClassId)
      const res = await createClassScheduleItemAction(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 title = selectedClass ? selectedClass.name : t("filters.allClasses")

  return (
    <div className="relative flex items-center justify-between py-2">
      <div className="flex items-center gap-2">
        <Select value={classId} onValueChange={(val) => setClassId(val === "all" ? "all" : val)}>
          <SelectTrigger className="h-8 w-[180px] text-xs bg-transparent border-none shadow-none hover:bg-muted/50 focus:ring-0 text-muted-foreground hover:text-foreground">
            <SelectValue placeholder={t("filters.allClasses")} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all" className="text-xs">{t("filters.allClasses")}</SelectItem>
            {classes.map((c) => (
              <SelectItem key={c.id} value={c.id} className="text-xs">
                {c.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="absolute left-1/2 -translate-x-1/2 text-sm font-medium text-muted-foreground">
        {title}
      </div>

      <Dialog
        open={open}
        onOpenChange={(v) => {
          if (isWorking) return
          setOpen(v)
        }}
      >
        <DialogTrigger asChild>
          <Button 
            className="h-8 gap-1.5 text-xs px-3 shadow-none border-transparent bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50" 
            disabled={classes.length === 0}
            variant="ghost"
          >
            <Plus className="size-3.5" />
            {t("filters.addEvent")}
          </Button>
        </DialogTrigger>
        <DialogContent className="sm:max-w-[560px]">
          <DialogHeader>
            <DialogTitle>{t("schedule.form.createTitle")}</DialogTitle>
            <DialogDescription>{t("filters.createScheduleEntryDescription")}</DialogDescription>
          </DialogHeader>
          <form action={handleCreate}>
            <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={createClassId} onValueChange={setCreateClassId}>
                    <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="weekday" className="text-right">
                  {t("schedule.column.weekday")}
                </Label>
                <div className="col-span-3">
                  <Select value={weekday} onValueChange={setWeekday}>
                    <SelectTrigger>
                      <SelectValue placeholder={t("filters.selectWeekday")} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="1">{t("schedule.weekday.1")}</SelectItem>
                      <SelectItem value="2">{t("schedule.weekday.2")}</SelectItem>
                      <SelectItem value="3">{t("schedule.weekday.3")}</SelectItem>
                      <SelectItem value="4">{t("schedule.weekday.4")}</SelectItem>
                      <SelectItem value="5">{t("schedule.weekday.5")}</SelectItem>
                      <SelectItem value="6">{t("schedule.weekday.6")}</SelectItem>
                      <SelectItem value="7">{t("schedule.weekday.7")}</SelectItem>
                    </SelectContent>
                  </Select>
                  <input type="hidden" name="weekday" value={weekday} />
                </div>
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="startTime" className="text-right">
                  {t("filters.startTime")}
                </Label>
                <Input id="startTime" name="startTime" type="time" className="col-span-3" required />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="endTime" className="text-right">
                  {t("filters.endTime")}
                </Label>
                <Input id="endTime" name="endTime" type="time" className="col-span-3" required />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="course" className="text-right">
                  {t("schedule.column.subject")}
                </Label>
                <Input id="course" name="course" className="col-span-3" placeholder={t("filters.subjectPlaceholderExample")} required />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="location" className="text-right">
                  {t("schedule.column.location")}
                </Label>
                <Input id="location" name="location" className="col-span-3" placeholder={t("schedule.form.locationPlaceholder")} />
              </div>
            </div>
            <DialogFooter>
              <Button type="submit" disabled={isWorking || !createClassId}>
                {isWorking ? t("form.creating") : t("form.create")}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  )
}
