//
"use client";

import React, {
  type ReactNode,
  useState,
  useCallback,
  useMemo,
  useEffect,
  startTransition,
  useTransition,
} from "react";
import { Brain, Zap } from "lucide-react";
import { NLP } from "sortug-ai";
import GranularityMenu, { GranularityId } from "./LevelPicker";
import TextViewer from "./TextViewer";
import { wordAction } from "@/actions/lang";
import Modal from "@/components/Modal";
import { Spinner } from "@/components/ui/spinner";

// --- Granularity Definition ---
type AnalysisEngine = "spacy" | "stanza";

// --- Main Application Component ---
export default function NlpTextAnalysisScreen({
  children,
}: {
  children: ReactNode;
}) {
  const [modalContent, setModalContent] = useState<ReactNode | null>(null);

  const closeModal = () => setModalContent(null);

  const [selectedGranularity, setSelectedGranularity] =
    useState<GranularityId>("word");
  const [currentEngine, setCurrentEngine] = useState<AnalysisEngine>("spacy");
  const [selectedElementInfo, setSelectedElementInfo] = useState<string | null>(
    null,
  );
  const [activeNlpData, setData] = useState<NLP.Spacy.SpacyRes>();
  useEffect(() => {
    const nlpdata = sessionStorage.getItem(
      currentEngine === "spacy" ? "spacyres" : "stanzares",
    );
    const parsed = JSON.parse(nlpdata!);
    setData(parsed);
  }, []);

  const handleGranularityChange = useCallback((granularity: GranularityId) => {
    setSelectedGranularity(granularity);
    setSelectedElementInfo(null);
  }, []);
  const [isPending, startTransition] = useTransition();
  const handleElementSelect = useCallback(
    (elementType: GranularityId, elementData: any, elementText: string) => {
      if (elementType === "word") {
        startTransition(async () => {
          const modal = await wordAction(elementData.lemma, "en");
          setModalContent(modal);
        });
      }
    },
    [currentEngine],
  );
  // const handleElementSelect = useCallback(
  //   (elementType: GranularityId, elementData: any, elementText: string) => {
  //     let info = `Selected: ${elementType.toUpperCase()} (${currentEngine})\n`;
  //     info += `Text: "${elementText}"\n`;

  //     if (elementType === "syllable" || elementType === "phoneme") {
  //       info += `(Granularity: ${elementType}, showing parent Word/Token details)\n`;
  //     }

  //     // Add specific details based on element type and engine
  //     if (elementType === "word") {
  //       if (currentEngine === "stanza" && elementData.lemma) {
  //         // StanzaWord
  //         info += `Lemma: ${elementData.lemma}\nUPOS: ${elementData.upos}\nXPOS: ${elementData.xpos}\nDepRel: ${elementData.deprel} (Head ID: ${elementData.head})\n`;
  //         if (elementData.parentToken?.ner)
  //           info += `NER (Token): ${elementData.parentToken.ner}\n`;
  //       } else if (currentEngine === "spacy" && elementData.lemma_) {
  //         // SpacyToken
  //         info += `Lemma: ${elementData.lemma_}\nPOS: ${elementData.pos_}\nTag: ${elementData.tag_}\nDep: ${elementData.dep_} (Head ID: ${elementData.head?.i})\n`;
  //         if (elementData.ent_type_)
  //           info += `Entity: ${elementData.ent_type_} (${elementData.ent_iob_})\n`;
  //       }
  //     } else if (elementType === "sentence") {
  //       if (
  //         currentEngine === "stanza" &&
  //         (elementData as NLP.Stanza.Sentence).sentiment
  //       ) {
  //         info += `Sentiment: ${(elementData as NLP.Stanza.Sentence).sentiment}\n`;
  //       }
  //       if (
  //         (elementData as NLP.Stanza.Sentence | NLP.Spacy.Sentence).entities
  //           ?.length
  //       ) {
  //         info += `Entities in sentence: ${(elementData.entities as any[]).map((e) => `${e.text} (${e.type || e.label_})`).join(", ")}\n`;
  //       }
  //     } else if (elementType === "paragraph") {
  //       info += `Char range: ${elementData.start_char}-${elementData.end_char}\n`;
  //       info += `Sentence count: ${elementData.sentences.length}\n`;
  //     }

  //     info += `Raw Data Keys: ${Object.keys(elementData).slice(0, 5).join(", ")}...`; // Show some keys
  //     setSelectedElementInfo(info);
  //     console.log(
  //       "Selected Element:",
  //       elementType,
  //       elementData,
  //       "Text:",
  //       elementText,
  //     );
  //   },
  //   [currentEngine],
  // );

  const toggleEngine = () => {
    setCurrentEngine((prev) => (prev === "spacy" ? "stanza" : "spacy"));
    setSelectedElementInfo(null);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-100 to-sky-100 p-4 sm:p-8 font-sans">
      <header className="mb-6 text-center">
        <h1 className="text-3xl sm:text-4xl font-bold text-slate-800">
          NLP Text Analyzer
        </h1>
        <button
          onClick={toggleEngine}
          className="mt-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg shadow-md transition-colors flex items-center mx-auto"
        >
          {currentEngine === "spacy" ? (
            <Zap size={18} className="mr-2" />
          ) : (
            <Brain size={18} className="mr-2" />
          )}
          Switch to {currentEngine === "spacy" ? "Stanza" : "spaCy"} View
        </button>
        <p className="text-sm text-slate-600 mt-1">
          Currently viewing with:{" "}
          <span className="font-semibold">{currentEngine.toUpperCase()}</span>
        </p>
      </header>

      <div className="flex flex-col lg:flex-row gap-6 max-w-7xl mx-auto">
        <aside className="lg:w-72 lg:sticky lg:top-8 h-full flex flex-col gap-6">
          <GranularityMenu
            selectedGranularity={selectedGranularity}
            onSelectGranularity={handleGranularityChange}
          />
          {selectedElementInfo && (
            <div className="p-4 bg-white rounded-lg shadow-md text-xs text-slate-700 overflow-auto max-h-96">
              <h3 className="font-semibold text-sky-600 mb-2 text-sm">
                Selection Details:
              </h3>
              <pre className="whitespace-pre-wrap break-all">
                {selectedElementInfo}
              </pre>
            </div>
          )}
        </aside>

        <main className="flex-1 min-w-0">
          {" "}
          {/* min-w-0 for flex child to prevent overflow */}
          {activeNlpData ? (
            <TextViewer
              nlpData={activeNlpData}
              engine={currentEngine}
              granularity={selectedGranularity}
              onElementSelect={handleElementSelect}
            />
          ) : (
            <Spinner />
          )}
        </main>
      </div>

      <footer className="text-center mt-12 text-sm text-slate-500">
        <p>
          &copy; {new Date().getFullYear()} NLP Analysis Tool. Powered by React,
          TailwindCSS, and your NLP engine of choice!
        </p>
      </footer>
      {modalContent && (
        <Modal onClose={closeModal} isOpen={!!modalContent}>
          {modalContent}
        </Modal>
      )}
    </div>
  );
}
