"use client"

import { useState } from "react"
import { useFormStatus } from "react-dom"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"

import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Checkbox } from "@/shared/components/ui/checkbox"
import { resolveActionError } from "@/shared/lib/resolve-action-error"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"

import { saveAttendanceRulesAction } from "../actions"
import type { AttendanceRule } from "../types"

type Option = { id: string; name: string }

function SubmitButton() {
  const { pending } = useFormStatus()
  const t = useTranslations("attendance")
  return (
    <Button type="submit" disabled={pending}>
      {pending ? t("actions.save") + "..." : t("rules.saved")}
    </Button>
  )
}

export function AttendanceRulesForm({
  classes,
  existingRules,
}: {
  classes: Option[]
  existingRules: AttendanceRule[]
}) {
  const router = useRouter()
  const t = useTranslations("attendance")
  const [classId, setClassId] = useState(classes[0]?.id ?? "")
  const [lateThreshold, setLateThreshold] = useState("15")
  const [earlyLeaveThreshold, setEarlyLeaveThreshold] = useState("15")
  const [enableAutoMark, setEnableAutoMark] = useState(false)
  const [attendanceRateThreshold, setAttendanceRateThreshold] = useState("90")
  const [consecutiveAbsenceThreshold, setConsecutiveAbsenceThreshold] = useState("3")

  const handleClassChange = (id: string) => {
    setClassId(id)
    const rule = existingRules.find((r) => r.classId === id)
    if (rule) {
      setLateThreshold(String(rule.lateThresholdMinutes ?? 15))
      setEarlyLeaveThreshold(String(rule.earlyLeaveThresholdMinutes ?? 15))
      setEnableAutoMark(rule.enableAutoMark ?? false)
      setAttendanceRateThreshold(String(rule.attendanceRateThreshold ?? 90))
      setConsecutiveAbsenceThreshold(String(rule.consecutiveAbsenceThreshold ?? 3))
    } else {
      setLateThreshold("15")
      setEarlyLeaveThreshold("15")
      setEnableAutoMark(false)
      setAttendanceRateThreshold("90")
      setConsecutiveAbsenceThreshold("3")
    }
  }

  const handleSubmit = async (formData: FormData) => {
    if (!classId) {
      toast.error(t("sheet.selectClass"))
      return
    }
    formData.set("classId", classId)
    formData.set("lateThresholdMinutes", lateThreshold)
    formData.set("earlyLeaveThresholdMinutes", earlyLeaveThreshold)
    formData.set("enableAutoMark", enableAutoMark ? "true" : "false")
    formData.set("attendanceRateThreshold", attendanceRateThreshold)
    formData.set("consecutiveAbsenceThreshold", consecutiveAbsenceThreshold)

    try {
      const result = await saveAttendanceRulesAction(null, formData)
      if (result.success) {
        toast.success(result.message || t("rules.saved"))
        router.refresh()
      } else {
        toast.error(resolveActionError(result, t, t("errors.unexpected")))
      }
    } catch {
      toast.error(t("errors.unexpected"))
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("title.rules")}</CardTitle>
      </CardHeader>
      <CardContent>
        <form action={handleSubmit} className="space-y-6">
          <div className="grid gap-2">
            <Label htmlFor="rules-class-select">{t("filters.class")}</Label>
            <Select value={classId} onValueChange={handleClassChange}>
              <SelectTrigger id="rules-class-select">
                <SelectValue placeholder={t("sheet.selectClass")} />
              </SelectTrigger>
              <SelectContent>
                {classes.map((c) => (
                  <SelectItem key={c.id} value={c.id}>
                    {c.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label htmlFor="lateThresholdMinutes">{t("rules.lateThreshold")}</Label>
              <Input
                id="lateThresholdMinutes"
                type="number"
                min="0"
                value={lateThreshold}
                onChange={(e) => setLateThreshold(e.target.value)}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="earlyLeaveThresholdMinutes">{t("rules.earlyLeaveThreshold")}</Label>
              <Input
                id="earlyLeaveThresholdMinutes"
                type="number"
                min="0"
                value={earlyLeaveThreshold}
                onChange={(e) => setEarlyLeaveThreshold(e.target.value)}
              />
            </div>
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="enableAutoMark"
              checked={enableAutoMark}
              onCheckedChange={(v) => setEnableAutoMark(v === true)}
            />
            <Label htmlFor="enableAutoMark" className="cursor-pointer">
              {t("rules.enableAutoMark")}
            </Label>
          </div>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 border-t pt-4">
            <div className="grid gap-2">
              <Label htmlFor="attendanceRateThreshold">{t("rules.attendanceRateThreshold")}</Label>
              <Input
                id="attendanceRateThreshold"
                type="number"
                min="0"
                max="100"
                value={attendanceRateThreshold}
                onChange={(e) => setAttendanceRateThreshold(e.target.value)}
              />
              <p className="text-xs text-muted-foreground">{t("rules.attendanceRateThresholdHint")}</p>
            </div>
            <div className="grid gap-2">
              <Label htmlFor="consecutiveAbsenceThreshold">{t("rules.consecutiveAbsenceThreshold")}</Label>
              <Input
                id="consecutiveAbsenceThreshold"
                type="number"
                min="1"
                value={consecutiveAbsenceThreshold}
                onChange={(e) => setConsecutiveAbsenceThreshold(e.target.value)}
              />
              <p className="text-xs text-muted-foreground">{t("rules.consecutiveAbsenceThresholdHint")}</p>
            </div>
          </div>

          <CardFooter className="justify-end gap-2 px-0">
            <Button type="button" variant="outline" onClick={() => router.back()}>
              {t("actions.cancel")}
            </Button>
            <SubmitButton />
          </CardFooter>
        </form>
      </CardContent>
    </Card>
  )
}
