"use client";

import { useCallback, useEffect, useRef, useState } from "react";

import type { CalendarMode } from "@/lib/fortune";
import { getApiBaseUrl } from "@/lib/api";
import { postTuViChatSessionCreate, postTuViChatSessionMessage } from "@/lib/tuvi-ai-chat";
import type { TuViChatTranscriptTurnV1 } from "@/lib/tuvi-chart-records-api";

const EXAMPLES = [
  "Năm nay nên tập trung tiền bạc hay sự nghiệp?",
  "Vì sao cung Tài Bạch của tôi có rủi ro?",
  "Tình duyên cần lưu ý điều gì?",
];

export type TuViFollowUpChatTurn = TuViChatTranscriptTurnV1;

type Props = {
  /** Đổi khi mở lá khác — reset phiên chat. */
  chartIdentityKey: string;
  /** `result` từ payload đã lưu (sau POST /fortune/tu-vi). */
  chartSnapshot: Record<string, unknown> | null | undefined;
  calendarMode: CalendarMode;
  viewingYearSolar: number;
  /** Khôi phục hội thoại từ bản ghi đã lưu (một lần khi mở). */
  restoredAiChatMessages?: TuViChatTranscriptTurnV1[] | null;
  /** Gọi khi transcript thay đổi — để nút «Lưu lá số» gửi kèm AI chat. */
  onTranscriptChange?: (messages: TuViChatTranscriptTurnV1[]) => void;
};

function normalizeRestored(msgs: TuViChatTranscriptTurnV1[] | null | undefined): TuViChatTranscriptTurnV1[] {
  if (!msgs?.length) return [];
  const now = new Date().toISOString();
  return msgs
    .filter((m) => m && (m.role === "user" || m.role === "assistant") && typeof m.content === "string")
    .map((m) => ({
      role: m.role,
      content: m.content.replace(/\s+/g, " ").trim(),
      createdAt: typeof m.createdAt === "string" ? m.createdAt : now,
    }))
    .filter((m) => m.content.length > 0);
}

