"use client"

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

import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Button } from "@/shared/components/ui/button"
import { Label } from "@/shared/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"

import { autoScheduleAction, applyAutoScheduleAction } from "../actions"
import { AutoScheduleResultView } from "./auto-schedule-result"
import type { AutoScheduleResult } from "../types"

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

export function AutoSchedulePanel({ classes }: { classes: ClassOption[] }) {
  const router = useRouter()
  const [classId, setClassId] = useState(classes[0]?.id ?? "")
  const [loading, setLoading] = useState(false)
  const [applying, setApplying] = useState(false)
  const [result, setResult] = useState<AutoScheduleResult | null>(null)

  const handlePreview = async () => {
    if (!classId) {
      toast.error("Please select a class")
      return
    }
    setLoading(true)
    try {
      const formData = new FormData()
      formData.set("classId", classId)
      const res = await autoScheduleAction(null, formData)
      if (res.success && res.data) {
        setResult(res.data)
        toast.success(res.message)
      } else {
        toast.error(res.message || "Failed to generate schedule")
      }
    } catch {
      toast.error("Failed to generate schedule")
    } finally {
      setLoading(false)
    }
  }

  const handleApply = async () => {
    if (!result || !classId) return
    setApplying(true)
    try {
      const res = await applyAutoScheduleAction(
        classId,
        result.schedules.map((s) => ({
          weekday: s.weekday,
          startTime: s.startTime,
          endTime: s.endTime,
          course: s.course,
          location: s.location,
        }))
      )
      if (res.success) {
        toast.success(res.message)
        router.refresh()
      } else {
        toast.error(res.message || "Failed to apply schedule")
      }
    } catch {
      toast.error("Failed to apply schedule")
    } finally {
      setApplying(false)
    }
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Auto Schedule</CardTitle>
        </CardHeader>
        <CardContent 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="flex gap-2">
            <Button onClick={handlePreview} disabled={loading || !classId}>
              {loading ? "Generating..." : "Preview Schedule"}
            </Button>
            {result && (
              <Button onClick={handleApply} disabled={applying || result.schedules.length === 0} variant="default">
                {applying ? "Applying..." : "Apply to Class"}
              </Button>
            )}
          </div>
        </CardContent>
      </Card>

      {result && <AutoScheduleResultView result={result} />}
    </div>
  )
}
