"use client"

import { useState, useMemo } from "react"
import { usePathname } from "next/navigation"
import { useTranslations } from "next-intl"
import { Bot, X, Sparkles, RotateCcw, ChevronLeft } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
} from "@/shared/components/ui/sheet"
import { AiChatPanel } from "./ai-chat-panel"
import { useAiClientOptional } from "../context/ai-client-provider"
import { useFloatingBall } from "../hooks/use-floating-ball"

/**
 * 上下文感知规则
 *
 * 根据当前路由推断用户上下文，动态生成 systemPrompt 和 contextMessage。
 */
type AiContextConfig = {
  systemPrompt: string
  contextMessage: string
  suggestedPrompts?: string[]
}

/**
 * 全局 AI 助手悬浮球（360 悬浮球风格）
 *
 * 特性：
 * - 可拖拽移动，松手吸附到最近屏幕边缘
 * - 拖到边缘自动半隐藏（只露出一小部分）
 * - 鼠标悬停时恢复显示
 * - 位置持久化到 localStorage
 * - 点击打开侧边抽屉，内嵌 AiChatPanel
 * - 上下文感知：根据当前路由自动推断用户场景
 *
 * 使用：
 * 在 dashboard layout 中引入即可全局生效。
 * 需要 AiClientProvider 包裹（可选，未注入时按钮不显示）。
 */
export function AiAssistantWidget(): React.ReactNode {
  const t = useTranslations("ai")
  const pathname = usePathname()
  const aiClient = useAiClientOptional()
  const [open, setOpen] = useState(false)
  const [chatKey, setChatKey] = useState(0)

  const handleBallClick = () => setOpen(true)
  const ball = useFloatingBall(handleBallClick)

  // 根据路由推断上下文
  const contextConfig = useMemo<AiContextConfig>(() => {
    return inferContextFromPath(pathname, t)
  }, [pathname, t])

  // 如果未注入 AI 客户端服务，不显示悬浮按钮
  if (!aiClient) {
    return null
  }

  const { position, hidden, dragging, hovered, hiddenOffset, handlers, show, resetPosition } = ball

  // 首次渲染时 position 为占位值（屏幕外），避免闪烁
  const isReady = position.x < 9999

  return (
    <>
      {/* 悬浮球 */}
      {isReady ? (
        <button
          type="button"
          aria-label={hidden ? t("widget.show") : t("widget.open")}
          className="fixed z-50 flex select-none items-center justify-center rounded-full bg-gradient-to-br from-primary to-primary/80 text-primary-foreground shadow-lg transition-[width,height,opacity,transform] duration-200 ease-out hover:shadow-xl hover:scale-105 touch-none"
          style={{
            left: `${position.x}px`,
            top: `${position.y}px`,
            width: "56px",
            height: "56px",
            transform: `translateX(${hiddenOffset}px) ${dragging ? "scale(1.1)" : ""}`,
            cursor: dragging ? "grabbing" : "grab",
            opacity: hidden && !hovered ? 0.55 : 1,
            transition: dragging ? "none" : "transform 0.25s ease-out, opacity 0.25s ease-out",
          }}
          onPointerDown={handlers.onPointerDown}
          onPointerMove={handlers.onPointerMove}
          onPointerUp={handlers.onPointerUp}
          onPointerCancel={handlers.onPointerCancel}
          onMouseEnter={handlers.onMouseEnter}
          onMouseLeave={handlers.onMouseLeave}
          onClick={(e) => {
            // 拖动产生的 click 不触发打开
            if (e.detail === 0) return
          }}
        >
          <Bot className="h-6 w-6 drop-shadow-sm" />
          <span className="pointer-events-none absolute -top-0.5 -right-0.5 flex h-3 w-3">
            <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
            <span className="relative inline-flex rounded-full h-3 w-3 bg-emerald-500 ring-2 ring-background" />
          </span>
          {hidden ? (
            <span className="pointer-events-none absolute inset-0 flex items-center justify-center rounded-full bg-primary/30 opacity-0 transition-opacity hover:opacity-100">
              <ChevronLeft
                className="h-4 w-4"
                style={{
                  transform: position.x <= 16 ? "rotate(0deg)" : "rotate(180deg)",
                }}
              />
            </span>
          ) : null}
        </button>
      ) : null}

      {/* 半隐藏时的提示条 */}
      {hidden && isReady ? (
        <button
          type="button"
          aria-label={t("widget.show")}
          className="fixed z-40 flex items-center justify-center rounded-full bg-primary/15 text-primary backdrop-blur-sm transition-opacity hover:bg-primary/25"
          style={{
            left: `${position.x + (hiddenOffset > 0 ? 0 : BALL_SIZE * 0.45)}px`,
            top: `${position.y}px`,
            width: "14px",
            height: "56px",
            cursor: "pointer",
          }}
          onClick={show}
        >
          <ChevronLeft
            className="h-3 w-3"
            style={{
              transform: position.x <= 16 ? "rotate(0deg)" : "rotate(180deg)",
            }}
          />
        </button>
      ) : null}

      {/* 侧边抽屉 */}
      <Sheet open={open} onOpenChange={setOpen}>
        <SheetContent hideClose className="w-full sm:max-w-lg overflow-hidden p-0 flex flex-col">
          <SheetHeader className="px-5 py-4 border-b bg-gradient-to-r from-primary/5 to-transparent">
            <div className="flex items-center justify-between">
              <SheetTitle className="flex items-center gap-2.5">
                <span className="flex h-9 w-9 items-center justify-center rounded-full bg-gradient-to-br from-primary to-primary/80 text-primary-foreground shadow-sm">
                  <Bot className="h-5 w-5" />
                </span>
                <div className="flex flex-col">
                  <span className="text-base font-semibold leading-tight">{t("widget.title")}</span>
                  <span className="flex items-center gap-1 text-xs text-muted-foreground">
                    <span className="inline-block h-1.5 w-1.5 rounded-full bg-emerald-500" />
                    {t("widget.online")}
                  </span>
                </div>
              </SheetTitle>
              <div className="flex items-center gap-1">
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="h-8 w-8 p-0 text-muted-foreground"
                  onClick={() => {
                    try {
                      localStorage.removeItem("ai-chat-history")
                    } catch {
                      // ignore
                    }
                    setChatKey((k) => k + 1)
                  }}
                  aria-label={t("widget.newChat")}
                  title={t("widget.newChat")}
                >
                  <Sparkles className="h-4 w-4" />
                </Button>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="h-8 w-8 p-0 text-muted-foreground"
                  onClick={resetPosition}
                  aria-label={t("widget.resetPosition")}
                  title={t("widget.resetPosition")}
                >
                  <RotateCcw className="h-4 w-4" />
                </Button>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="h-8 w-8 p-0 text-muted-foreground"
                  onClick={() => setOpen(false)}
                  aria-label={t("widget.close")}
                  title={t("widget.close")}
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </SheetHeader>
          <div className="flex-1 overflow-y-auto">
            <AiChatPanel
              key={chatKey}
              systemPrompt={contextConfig.systemPrompt}
              contextMessage={contextConfig.contextMessage}
              suggestedPrompts={contextConfig.suggestedPrompts}
              maxMessages={30}
              variant="widget"
            />
          </div>
        </SheetContent>
      </Sheet>
    </>
  )
}

