"use client"

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

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

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

/**
 * 全局 AI 助手悬浮按钮
 *
 * 参考 Khanmigo 嵌入式助手模式：
 * - 右下角悬浮按钮，任何页面可见
 * - 点击打开侧边抽屉，内嵌 AiChatPanel
 * - 上下文感知：根据当前路由自动推断用户场景
 * - 流式响应 + Markdown 渲染
 *
 * 使用：
 * 在 dashboard layout 中引入即可全局生效。
 * 需要 AiClientProvider 包裹（可选，未注入时按钮不显示）。
 */
export function AiAssistantWidget(): React.ReactNode {
  const t = useTranslations("ai")
  const pathname = usePathname()
  const aiClient = useAiClientOptional()
  const [open, setOpen] = useState(false)

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

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

  return (
    <Sheet open={open} onOpenChange={setOpen}>
      <SheetTrigger asChild>
        <Button
          type="button"
          size="icon"
          className="fixed bottom-6 right-6 z-50 h-14 w-14 rounded-full shadow-lg hover:shadow-xl transition-shadow"
          aria-label={t("widget.open")}
        >
          <Bot className="h-6 w-6" />
          <span className="absolute -top-1 -right-1 flex h-3 w-3">
            <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75" />
            <span className="relative inline-flex rounded-full h-3 w-3 bg-green-500" />
          </span>
        </Button>
      </SheetTrigger>
      <SheetContent className="w-full sm:max-w-md overflow-y-auto p-0">
        <SheetHeader className="px-4 py-3 border-b">
          <div className="flex items-center justify-between">
            <SheetTitle className="flex items-center gap-2">
              <Bot className="h-4 w-4 text-primary" />
              {t("widget.title")}
            </SheetTitle>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              className="h-7 px-2"
              onClick={() => setOpen(false)}
              aria-label={t("widget.close")}
            >
              <X className="h-4 w-4" />
            </Button>
          </div>
          <p className="text-xs text-muted-foreground">{t("widget.contextAware")}</p>
        </SheetHeader>
        <div className="p-4">
          <AiChatPanel
            systemPrompt={contextConfig.systemPrompt}
            contextMessage={contextConfig.contextMessage}
            suggestedPrompts={contextConfig.suggestedPrompts}
            maxMessages={30}
          />
        </div>
      </SheetContent>
    </Sheet>
  )
}

/**
 * 根据路由推断 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: "Current page: Homework grading view",
      suggestedPrompts: [
        t("chat.suggestedPrompts.teacher.0"),
        "What are common mistakes in this type of question?",
        "How should I give constructive feedback?",
      ],
    }
  }

  // 教师备课
  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: "Current page: Lesson plan editor",
      suggestedPrompts: [
        t("chat.suggestedPrompts.teacher.1"),
        "Suggest a hook for this lesson",
        "What are some differentiation strategies?",
      ],
    }
  }

  // 教师试卷
  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: "Current page: Exam builder",
      suggestedPrompts: [
        t("chat.suggestedPrompts.teacher.2"),
        "Generate a question on this topic",
        "Analyze the difficulty distribution",
      ],
    }
  }

  // 学生错题本
  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: "Current page: Error book (student view)",
      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: "Current page: Student homework view",
      suggestedPrompts: [
        t("chat.suggestedPrompts.student.0"),
        "Give me a hint, not the answer",
        "Help me understand this concept",
      ],
    }
  }

  // 家长面板
  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: "Current page: Parent dashboard",
      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: "Current page: Admin dashboard",
      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,
  }
}
