"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { X, Sparkles, Loader2, AlertCircle, Lightbulb, CheckCircle2, Target, Users } from "lucide-react";
import { FocusTrap } from "@/shared/components/a11y/focus-trap";
import { Button } from "@/shared/components/ui/button";
import { generateLessonPlanFeedbackAction } from "../actions-ai";
import type { AiFeedbackResult, AiFeedbackItem } from "../lib/ai-feedback";
import type { LessonPlanDocument } from "../types";

interface Props {
  doc: LessonPlanDocument;
  onClose: () => void;
}

/** V5-17 A1/A2：AI 反馈闭环对话框（含解释性展示） */
export function AiFeedbackDialog({ doc, onClose }: Props) {
  const t = useTranslations("lessonPreparation");
  const [loading, setLoading] = useState(true);
  const [result, setResult] = useState<AiFeedbackResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await generateLessonPlanFeedbackAction(doc);
        if (cancelled) return;
        if (res.success && res.data) {
          setResult(res.data);
        } else {
          setError(res.message ?? t("feedback.loadFailed"));
        }
      } catch {
        if (!cancelled) setError(t("feedback.loadFailed"));
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [doc, t]);

  // ESC 关闭
  useEffect(() => {
    function handleEsc(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    document.addEventListener("keydown", handleEsc);
    return () => document.removeEventListener("keydown", handleEsc);
  }, [onClose]);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
      <div
        role="dialog"
        aria-modal="true"
        aria-label={t("feedback.title")}
        className="bg-surface rounded-lg shadow-xl w-[600px] max-h-[85vh] flex flex-col"
      >
        <FocusTrap className="contents">
          <div className="flex justify-between items-center p-4 border-b border-outline-variant">
            <h3 className="font-title-md flex items-center gap-2">
              <Sparkles className="w-4 h-4 text-primary" aria-hidden="true" />
              {t("feedback.title")}
            </h3>
            <button onClick={onClose} aria-label={t("editor.consistencyClose")}>
              <X className="w-4 h-4" aria-hidden="true" />
            </button>
          </div>

          <div className="p-4 overflow-y-auto flex-1">
            {loading ? (
              <div className="flex flex-col items-center justify-center py-12 gap-2">
                <Loader2 className="w-6 h-6 animate-spin text-primary" aria-hidden="true" />
                <p className="text-sm text-on-surface-variant">{t("feedback.loading")}</p>
              </div>
            ) : error ? (
              <div className="flex items-center gap-2 p-3 rounded border border-error/40 bg-error-container/30 text-sm">
                <AlertCircle className="w-4 h-4 text-error" aria-hidden="true" />
                {error}
              </div>
            ) : result ? (
              <FeedbackContent result={result} t={t} />
            ) : null}
          </div>

          <div className="p-3 border-t border-outline-variant flex justify-end">
            <Button variant="outline" size="sm" onClick={onClose}>
              {t("editor.consistencyClose")}
            </Button>
          </div>
        </FocusTrap>
      </div>
    </div>
  );
}

function FeedbackContent({
  result,
  t,
}: {
  result: AiFeedbackResult;
  t: ReturnType<typeof useTranslations>;
}) {
  // 按维度分组
  const grouped: Record<AiFeedbackItem["category"], AiFeedbackItem[]> = {
    strengths: [],
    improvements: [],
    alignment: [],
    differentiation: [],
  };
  for (const item of result.items) {
    grouped[item.category].push(item);
  }

  return (
    <div className="space-y-4">
      {/* 摘要 + 评分 */}
      <div className="flex items-center justify-between rounded border border-outline-variant p-3 bg-surface-container-low">
        <div className="flex-1">
          <p className="text-sm font-medium">{t("feedback.summary")}</p>
          <p className="text-xs text-on-surface-variant mt-1">{result.summary}</p>
        </div>
        <div className="text-right ml-3">
          <div className="text-2xl font-bold text-primary">{result.overallScore}</div>
          <div className="text-xs text-on-surface-variant">{t("feedback.score")}</div>
        </div>
      </div>

      {/* 各维度反馈 */}
      {(Object.keys(grouped) as AiFeedbackItem["category"][]).map((cat) => {
        const items = grouped[cat];
        if (items.length === 0) return null;
        return (
          <section key={cat}>
            <h4 className="text-sm font-medium flex items-center gap-1.5 mb-2">
              <CategoryIcon category={cat} />
              {t(`feedback.category.${cat}`)}
              <span className="text-xs text-on-surface-variant">({items.length})</span>
            </h4>
            <ul className="space-y-2">
              {items.map((item, idx) => (
                <li
                  key={idx}
                  className="rounded border border-outline-variant p-2.5 bg-surface"
                >
                  <div className="text-sm font-medium">{item.title}</div>
                  {/* A2：解释性展示 — reason 字段说明 AI 判断依据 */}
                  {item.reason && (
                    <div className="text-xs text-on-surface-variant mt-1 flex items-start gap-1">
                      <Lightbulb className="w-3 h-3 mt-0.5 flex-shrink-0" aria-hidden="true" />
                      <span>{item.reason}</span>
                    </div>
                  )}
                </li>
              ))}
            </ul>
          </section>
        );
      })}

      {result.items.length === 0 && (
        <div className="text-sm text-on-surface-variant text-center py-6">
          {t("feedback.empty")}
        </div>
      )}
    </div>
  );
}

function CategoryIcon({ category }: { category: AiFeedbackItem["category"] }) {
  const icon = {
    strengths: <CheckCircle2 className="w-3.5 h-3.5 text-primary" aria-hidden="true" />,
    improvements: <AlertCircle className="w-3.5 h-3.5 text-tertiary" aria-hidden="true" />,
    alignment: <Target className="w-3.5 h-3.5 text-secondary" aria-hidden="true" />,
    differentiation: <Users className="w-3.5 h-3.5 text-primary" aria-hidden="true" />,
  }[category];
  return icon;
}
