"use client"

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

import { requestScheduleChangeAction } from "../actions"

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

export function ScheduleChangeForm({
  classes,
  teachers,
  defaultClassId,
}: {
  classes: ClassOption[]
  teachers: TeacherOption[]
  defaultClassId?: string
}) {
  const router = useRouter()
  const [classId, setClassId] = useState(defaultClassId ?? classes[0]?.id ?? "")
  const [originalTeacherId, setOriginalTeacherId] = useState("")
  const [substituteTeacherId, setSubstituteTeacherId] = useState("")
  const [originalDate, setOriginalDate] = useState("")
  const [newDate, setNewDate] = useState("")
  const [newStartTime, setNewStartTime] = useState("")
  const [newEndTime, setNewEndTime] = useState("")
  const [reason, setReason] = useState("")
  const [submitting, setSubmitting] = useState(false)

  const handleSubmit = async (formData: FormData) => {
    if (!classId) {
      toast.error("Please select a class")
      return
    }
    if (!reason.trim()) {
      toast.error("Reason is required")
      return
    }
    setSubmitting(true)
    try {
      formData.set("classId", classId)
      if (originalTeacherId) formData.set("originalTeacherId", originalTeacherId)
      if (substituteTeacherId) formData.set("substituteTeacherId", substituteTeacherId)
      if (originalDate) formData.set("originalDate", originalDate)
      if (newDate) formData.set("newDate", newDate)
      if (newStartTime) formData.set("newStartTime", newStartTime)
      if (newEndTime) formData.set("newEndTime", newEndTime)
      formData.set("reason", reason)

      const res = await requestScheduleChangeAction(null, formData)
      if (res.success) {
        toast.success(res.message)
        router.refresh()
        // Reset form
        setOriginalDate("")
        setNewDate("")
        setNewStartTime("")
        setNewEndTime("")
        setReason("")
        setOriginalTeacherId("")
        setSubstituteTeacherId("")
      } else {
        toast.error(res.message || "Failed to submit request")
      }
    } catch {
      toast.error("Failed to submit request")
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Schedule Change Request</CardTitle>
      </CardHeader>
      <CardContent>
        <form action={handleSubmit} className="space-y-4">
          <div className="grid gap-2">
            <Label>Class</Label>
            <Select value={classId} onValueChange={setClassId}>
              <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="originalTeacherId">Original Teacher (optional)</Label>
              <Select value={originalTeacherId} onValueChange={setOriginalTeacherId}>
                <SelectTrigger id="originalTeacherId">
                  <SelectValue placeholder="Select original teacher" />
                </SelectTrigger>
                <SelectContent>
                  {teachers.map((t) => (
                    <SelectItem key={t.id} value={t.id}>
                      {t.name} ({t.email})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label htmlFor="substituteTeacherId">Substitute Teacher (optional)</Label>
              <Select value={substituteTeacherId} onValueChange={setSubstituteTeacherId}>
                <SelectTrigger id="substituteTeacherId">
                  <SelectValue placeholder="Select substitute teacher" />
                </SelectTrigger>
                <SelectContent>
                  {teachers.map((t) => (
                    <SelectItem key={t.id} value={t.id}>
                      {t.name} ({t.email})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label htmlFor="originalDate">Original Date (optional)</Label>
              <Input
                id="originalDate"
                type="date"
                value={originalDate}
                onChange={(e) => setOriginalDate(e.target.value)}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="newDate">New Date (optional)</Label>
              <Input
                id="newDate"
                type="date"
                value={newDate}
                onChange={(e) => setNewDate(e.target.value)}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label htmlFor="newStartTime">New Start Time (optional)</Label>
              <Input
                id="newStartTime"
                type="time"
                value={newStartTime}
                onChange={(e) => setNewStartTime(e.target.value)}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="newEndTime">New End Time (optional)</Label>
              <Input
                id="newEndTime"
                type="time"
                value={newEndTime}
                onChange={(e) => setNewEndTime(e.target.value)}
              />
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="reason">Reason</Label>
            <Textarea
              id="reason"
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder="Explain the reason for this schedule change..."
              rows={3}
            />
          </div>

          <CardFooter className="justify-end gap-2 px-0">
            <Button type="button" variant="outline" onClick={() => router.back()}>
              Cancel
            </Button>
            <Button type="submit" disabled={submitting}>
              {submitting ? "Submitting..." : "Submit Request"}
            </Button>
          </CardFooter>
        </form>
      </CardContent>
    </Card>
  )
}
