"use client"

import { useMemo, useState } from "react"
import { useTranslations } from "next-intl"
import { MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-react"

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 type { ClassScheduleItem, TeacherClass } from "../types"
import { getPositionStyle, getSubjectColor, SCHEDULE_WEEKDAYS } from "./schedule-utils"
import { ScheduleCreateDialog } from "./schedule-create-dialog"
import { ScheduleEditDialog } from "./schedule-edit-dialog"
import { ScheduleDeleteDialog } from "./schedule-delete-dialog"

/**
 * 课表周视图（P1-13：已将创建/编辑/删除对话框拆分为独立组件）。
 *
 * 本组件仅负责：
 * - 渲染时间轴与周列布局
 * - 渲染课表块及其 hover 操作菜单
 * - 维护当前打开的对话框状态（createOpen / editItem / deleteItem）
 */
export function ScheduleView({
  schedule,
  classes,
}: {
  schedule: ClassScheduleItem[]
  classes: TeacherClass[]
}) {
  const t = useTranslations("classes")
  const [editItem, setEditItem] = useState<ClassScheduleItem | null>(null)
  const [deleteItem, setDeleteItem] = useState<ClassScheduleItem | null>(null)
  const [createOpen, setCreateOpen] = useState(false)
  const [createWeekday, setCreateWeekday] = useState<ClassScheduleItem["weekday"]>(1)

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

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

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

  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">
          {SCHEDULE_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">{t(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">
                                <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" />
                                {t("list.actions.edit")}
                              </DropdownMenuItem>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem
                                className="text-xs text-destructive focus:text-destructive"
                                onClick={() => setDeleteItem(item)}
                              >
                                <Trash2 className="mr-2 h-3 w-3" />
                                {t("list.actions.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>

      <ScheduleCreateDialog
        open={createOpen}
        onOpenChange={setCreateOpen}
        classes={classes}
        defaultClassId={defaultClassId}
        weekday={createWeekday}
      />

      <ScheduleEditDialog
        editItem={editItem}
        classes={classes}
        onClose={() => setEditItem(null)}
      />

      <ScheduleDeleteDialog
        deleteItem={deleteItem}
        onClose={() => setDeleteItem(null)}
      />
    </div>
  )
}
