"use client"

import { useState, useCallback } from "react"
import Image from "next/image"
import { ChevronLeft, ChevronRight, ZoomIn, ZoomOut, Maximize2, RotateCw } from "lucide-react"
import { useTranslations } from "next-intl"

import { Button } from "@/shared/components/ui/button"
import { cn } from "@/shared/lib/utils"
import type { ScanImage } from "./scan-uploader"

interface ScanImageViewerProps {
  images: ScanImage[]
  className?: string
}

/**
 * 扫描图查看器 —— 用于阅卷式批改时查看学生答题图片。
 * 支持翻页、缩放、旋转、全屏。
 */
export function ScanImageViewer({ images, className }: ScanImageViewerProps) {
  const t = useTranslations("examHomework")
  const [currentPage, setCurrentPage] = useState(0)
  const [zoom, setZoom] = useState(1)
  const [rotation, setRotation] = useState(0)

  const goToPage = useCallback(
    (page: number) => {
      if (images.length === 0) return
      const clamped = Math.max(0, Math.min(images.length - 1, page))
      setCurrentPage(clamped)
      setZoom(1)
      setRotation(0)
    },
    [images.length]
  )

  const handlePrev = useCallback(() => goToPage(currentPage - 1), [currentPage, goToPage])
  const handleNext = useCallback(() => goToPage(currentPage + 1), [currentPage, goToPage])

  const handleZoomIn = useCallback(() => {
    setZoom((z) => Math.min(3, z + 0.25))
  }, [])

  const handleZoomOut = useCallback(() => {
    setZoom((z) => Math.max(0.5, z - 0.25))
  }, [])

  const handleRotate = useCallback(() => {
    setRotation((r) => (r + 90) % 360)
  }, [])

  const handleFullscreen = useCallback(() => {
    const img = document.getElementById("scan-image-fullscreen")
    if (img?.requestFullscreen) {
      void img.requestFullscreen()
    }
  }, [])

  if (images.length === 0) {
    return (
      <div className={cn("flex h-full items-center justify-center text-muted-foreground", className)}>
        <div className="text-center">
          <p>{t("homework.scanViewer.noImages")}</p>
          <p className="mt-1 text-xs">{t("homework.scanViewer.noImagesHint")}</p>
        </div>
      </div>
    )
  }

  const currentImage = images[currentPage]
  if (!currentImage) return null

  return (
    <div className={cn("flex h-full flex-col", className)}>
      {/* 工具栏 */}
      <div className="flex items-center justify-between border-b bg-muted/30 px-3 py-1.5">
        <div className="flex items-center gap-1">
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="h-7 w-7"
            onClick={handleZoomOut}
            disabled={zoom <= 0.5}
            title={t("homework.scanViewer.zoomOut")}
          >
            <ZoomOut className="h-3.5 w-3.5" />
          </Button>
          <span className="min-w-[44px] text-center text-xs tabular-nums">
            {Math.round(zoom * 100)}%
          </span>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="h-7 w-7"
            onClick={handleZoomIn}
            disabled={zoom >= 3}
            title={t("homework.scanViewer.zoomIn")}
          >
            <ZoomIn className="h-3.5 w-3.5" />
          </Button>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="h-7 w-7"
            onClick={handleRotate}
            title={t("homework.scanViewer.rotate")}
          >
            <RotateCw className="h-3.5 w-3.5" />
          </Button>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="h-7 w-7"
            onClick={handleFullscreen}
            title={t("homework.scanViewer.fullscreen")}
          >
            <Maximize2 className="h-3.5 w-3.5" />
          </Button>
        </div>
        <div className="text-xs text-muted-foreground">
          {t("homework.scanViewer.pageIndicator", { current: currentPage + 1, total: images.length })}
        </div>
      </div>

      {/* 图片显示区 */}
      <div className="relative flex-1 overflow-auto bg-neutral-100 dark:bg-neutral-900">
        <div className="flex min-h-full items-center justify-center p-4">
          <div
            id="scan-image-fullscreen"
            className="relative"
            style={{
              transform: `scale(${zoom}) rotate(${rotation}deg)`,
              transformOrigin: "center center",
              transition: "transform 0.2s ease-out",
            }}
          >
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={currentImage.url}
              alt={t("homework.scanViewer.answerImageAlt", { page: currentImage.page })}
              className="max-h-full max-w-full object-contain shadow-lg"
              style={{ maxHeight: "80vh" }}
            />
          </div>
        </div>

        {/* 翻页按钮 */}
        {images.length > 1 && (
          <>
            <Button
              type="button"
              variant="secondary"
              size="icon"
              className="absolute left-2 top-1/2 -translate-y-1/2"
              onClick={handlePrev}
              disabled={currentPage === 0}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button
              type="button"
              variant="secondary"
              size="icon"
              className="absolute right-2 top-1/2 -translate-y-1/2"
              onClick={handleNext}
              disabled={currentPage === images.length - 1}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </>
        )}
      </div>

      {/* 缩略图导航 */}
      {images.length > 1 && (
        <div className="flex gap-1.5 overflow-x-auto border-t bg-muted/20 p-2">
          {images.map((img, idx) => (
            <button
              key={img.fileId}
              type="button"
              onClick={() => goToPage(idx)}
              className={cn(
                "relative h-16 w-12 overflow-hidden rounded border-2 transition-colors",
                idx === currentPage
                  ? "border-primary"
                  : "border-transparent hover:border-muted-foreground/30"
              )}
            >
              <Image
                src={img.url}
                alt={t("homework.scanViewer.thumbnailAlt", { page: img.page })}
                fill
                sizes="48px"
                className="h-full w-full object-cover"
              />
              <span className="absolute bottom-0 left-0 right-0 bg-black/60 px-1 text-center text-[10px] text-white">
                {img.page}
              </span>
            </button>
          ))}
        </div>
      )}
    </div>
  )
}