export function TuViInterpretFollowUpChat({
  chartIdentityKey,
  chartSnapshot,
  calendarMode,
  viewingYearSolar,
  restoredAiChatMessages,
  onTranscriptChange,
}: Props) {
  const [question, setQuestion] = useState("");
  const [messages, setMessages] = useState<TuViChatTranscriptTurnV1[]>(() => normalizeRestored(restoredAiChatMessages));
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [sessionCreating, setSessionCreating] = useState(false);
  const [sessionError, setSessionError] = useState<string | null>(null);
  const [sendLoading, setSendLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const historyEndRef = useRef<HTMLDivElement>(null);
  const chartSnapshotRef = useRef(chartSnapshot);
  chartSnapshotRef.current = chartSnapshot;

  const canAsk = Boolean(chartSnapshot && typeof chartSnapshot === "object");
  const apiConfigured = Boolean(getApiBaseUrl());

  const restoredFingerprint = JSON.stringify(normalizeRestored(restoredAiChatMessages));

  useEffect(() => {
    if (onTranscriptChange) onTranscriptChange(messages);
  }, [messages, onTranscriptChange]);

  useEffect(() => {
    if (!canAsk || !apiConfigured) {
      setSessionId(null);
      setSessionError(null);
      return;
    }

    const snap = chartSnapshotRef.current;
    if (!snap || typeof snap !== "object") {
      setSessionId(null);
      setSessionError(null);
      return;
    }

    let cancelled = false;
    const seed = normalizeRestored(restoredAiChatMessages);
    setMessages(seed);

    setSessionCreating(true);
    setSessionError(null);
    setSessionId(null);

    void (async () => {
      try {
        const r = await postTuViChatSessionCreate({
          chartSnapshot: snap as Record<string, unknown>,
          calendarMode,
          viewingYearSolar,
          restoredMessages:
            seed.length > 0 ?
              seed.map((m) => ({ role: m.role, content: m.content, createdAt: m.createdAt }))
            : undefined,
        });
        if (!cancelled) setSessionId(r.sessionId);
      } catch (e) {
        if (!cancelled) {
          setSessionError(e instanceof Error ? e.message : String(e));
          setSessionId(null);
        }
      } finally {
        if (!cancelled) setSessionCreating(false);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [
    canAsk,
    apiConfigured,
    calendarMode,
    viewingYearSolar,
    chartIdentityKey,
    restoredFingerprint,
  ]);

  useEffect(() => {
    historyEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, sendLoading]);

  const send = useCallback(async () => {
    const q = question.replace(/\s+/g, " ").trim();
    if (!q || !sessionId) return;
    const ts = new Date().toISOString();
    setSendLoading(true);
    setError(null);
    setQuestion("");
    setMessages((prev) => [...prev, { role: "user", content: q, createdAt: ts }]);
    try {
      const r = await postTuViChatSessionMessage({ sessionId, question: q });
      const ta = new Date().toISOString();
      setMessages((prev) => [...prev, { role: "assistant", content: r.answer, createdAt: ta }]);
    } catch (e) {
      setMessages((prev) => prev.slice(0, -1));
      setQuestion(q);
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setSendLoading(false);
    }
  }, [sessionId, question]);

  if (!canAsk) {
    return (
      <section
        className="mx-auto mt-8 max-w-3xl rounded-xl border border-[#d4af37]/14 bg-[#060912]/55 px-4 py-4 sm:px-5"
        aria-label="Hỏi đáp sau luận"
      >
        <p className="font-sans text-[13px] leading-relaxed text-slate-500">
          Chưa có dữ liệu luận giải từ engine để hỏi tiếp.
        </p>
      </section>
    );
  }

  const sessionBlocked = Boolean(sessionError) || (!sessionCreating && !sessionId);

  return (
    <section
      className="mx-auto mt-8 max-w-3xl rounded-xl border border-[#d4af37]/14 bg-[linear-gradient(165deg,rgba(14,18,32,0.92),rgba(5,7,14,0.96))] px-4 py-5 shadow-[inset_0_1px_0_rgba(212,175,55,0.08)] sm:px-6 sm:py-6"
      aria-label="Hỏi đáp sau luận — lớp AI giải thích"
    >
      <p className="font-ctkp-serif text-[10px] uppercase tracking-[0.28em] text-[#d4af37]/72">Hỏi thêm</p>
      <h3 className="ctkp-tuvi-text-title-soft mt-1 font-ctkp-serif text-lg tracking-[0.04em] text-[#f0e6bc]">
        Giải thích từ luận đã có
      </h3>
      <p className="mt-2 font-sans text-[12px] leading-relaxed text-slate-500">
        Lớp AI chỉ diễn giải nội dung deterministic đã tải — không tính lại lá, không đổi an sao. Phiên hội thoại giữ ngữ cảnh
        lá và các lượt hỏi–đáp trước (trên máy chủ).
      </p>

      {!apiConfigured ?
        <p className="mt-4 rounded-lg border border-amber-800/35 bg-amber-950/20 px-3 py-2 font-sans text-[12px] text-amber-100/88">
          Chưa kết nối dịch vụ chat — kiểm tra cấu hình triển khai của ứng dụng.
        </p>
      : null}

      {sessionCreating ?
        <p className="mt-4 font-sans text-[12px] text-slate-400">Đang mở phiên hỏi đáp…</p>
      : null}

      {sessionError ?
        <p className="mt-4 rounded-lg border border-red-900/40 bg-red-950/25 px-3 py-2 font-sans text-[12px] text-red-100/90">
          {sessionError}
        </p>
      : null}

      {!sessionCreating && sessionBlocked && !sessionError && apiConfigured ?
        <p className="mt-4 font-sans text-[12px] text-slate-500">
          Chưa tạo được phiên hỏi đáp cho lá số này.
        </p>
      : null}

      {messages.length > 0 ?
        <div
          className="mt-5 max-h-[min(420px,50vh)] space-y-3 overflow-y-auto rounded-lg border border-[#d4af37]/10 bg-black/20 px-3 py-3 sm:px-4"
          aria-label="Lịch sử hỏi đáp"
        >
          {messages.map((m, i) => (
            <div
              key={`${i}-${m.role}-${m.createdAt}-${m.content.slice(0, 24)}`}
              className={
                m.role === "user" ?
                  "rounded-lg border border-slate-700/40 bg-slate-900/35 px-3 py-2"
                : "rounded-lg border border-[#d4af37]/15 bg-[#0c101f]/80 px-3 py-2"
              }
            >
              <p className="font-ctkp-serif text-[9px] uppercase tracking-[0.2em] text-[#d4af37]/55">
                {m.role === "user" ? "Bạn" : "Trợ lý"}
              </p>
              <p className="mt-1 whitespace-pre-wrap font-sans text-[13px] leading-relaxed text-slate-200">{m.content}</p>
            </div>
          ))}
          {sendLoading ?
            <p className="font-sans text-[12px] italic text-slate-500">Đang trả lời…</p>
          : null}
          <div ref={historyEndRef} />
        </div>
      : null}

      <div className="mt-4 flex flex-col gap-2 sm:flex-row sm:items-end">
        <label className="min-w-0 flex-1 font-sans text-[11px] text-slate-500">
          <span className="sr-only">Câu hỏi</span>
          <textarea
            value={question}
            onChange={(e) => setQuestion(e.target.value)}
            placeholder="Nhập câu hỏi muốn hỏi sâu về lá số…"
            rows={3}
            disabled={sendLoading || !apiConfigured || sessionBlocked}
            className="mt-1 w-full resize-y rounded-lg border border-[#d4af37]/18 bg-black/30 px-3 py-2.5 font-sans text-[13px] leading-relaxed text-slate-200 placeholder:text-slate-600 focus:border-[#d4af37]/40 focus:outline-none focus:ring-1 focus:ring-[#d4af37]/25 disabled:opacity-50"
          />
        </label>
        <button
          type="button"
          onClick={() => void send()}
          disabled={sendLoading || !apiConfigured || sessionBlocked || question.trim().length < 2}
          className="shrink-0 rounded-lg border border-[#d4af37]/38 bg-[#d4af37]/14 px-4 py-2.5 font-ctkp-serif text-[11px] uppercase tracking-[0.14em] text-[#f5ebd6] transition-colors hover:bg-[#d4af37]/22 disabled:cursor-not-allowed disabled:opacity-45"
        >
          {sendLoading ? "Đang gửi…" : "Gửi câu hỏi"}
        </button>
      </div>

      <p className="mt-3 font-sans text-[11px] leading-relaxed text-slate-600">
        Ví dụ: {EXAMPLES.join(" · ")}
      </p>

      {error ?
        <p className="mt-4 rounded-lg border border-red-900/40 bg-red-950/25 px-3 py-2 font-sans text-[12px] text-red-100/90">
          {error}
        </p>
      : null}
    </section>
  );
}