const BALL_SIZE = 56

/**
 * 根据路由推断 AI 上下文
 */
function inferContextFromPath(
  pathname: string,
  t: ReturnType<typeof useTranslations>
): AiContextConfig {
  // 教师批改
  if (pathname.includes("/teacher/homework/submissions")) {
    return {
      systemPrompt:
        "You are an AI grading assistant for teachers. Help with evaluating student submissions, providing feedback suggestions, and identifying common mistakes. Be concise and constructive.",
      contextMessage: t("chat.contextMessage.teacherGrading"),
      suggestedPrompts: [
        t("chat.suggestedPrompts.teacher.0"),
        t("chat.suggestedPrompts.context.teacherGrading.0"),
        t("chat.suggestedPrompts.context.teacherGrading.1"),
      ],
    }
  }

  // 教师备课
  if (pathname.includes("/teacher/lesson-plans")) {
    return {
      systemPrompt:
        "You are an AI lesson planning assistant. Help teachers design lessons, create activities, generate discussion questions, and align with curriculum standards.",
      contextMessage: t("chat.contextMessage.teacherLesson"),
      suggestedPrompts: [
        t("chat.suggestedPrompts.teacher.1"),
        t("chat.suggestedPrompts.context.teacherLesson.0"),
        t("chat.suggestedPrompts.context.teacherLesson.1"),
      ],
    }
  }

  // 教师试卷
  if (pathname.includes("/teacher/exams")) {
    return {
      systemPrompt:
        "You are an AI exam design assistant. Help create questions, generate variants, analyze difficulty distribution, and ensure knowledge point coverage.",
      contextMessage: t("chat.contextMessage.teacherExam"),
      suggestedPrompts: [
        t("chat.suggestedPrompts.teacher.2"),
        t("chat.suggestedPrompts.context.teacherExam.0"),
        t("chat.suggestedPrompts.context.teacherExam.1"),
      ],
    }
  }

  // 学生错题本
  if (pathname.includes("/student/error-book")) {
    return {
      systemPrompt:
        "You are a Socratic tutor for K12 students. Guide the student to find answers themselves. Do NOT give direct answers. Use questions and hints to help them understand their mistakes.",
      contextMessage: t("chat.contextMessage.studentErrorBook"),
      suggestedPrompts: [
        t("chat.suggestedPrompts.student.0"),
        t("chat.suggestedPrompts.student.1"),
        t("chat.suggestedPrompts.student.2"),
      ],
    }
  }

  // 学生作业
  if (pathname.includes("/student/homework") || pathname.includes("/student/learning")) {
    return {
      systemPrompt:
        "You are a homework helper for K12 students. Use the Socratic method. Do NOT give direct answers. Guide the student through hints and questions.",
      contextMessage: t("chat.contextMessage.studentHomework"),
      suggestedPrompts: [
        t("chat.suggestedPrompts.student.0"),
        t("chat.suggestedPrompts.context.studentHomework.0"),
        t("chat.suggestedPrompts.context.studentHomework.1"),
      ],
    }
  }

  // 家长面板
  if (pathname.includes("/parent")) {
    return {
      systemPrompt:
        "You are a family education advisor. Help parents understand their child's learning progress, suggest home tutoring strategies, and provide educational guidance.",
      contextMessage: t("chat.contextMessage.parent"),
      suggestedPrompts: [
        t("chat.suggestedPrompts.parent.0"),
        t("chat.suggestedPrompts.parent.1"),
      ],
    }
  }

  // 管理员面板
  if (pathname.includes("/admin")) {
    return {
      systemPrompt:
        "You are an AI education administration assistant. Help administrators monitor AI usage, analyze school-wide trends, and optimize resource allocation.",
      contextMessage: t("chat.contextMessage.admin"),
      suggestedPrompts: [
        t("chat.suggestedPrompts.admin.0"),
        t("chat.suggestedPrompts.admin.1"),
      ],
    }
  }

  // 默认
  return {
    systemPrompt: "You are a helpful AI assistant for a K12 school management system.",
    contextMessage: "",
    suggestedPrompts: undefined,
  }
}
