"use client"

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

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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"

import { saveSchedulingRulesAction } from "../actions"
import type { SchedulingRule } from "../types"

type ClassOption = { id: string; name: string; grade: string }

function SubmitButton() {
  const { pending } = useFormStatus()
  return (
    <Button type="submit" disabled={pending}>
      {pending ? "Saving..." : "Save Rules"}
    </Button>
  )
}

export function SchedulingRulesForm({
  classes,
  existingRules,
}: {
  classes: ClassOption[]
  existingRules: SchedulingRule[]
}) {
  const router = useRouter()
  const [classId, setClassId] = useState(classes[0]?.id ?? "")
  const [maxDailyHours, setMaxDailyHours] = useState("8")
  const [maxContinuousHours, setMaxContinuousHours] = useState("2")
  const [lunchBreakStart, setLunchBreakStart] = useState("12:00")
  const [lunchBreakEnd, setLunchBreakEnd] = useState("13:00")
  const [morningStart, setMorningStart] = useState("08:00")
  const [afternoonEnd, setAfternoonEnd] = useState("17:00")
  const [avoidBackToBack, setAvoidBackToBack] = useState(false)
  const [balancedSubjects, setBalancedSubjects] = useState(true)

  const handleClassChange = (id: string) => {
    setClassId(id)
    const rule = existingRules.find((r) => r.classId === id)
    if (rule) {
      setMaxDailyHours(String(rule.maxDailyHours ?? 8))
      setMaxContinuousHours(String(rule.maxContinuousHours ?? 2))
      setLunchBreakStart(rule.lunchBreakStart ?? "12:00")
      setLunchBreakEnd(rule.lunchBreakEnd ?? "13:00")
      setMorningStart(rule.morningStart ?? "08:00")
      setAfternoonEnd(rule.afternoonEnd ?? "17:00")
      setAvoidBackToBack(rule.avoidBackToBack ?? false)
      setBalancedSubjects(rule.balancedSubjects ?? true)
    } else {
      const global = existingRules.find((r) => r.classId === null)
      if (global) {
        setMaxDailyHours(String(global.maxDailyHours ?? 8))
        setMaxContinuousHours(String(global.maxContinuousHours ?? 2))
        setLunchBreakStart(global.lunchBreakStart ?? "12:00")
        setLunchBreakEnd(global.lunchBreakEnd ?? "13:00")
        setMorningStart(global.morningStart ?? "08:00")
        setAfternoonEnd(global.afternoonEnd ?? "17:00")
        setAvoidBackToBack(global.avoidBackToBack ?? false)
        setBalancedSubjects(global.balancedSubjects ?? true)
      } else {
        setMaxDailyHours("8")
        setMaxContinuousHours("2")
        setLunchBreakStart("12:00")
        setLunchBreakEnd("13:00")
        setMorningStart("08:00")
        setAfternoonEnd("17:00")
        setAvoidBackToBack(false)
        setBalancedSubjects(true)
      }
    }
  }

  const handleSubmit = async (formData: FormData) => {
    if (!classId) {
      toast.error("Please select a class")
      return
    }
    formData.set("classId", classId)
    formData.set("maxDailyHours", maxDailyHours)
    formData.set("maxContinuousHours", maxContinuousHours)
    formData.set("lunchBreakStart", lunchBreakStart)
    formData.set("lunchBreakEnd", lunchBreakEnd)
    formData.set("morningStart", morningStart)
    formData.set("afternoonEnd", afternoonEnd)
    formData.set("avoidBackToBack", avoidBackToBack ? "true" : "false")
    formData.set("balancedSubjects", balancedSubjects ? "true" : "false")

    const result = await saveSchedulingRulesAction(null, formData)
    if (result.success) {
      toast.success(result.message)
      router.refresh()
    } else {
      toast.error(result.message || "Failed to save rules")
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Scheduling Rules</CardTitle>
      </CardHeader>
      <CardContent>
        <form action={handleSubmit} className="space-y-6">
          <div className="grid gap-2">
            <Label>Class</Label>
            <Select value={classId} onValueChange={handleClassChange}>
              <SelectTrigger>
                <SelectValue placeholder="Select a class" />
              </SelectTrigger>
              <SelectContent>
                {classes.map((c) => (
                  <SelectItem key={c.id} value={c.id}>
                    {c.grade} - {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="maxDailyHours">Max Daily Hours</Label>
              <Input
                id="maxDailyHours"
                type="number"
                min="1"
                max="24"
                value={maxDailyHours}
                onChange={(e) => setMaxDailyHours(e.target.value)}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="maxContinuousHours">Max Continuous Hours</Label>
              <Input
                id="maxContinuousHours"
                type="number"
                min="1"
                max="12"
                value={maxContinuousHours}
                onChange={(e) => setMaxContinuousHours(e.target.value)}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label htmlFor="morningStart">Morning Start</Label>
              <Input
                id="morningStart"
                type="time"
                value={morningStart}
                onChange={(e) => setMorningStart(e.target.value)}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="afternoonEnd">Afternoon End</Label>
              <Input
                id="afternoonEnd"
                type="time"
                value={afternoonEnd}
                onChange={(e) => setAfternoonEnd(e.target.value)}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label htmlFor="lunchBreakStart">Lunch Break Start</Label>
              <Input
                id="lunchBreakStart"
                type="time"
                value={lunchBreakStart}
                onChange={(e) => setLunchBreakStart(e.target.value)}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="lunchBreakEnd">Lunch Break End</Label>
              <Input
                id="lunchBreakEnd"
                type="time"
                value={lunchBreakEnd}
                onChange={(e) => setLunchBreakEnd(e.target.value)}
              />
            </div>
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="avoidBackToBack"
              checked={avoidBackToBack}
              onCheckedChange={(v) => setAvoidBackToBack(v === true)}
            />
            <Label htmlFor="avoidBackToBack" className="cursor-pointer">
              Avoid back-to-back sessions
            </Label>
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="balancedSubjects"
              checked={balancedSubjects}
              onCheckedChange={(v) => setBalancedSubjects(v === true)}
            />
            <Label htmlFor="balancedSubjects" className="cursor-pointer">
              Balance subjects across the week
            </Label>
          </div>

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