"use client"

import { useState } from "react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { AlertTriangle, CheckCircle2, RefreshCw } from "lucide-react"

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

import { getClassConflictsAction } from "../actions"
import type { ScheduleConflict } from "../types"

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

const CONFLICT_TYPE_LABELS: Record<ScheduleConflict["type"], string> = {
  teacher_overlap: "Teacher Overlap",
  classroom_overlap: "Classroom Overlap",
  class_overlap: "Class Overlap",
  rule_violation: "Rule Violation",
}

export function ScheduleConflictsView({ classes }: { classes: ClassOption[] }) {
  const router = useRouter()
  const [classId, setClassId] = useState(classes[0]?.id ?? "")
  const [loading, setLoading] = useState(false)
  const [conflicts, setConflicts] = useState<ScheduleConflict[] | null>(null)

  const handleCheck = async () => {
    if (!classId) {
      toast.error("Please select a class")
      return
    }
    setLoading(true)
    try {
      const res = await getClassConflictsAction(classId)
      if (res.success && res.data) {
        setConflicts(res.data)
        if (res.data.length === 0) {
          toast.success("No conflicts detected")
        } else {
          toast.warning(`Found ${res.data.length} conflict(s)`)
        }
      } else {
        toast.error(res.message || "Failed to check conflicts")
      }
    } catch {
      toast.error("Failed to check conflicts")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Conflict Detection</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-2">
            <label className="text-sm font-medium">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>

          <Button onClick={handleCheck} disabled={loading || !classId}>
            <RefreshCw className={`mr-2 h-4 w-4 ${loading ? "animate-spin" : ""}`} />
            {loading ? "Checking..." : "Check Conflicts"}
          </Button>
        </CardContent>
      </Card>

      {conflicts && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span>Results</span>
              <Badge variant={conflicts.length > 0 ? "destructive" : "default"}>
                {conflicts.length} conflict(s)
              </Badge>
            </CardTitle>
          </CardHeader>
          <CardContent>
            {conflicts.length === 0 ? (
              <div className="flex items-center gap-2 text-sm">
                <CheckCircle2 className="h-5 w-5 text-primary" />
                <span>No conflicts detected for this class schedule.</span>
              </div>
            ) : (
              <ul className="space-y-3">
                {conflicts.map((c, idx) => (
                  <li
                    key={idx}
                    className="flex flex-col gap-1 rounded-md border p-3 text-sm"
                  >
                    <div className="flex items-center gap-2">
                      <AlertTriangle className="h-4 w-4 text-destructive" />
                      <Badge variant="outline">{CONFLICT_TYPE_LABELS[c.type]}</Badge>
                    </div>
                    <p className="text-muted-foreground">{c.description}</p>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>
      )}

      {conflicts && conflicts.length === 0 && (
        <div className="flex justify-end">
          <Button variant="outline" onClick={() => router.refresh()}>
            Refresh Data
          </Button>
        </div>
      )}
    </div>
  )
}
