"use client"

import type { JSX } from "react"
import { useTranslations } from "next-intl"
import Link from "next/link"
import { useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { GripVertical, ExternalLink, BookOpen } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import {
  TableCell,
  TableRow,
} from "@/shared/components/ui/table"
import { cn } from "@/shared/lib/utils"

import type { CoursePlanWithItems } from "../types"

interface SortableWeekRowProps {
  item: CoursePlanWithItems["items"][number]
  canManage: boolean
  isSelected: boolean
  onToggleSelect: (id: string) => void
  onEdit: (item: CoursePlanWithItems["items"][number]) => void
  /** 教材列表页地址（按角色不同）；提供时章节文本渲染为可跳转链接 */
  textbooksHref?: string
  /** 作业列表页地址（按角色不同）；提供时显示作业跳转按钮 */
  homeworkHref?: string
}

/**
 * 可拖拽排序的周计划表格行。
 *
 * 使用 @dnd-kit/sortable 提供拖拽能力：
 * - 仅当 `canManage=true` 时启用拖拽（通过 disabled 控制）
 * - 拖拽手柄单独位于第一列，避免点击/复选交互被误触发
 * - 行点击（非手柄/复选区域）仍可触发 `onEdit`
 *
 * 数据联动（P2-3）：
 * - `textbookChapter` 在提供 `textbooksHref` 时渲染为链接，支持一键跳转教材列表
 * - 行尾在提供 `homeworkHref` 时显示作业跳转按钮
 *
 * 可访问性：
 * - 手柄带 `aria-label`，键盘可通过 sortableKeyboardCoordinates 排序
 * - 复选框带 `aria-label` 描述所选周次
 * - 跳转链接带描述性 `aria-label`
 */
export function SortableWeekRow({
  item,
  canManage,
  isSelected,
  onToggleSelect,
  onEdit,
  textbooksHref,
  homeworkHref,
}: SortableWeekRowProps): JSX.Element {
  const t = useTranslations("coursePlans")
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: item.id, disabled: !canManage })

  const style: React.CSSProperties = {
    transform: CSS.Transform.toString(transform),
    transition,
    zIndex: isDragging ? 10 : 1,
    position: "relative",
  }

  const handleRowClick = canManage ? () => onEdit(item) : undefined

  return (
    <TableRow
      ref={setNodeRef}
      style={style}
      className={cn(
        canManage && "cursor-pointer",
        isDragging && "opacity-50"
      )}
      onClick={handleRowClick}
    >
      {canManage ? (
        <TableCell
          onClick={(e) => e.stopPropagation()}
          className="w-8"
        >
          <button
            type="button"
            {...attributes}
            {...listeners}
            className="cursor-grab rounded p-1 text-muted-foreground/60 transition-colors hover:bg-muted hover:text-muted-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
            aria-label={t("detail.dragHandle")}
          >
            <GripVertical className="h-4 w-4" aria-hidden="true" />
          </button>
        </TableCell>
      ) : null}
      {canManage ? (
        <TableCell
          onClick={(e) => e.stopPropagation()}
          className="w-8"
        >
          <input
            type="checkbox"
            checked={isSelected}
            onChange={() => onToggleSelect(item.id)}
            className="h-4 w-4"
            aria-label={t("detail.selectWeekAria", { week: item.week })}
          />
        </TableCell>
      ) : null}
      <TableCell className="font-medium">{item.week}</TableCell>
      <TableCell>
        <div className="space-y-1">
          <p className="font-medium">{item.topic}</p>
          {item.content ? (
            <p className="line-clamp-2 text-xs text-muted-foreground">
              {item.content}
            </p>
          ) : null}
          {item.notes ? (
            <p className="text-xs text-muted-foreground italic">
              {t("detail.notes", { notes: item.notes })}
            </p>
          ) : null}
        </div>
      </TableCell>
      <TableCell>{item.hours}</TableCell>
      <TableCell className="text-muted-foreground">
        {item.textbookChapter ? (
          textbooksHref ? (
            <Link
              href={textbooksHref}
              className="inline-flex items-center gap-1 text-primary underline-offset-2 hover:underline"
              onClick={(e) => e.stopPropagation()}
              aria-label={t("detail.viewTextbookAria", { chapter: item.textbookChapter })}
            >
              <BookOpen className="h-3 w-3" aria-hidden="true" />
              {item.textbookChapter}
            </Link>
          ) : (
            item.textbookChapter
          )
        ) : (
          "—"
        )}
      </TableCell>
      <TableCell>
        <div className="flex items-center gap-2">
          <Badge variant={item.isCompleted ? "default" : "secondary"}>
            {item.isCompleted ? t("detail.completed") : t("detail.pending")}
          </Badge>
          {homeworkHref ? (
            <Button
              asChild
              variant="ghost"
              size="icon"
              className="h-6 w-6"
              aria-label={t("detail.viewHomeworkAria")}
              onClick={(e) => e.stopPropagation()}
            >
              <Link href={homeworkHref}>
                <ExternalLink className="h-3 w-3" aria-hidden="true" />
              </Link>
            </Button>
          ) : null}
        </div>
      </TableCell>
    </TableRow>
  )
}
