"use client"

import { useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-react"
import { toast } from "sonner"

import { cn } from "@/shared/lib/utils"
import { Button } from "@/shared/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/components/ui/select"
import type { ClassScheduleItem, TeacherClass } from "../types"
import {
  createClassScheduleItemAction,
  deleteClassScheduleItemAction,
  updateClassScheduleItemAction,
} from "../actions"

const WEEKDAYS: Array<{ key: ClassScheduleItem["weekday"]; label: string }> = [
  { key: 1, label: "Mon" },
  { key: 2, label: "Tue" },
  { key: 3, label: "Wed" },
  { key: 4, label: "Thu" },
  { key: 5, label: "Fri" },
  { key: 6, label: "Sat" },
  { key: 7, label: "Sun" },
]

export function ScheduleView({
  schedule,
  classes,
}: {
  schedule: ClassScheduleItem[]
  classes: TeacherClass[]
}) {
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const [editItem, setEditItem] = useState<ClassScheduleItem | null>(null)
  const [deleteItem, setDeleteItem] = useState<ClassScheduleItem | null>(null)

  const [createWeekday, setCreateWeekday] = useState<ClassScheduleItem["weekday"]>(1)
  const [createOpen, setCreateOpen] = useState(false)
  const [createClassId, setCreateClassId] = useState<string>("")

  const [editClassId, setEditClassId] = useState<string>("")
  const [editWeekday, setEditWeekday] = useState<string>("1")

  const classNameById = useMemo(() => new Map(classes.map((c) => [c.id, c.name] as const)), [classes])
  const defaultClassId = useMemo(() => classes[0]?.id ?? "", [classes])

  useEffect(() => {
    if (!editItem) return
    setEditClassId(editItem.classId)
    setEditWeekday(String(editItem.weekday))
  }, [editItem])

  useEffect(() => {
    if (!createOpen) return
    setCreateClassId(defaultClassId)
  }, [createOpen, defaultClassId])

  const byDay = new Map<ClassScheduleItem["weekday"], ClassScheduleItem[]>()
  for (const d of WEEKDAYS) byDay.set(d.key, [])
  for (const item of schedule) byDay.get(item.weekday)?.push(item)

  const handleCreate = async (formData: FormData) => {
    setIsWorking(true)
    try {
      formData.set("classId", createClassId || defaultClassId)
      formData.set("weekday", String(createWeekday))
      const res = await createClassScheduleItemAction(null, formData)
      if (res.success) {
        toast.success(res.message)
        setCreateOpen(false)
        router.refresh()
      } else {
        toast.error(res.message || "Failed to create schedule item")
      }
    } catch {
      toast.error("Failed to create schedule item")
    } finally {
      setIsWorking(false)
    }
  }

  const handleUpdate = async (formData: FormData) => {
    if (!editItem) return
    setIsWorking(true)
    try {
      formData.set("classId", editClassId)
      formData.set("weekday", editWeekday)
      const res = await updateClassScheduleItemAction(editItem.id, null, formData)
      if (res.success) {
        toast.success(res.message)
        setEditItem(null)
        router.refresh()
      } else {
        toast.error(res.message || "Failed to update schedule item")
      }
    } catch {
      toast.error("Failed to update schedule item")
    } finally {
      setIsWorking(false)
    }
  }

  const handleDelete = async () => {
    if (!deleteItem) return
    setIsWorking(true)
    try {
      const res = await deleteClassScheduleItemAction(deleteItem.id)
      if (res.success) {
        toast.success(res.message)
        setDeleteItem(null)
        router.refresh()
      } else {
        toast.error(res.message || "Failed to delete schedule item")
      }
    } catch {
      toast.error("Failed to delete schedule item")
    } finally {
      setIsWorking(false)
    }
  }

  const getPositionStyle = (startTime: string, endTime: string) => {
    // Range 8:00 (480 min) -> 18:00 (1080 min)
    // Total duration: 600 min
    const startParts = startTime.split(':').map(Number)
    const endParts = endTime.split(':').map(Number)
    
    const startMinutes = startParts[0] * 60 + startParts[1]
    const endMinutes = endParts[0] * 60 + endParts[1]
    
    const minTime = 8 * 60
    const maxTime = 18 * 60
    const totalDuration = maxTime - minTime
    
    // Calculate percentage positions
    const top = Math.max(0, ((startMinutes - minTime) / totalDuration) * 100)
    const height = Math.min(100 - top, ((endMinutes - startMinutes) / totalDuration) * 100)
    
    return {
      top: `${top}%`,
      height: `${height}%`,
    }
  }

  const HOURS = Array.from({ length: 11 }, (_, i) => 8 + i) // 8, 9, ..., 18

  // Predefined colors for different subjects to add visual variety
  const getSubjectColor = (subject: string) => {
    const s = subject.toLowerCase()
    if (s.includes('math')) return 'bg-blue-500/10 text-blue-700 border-blue-500/20 hover:bg-blue-500/20'
    if (s.includes('physics') || s.includes('science')) return 'bg-purple-500/10 text-purple-700 border-purple-500/20 hover:bg-purple-500/20'
    if (s.includes('english') || s.includes('lit')) return 'bg-amber-500/10 text-amber-700 border-amber-500/20 hover:bg-amber-500/20'
    if (s.includes('history') || s.includes('geo')) return 'bg-orange-500/10 text-orange-700 border-orange-500/20 hover:bg-orange-500/20'
    if (s.includes('art') || s.includes('music')) return 'bg-pink-500/10 text-pink-700 border-pink-500/20 hover:bg-pink-500/20'
    if (s.includes('sport') || s.includes('pe')) return 'bg-emerald-500/10 text-emerald-700 border-emerald-500/20 hover:bg-emerald-500/20'
    return 'bg-primary/10 text-primary border-primary/20 hover:bg-primary/20'
  }

  return (
    <div className="h-[600px] flex flex-col">
      <div className="flex h-full">
        {/* Time Axis */}
        <div className="w-14 flex-shrink-0 flex flex-col">
          <div className="h-10" /> {/* Header spacer */}
          <div className="flex-1 relative">
            {HOURS.map((h, i) => (
              <div 
                key={h} 
                className="absolute w-full text-right pr-3 text-[11px] text-muted-foreground/60 font-medium -translate-y-1/2 font-mono"
                style={{ top: `${(i / 10) * 100}%` }}
              >
                {h}:00
              </div>
            ))}
          </div>
        </div>

        {/* Days Columns */}
        <div className="flex-1 grid grid-cols-5">
          {WEEKDAYS.slice(0, 5).map((d) => (
            <div key={d.key} className="flex flex-col h-full min-w-0">
              <div className="flex items-center justify-center py-2 h-10 group">
                <span className="text-xs font-semibold text-muted-foreground group-hover:text-foreground transition-colors uppercase tracking-wider">{d.label}</span>
              </div>
              
              <div className="relative h-full mx-1">
                {/* Subtle vertical guideline */}
                <div className="absolute left-0 top-0 bottom-0 w-px bg-border/30" />
                
                {(byDay.get(d.key) ?? []).map((item) => (
                  <div 
                    key={item.id} 
                    className="group absolute w-full px-1 z-10"
                    style={getPositionStyle(item.startTime, item.endTime)}
                  >
                    <div className={cn(
                      "rounded-md p-2 text-xs text-left relative transition-all cursor-default leading-tight h-full border overflow-hidden shadow-sm hover:shadow-md flex flex-col justify-center",
                      getSubjectColor(item.course)
                    )}>
                      <div className="flex justify-between items-start gap-1">
                        <div className="min-w-0 flex-1 flex flex-col gap-0.5">
                          <div className="font-bold truncate text-[11px] leading-none tracking-tight">{item.course}</div>
                          <div className="opacity-80 scale-95 origin-left whitespace-nowrap tabular-nums text-[10px] font-medium leading-none font-mono">
                            {item.startTime} - {item.endTime}
                          </div>
                          <div className="opacity-70 scale-95 origin-left truncate text-[9px] leading-none mt-0.5 font-medium">
                            {classNameById.get(item.classId)}
                          </div>
                        </div>
                        
                        <div className="opacity-0 group-hover:opacity-100 transition-opacity absolute top-1 right-1">
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon" className="h-5 w-5 hover:bg-background/20 p-0" disabled={isWorking}>
                                <MoreHorizontal className="h-3.5 w-3.5" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end" className="w-32">
                              <DropdownMenuItem onClick={() => setEditItem(item)} className="text-xs">
                                <Pencil className="mr-2 h-3 w-3" />
                                Edit
                              </DropdownMenuItem>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                className="text-xs text-destructive focus:text-destructive"
                                onClick={() => setDeleteItem(item)}
                              >
                                <Trash2 className="mr-2 h-3 w-3" />
                                Delete
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
                
                {/* Add Button Overlay - Only visible on hover of the column */}
                <div className="absolute inset-0 opacity-0 hover:opacity-100 transition-opacity pointer-events-none">
                   <div className="absolute top-2 right-2 pointer-events-auto">
                      <Button
                        variant="secondary"
                        size="icon"
                        className="h-6 w-6 rounded-full shadow-sm bg-background/80 backdrop-blur-sm hover:bg-primary hover:text-primary-foreground transition-all"
                        disabled={classes.length === 0}
                        onClick={() => {
                          setCreateWeekday(d.key)
                          setCreateOpen(true)
                        }}
                      >
                        <Plus className="h-3 w-3" />
                      </Button>
                   </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <Dialog
        open={createOpen}
        onOpenChange={(v) => {
          if (isWorking) return
          setCreateOpen(v)
        }}
      >
        <DialogContent className="sm:max-w-[560px]">
          <DialogHeader>
            <DialogTitle>Add schedule item</DialogTitle>
            <DialogDescription>Create a class schedule entry.</DialogDescription>
          </DialogHeader>
          <form action={handleCreate}>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">Class</Label>
                <div className="col-span-3">
                  <Select value={createClassId} onValueChange={setCreateClassId}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select a class" />
                    </SelectTrigger>
                    <SelectContent>
                      {classes.map((c) => (
                        <SelectItem key={c.id} value={c.id}>
                          {c.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <input type="hidden" name="classId" value={createClassId} />
                </div>
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">Weekday</Label>
                <Input value={WEEKDAYS.find((w) => w.key === createWeekday)?.label ?? ""} readOnly className="col-span-3" />
                <input type="hidden" name="weekday" value={String(createWeekday)} />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="create-startTime" className="text-right">
                  Start
                </Label>
                <Input id="create-startTime" name="startTime" type="time" className="col-span-3" required />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="create-endTime" className="text-right">
                  End
                </Label>
                <Input id="create-endTime" name="endTime" type="time" className="col-span-3" required />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="create-course" className="text-right">
                  Course
                </Label>
                <Input id="create-course" name="course" className="col-span-3" placeholder="e.g. Math" required />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="create-location" className="text-right">
                  Location
                </Label>
                <Input id="create-location" name="location" className="col-span-3" placeholder="Optional" />
              </div>
            </div>
            <DialogFooter>
              <Button type="submit" disabled={isWorking || !createClassId}>
                {isWorking ? "Creating..." : "Create"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog
        open={!!editItem}
        onOpenChange={(v) => {
          if (isWorking) return
          if (!v) setEditItem(null)
        }}
      >
        <DialogContent className="sm:max-w-[560px]">
          <DialogHeader>
            <DialogTitle>Edit schedule item</DialogTitle>
            <DialogDescription>Update class schedule entry.</DialogDescription>
          </DialogHeader>
          <form action={handleUpdate}>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">Class</Label>
                <div className="col-span-3">
                  <Select value={editClassId} onValueChange={setEditClassId}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select a class" />
                    </SelectTrigger>
                    <SelectContent>
                      {classes.map((c) => (
                        <SelectItem key={c.id} value={c.id}>
                          {c.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <input type="hidden" name="classId" value={editClassId} />
                </div>
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-weekday" className="text-right">
                  Weekday
                </Label>
                <div className="col-span-3">
                  <Select value={editWeekday} onValueChange={setEditWeekday}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select weekday" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="1">Mon</SelectItem>
                      <SelectItem value="2">Tue</SelectItem>
                      <SelectItem value="3">Wed</SelectItem>
                      <SelectItem value="4">Thu</SelectItem>
                      <SelectItem value="5">Fri</SelectItem>
                      <SelectItem value="6">Sat</SelectItem>
                      <SelectItem value="7">Sun</SelectItem>
                    </SelectContent>
                  </Select>
                  <input type="hidden" name="weekday" value={editWeekday} />
                </div>
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-startTime" className="text-right">
                  Start
                </Label>
                <Input
                  id="edit-startTime"
                  name="startTime"
                  type="time"
                  className="col-span-3"
                  defaultValue={editItem?.startTime}
                  required
                />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-endTime" className="text-right">
                  End
                </Label>
                <Input
                  id="edit-endTime"
                  name="endTime"
                  type="time"
                  className="col-span-3"
                  defaultValue={editItem?.endTime}
                  required
                />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-course" className="text-right">
                  Course
                </Label>
                <Input
                  id="edit-course"
                  name="course"
                  className="col-span-3"
                  defaultValue={editItem?.course}
                  placeholder="e.g. Math"
                  required
                />
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-location" className="text-right">
                  Location
                </Label>
                <Input
                  id="edit-location"
                  name="location"
                  className="col-span-3"
                  defaultValue={editItem?.location ?? ""}
                  placeholder="Optional"
                />
              </div>
            </div>
            <DialogFooter>
              <Button type="submit" disabled={isWorking || !editClassId}>
                {isWorking ? "Saving..." : "Save changes"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <AlertDialog
        open={!!deleteItem}
        onOpenChange={(v) => {
          if (isWorking) return
          if (!v) setDeleteItem(null)
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This will permanently delete this schedule item.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isWorking}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={(e) => {
                e.preventDefault()
                handleDelete()
              }}
              disabled={isWorking}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {isWorking ? "Deleting..." : "Delete"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
