"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
import { Sparkles, TrendingUp, Lightbulb, CheckCircle, AlertCircle } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { AiErrorBoundary } from "@/modules/ai/components/ai-error-boundary"
import { AiSuggestionSkeleton } from "@/modules/ai/components/ai-skeleton"
import { AiMarkdownRenderer } from "@/modules/ai/components/ai-markdown-renderer"
import { useAiClient } from "@/modules/ai/context/ai-client-provider"
import type { ChildSummaryResult, ChildSummaryInput } from "@/modules/ai/types"

type AiChildSummaryProps = {
  studentId: string
  studentName?: string
  grade?: string
  recentGrades?: ChildSummaryInput["recentGrades"]
  attendanceRate?: number
  homeworkCompletionRate?: number
}

/**
 * 家长 AI 学情摘要组件
 *
 * 参考 Squirrel AI 24/7 家长面板和 Khanmigo 家长可见性。
 * 为家长生成子女学情的 AI 摘要，包括：
 * - 整体评估
 * - 优势领域
 * - 需改进领域
 * - 家庭辅导建议
 * - 下一步行动
 */
export function AiChildSummary({
  studentId,
  studentName,
  grade,
  recentGrades,
  attendanceRate,
  homeworkCompletionRate,
}: AiChildSummaryProps): React.ReactNode {
  const t = useTranslations("ai")
  const aiClient = useAiClient()
  const [loading, setLoading] = useState(false)
  const [summary, setSummary] = useState<ChildSummaryResult | null>(null)

  const handleGenerate = async (): Promise<void> => {
    if (!aiClient.generateChildSummary) {
      toast.error(t("parent.error"))
      return
    }
    setLoading(true)
    try {
      const result = await aiClient.generateChildSummary({
        studentId,
        studentName,
        grade,
        recentGrades,
        attendanceRate,
        homeworkCompletionRate,
      })
      if (result.success && result.data) {
        setSummary(result.data)
        toast.success(t("parent.summary"))
      } else {
        toast.error(result.message ?? t("parent.error"))
      }
    } catch {
      toast.error(t("parent.error"))
    } finally {
      setLoading(false)
    }
  }

  return (
    <AiErrorBoundary>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Sparkles className="h-4 w-4 text-primary" />
            {t("parent.summary")}
          </CardTitle>
          <CardDescription>{t("parent.summaryDescription")}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {loading ? (
            <AiSuggestionSkeleton />
          ) : summary ? (
            <div className="space-y-4">
              {/* 整体评估 */}
              <div className="space-y-1">
                <h4 className="text-sm font-medium">{t("parent.summary")}</h4>
                <div className="text-sm text-muted-foreground rounded-md bg-muted p-3">
                  <AiMarkdownRenderer content={summary.overallAssessment} showCopyButton={false} />
                </div>
              </div>

              {/* 优势领域 */}
              {summary.strengths.length > 0 ? (
                <div className="space-y-1">
                  <h4 className="text-sm font-medium flex items-center gap-1">
                    <CheckCircle className="h-3.5 w-3.5 text-green-500" />
                    {t("parent.summary")}
                  </h4>
                  <ul className="space-y-1">
                    {summary.strengths.map((item, index) => (
                      <li key={index} className="text-sm text-muted-foreground flex items-start gap-2">
                        <span className="text-green-500 mt-0.5">•</span>
                        {item}
                      </li>
                    ))}
                  </ul>
                </div>
              ) : null}

              {/* 需改进领域 */}
              {summary.areasForImprovement.length > 0 ? (
                <div className="space-y-1">
                  <h4 className="text-sm font-medium flex items-center gap-1">
                    <AlertCircle className="h-3.5 w-3.5 text-orange-500" />
                    {t("parent.weaknessHint")}
                  </h4>
                  <ul className="space-y-1">
                    {summary.areasForImprovement.map((item, index) => (
                      <li key={index} className="text-sm text-muted-foreground flex items-start gap-2">
                        <span className="text-orange-500 mt-0.5">•</span>
                        {item}
                      </li>
                    ))}
                  </ul>
                </div>
              ) : null}

              {/* 家庭辅导建议 */}
              {summary.familyTutoringSuggestions.length > 0 ? (
                <div className="space-y-1">
                  <h4 className="text-sm font-medium flex items-center gap-1">
                    <Lightbulb className="h-3.5 w-3.5 text-primary" />
                    {t("parent.suggestion")}
                  </h4>
                  <ul className="space-y-1">
                    {summary.familyTutoringSuggestions.map((item, index) => (
                      <li key={index} className="text-sm text-muted-foreground flex items-start gap-2">
                        <span className="text-primary mt-0.5">•</span>
                        {item}
                      </li>
                    ))}
                  </ul>
                </div>
              ) : null}

              {/* 下一步行动 */}
              {summary.nextSteps.length > 0 ? (
                <div className="space-y-1">
                  <h4 className="text-sm font-medium flex items-center gap-1">
                    <TrendingUp className="h-3.5 w-3.5 text-primary" />
                    {t("studyPath.nextSteps")}
                  </h4>
                  <div className="flex flex-wrap gap-2">
                    {summary.nextSteps.map((item, index) => (
                      <Badge key={index} variant="outline" className="text-xs">
                        {item}
                      </Badge>
                    ))}
                  </div>
                </div>
              ) : null}

              <Button type="button" variant="outline" size="sm" onClick={handleGenerate} className="w-full">
                {t("suggestion.regenerate")}
              </Button>
            </div>
          ) : (
            <Button type="button" variant="outline" size="sm" onClick={handleGenerate} className="w-full">
              <Sparkles className="mr-1 h-3.5 w-3.5" />
              {t("parent.generateSummary")}
            </Button>
          )}
        </CardContent>
      </Card>
    </AiErrorBoundary>
  )
}
