"use client";

import React, { useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store/store";
import {
  setWizardStep,
  setJobId,
  setPresentationId as setWizardPresentationId,
  WizardOutlineItem,
  toggleSlideAttachment,
} from "@/store/slices/wizardSlice";
import { clearPresentationData } from "@/store/slices/presentationGeneration";
import { useOutlineStreaming } from "../../outline/hooks/useOutlineStreaming";
import { useOutlineManagement } from "../../outline/hooks/useOutlineManagement";
import OutlineContent from "../../outline/components/OutlineContent";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  ChevronLeft,
  ChevronRight,
  FileText,
  Layers,
  Loader2,
  Paperclip,
} from "lucide-react";
import { toast } from "sonner";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Checkbox } from "@/components/ui/checkbox";
import { OverlayLoader } from "@/components/ui/overlay-loader";
import Wrapper from "@/components/Wrapper";
import { PresentationGenerationApi } from "../../services/api/presentation-generation";
import { WizardApi } from "../../services/api/wizard";
import TemplateSelection from "../../outline/components/TemplateSelection";
import { TemplateLayoutsWithSettings } from "@/app/presentation-templates/utils";
import { getCustomTemplateDetails } from "@/app/hooks/useCustomTemplates";

export default function WizardOutlinePage() {
  const router = useRouter();
  const dispatch = useDispatch();
  const wizard = useSelector((s: RootState) => s.wizard);
  const { presentation_id, outlines } = useSelector(
    (s: RootState) => s.presentationGeneration
  );

  const [selectedTemplate, setSelectedTemplate] = useState<
    TemplateLayoutsWithSettings | string | null
  >(null);
  const [activeTab, setActiveTab] = useState("outline");
  const [isGenerating, setIsGenerating] = useState(false);

  // Reuse existing hooks
  const streamState = useOutlineStreaming(presentation_id);
  const { handleDragEnd, handleAddSlide } = useOutlineManagement(outlines);

  const handleBack = () => {
    dispatch(setWizardStep(2));
    router.push("/generate/configure");
  };

  const handleApproveAndGenerate = async () => {
    if (!outlines || outlines.length === 0) {
      toast.error("No outlines to generate from.");
      return;
    }

    if (!selectedTemplate) {
      setActiveTab("template");
      toast.error("Please select a template/layout first.");
      return;
    }

    try {
      setIsGenerating(true);

      // Build layout object (same pattern as usePresentationGeneration)
      let layout;
      if (typeof selectedTemplate === "string") {
        const customDetail = await getCustomTemplateDetails(selectedTemplate);
        if (!customDetail || customDetail.layouts.length === 0) {
          toast.error("Failed to load custom template layouts");
          return;
        }
        layout = {
          name: customDetail.id,
          ordered: false,
          slides: customDetail.layouts.map((l) => ({
            id: customDetail.id.startsWith("custom-")
              ? `${customDetail.id}:${l.layoutId}`
              : `custom-${customDetail.id}:${l.layoutId}`,
            name: l.layoutName,
            description: l.layoutDescription,
            templateID: customDetail.id,
            templateName: customDetail.name,
            json_schema: l.schemaJSON,
          })),
        };
      } else {
        layout = {
          name: selectedTemplate.id,
          ordered: false,
          slides: selectedTemplate.layouts.map((l) => ({
            id: l.layoutId,
            name: l.layoutName,
            description: l.layoutDescription,
            templateID: selectedTemplate.id,
            templateName: selectedTemplate.name,
            json_schema: l.schemaJSON,
          })),
        };
      }

      // Prepare (same as existing flow)
      const response = await PresentationGenerationApi.presentationPrepare({
        presentation_id,
        outlines,
        layout,
      });

      if (response) {
        dispatch(clearPresentationData());
        dispatch(setWizardPresentationId(presentation_id));
        dispatch(setWizardStep(4));
        router.push(
          `/presentation?id=${presentation_id}&stream=true&type=standard`
        );
      }
    } catch (error: any) {
      toast.error("Generation failed", {
        description: error.message || "Please try again.",
      });
    } finally {
      setIsGenerating(false);
    }
  };

  if (!presentation_id) {
    return (
      <Wrapper className="py-16 text-center">
        <FileText className="w-12 h-12 text-gray-300 mx-auto mb-4" />
        <p className="text-gray-500 mb-4">No presentation in progress.</p>
        <Button variant="outline" onClick={() => router.push("/generate/upload")}>
          Start Over
        </Button>
      </Wrapper>
    );
  }

  return (
    <div className="h-[calc(100vh-140px)] flex flex-col">
      <OverlayLoader
        show={isGenerating}
        text="Preparing presentation..."
        showProgress
        duration={30}
      />

      <Wrapper className="flex-1 flex flex-col overflow-hidden py-4">
        {/* Split View */}
        <div className="flex-1 flex gap-4 min-h-0">
          {/* LEFT: Source Content */}
          <div className="w-[340px] flex-shrink-0 flex flex-col border rounded-xl bg-white overflow-hidden">
            <div className="px-4 py-3 border-b bg-gray-50">
              <h3 className="text-sm font-semibold flex items-center gap-2">
                <FileText className="w-4 h-4" />
                Source Content
              </h3>
            </div>
            <div className="flex-1 overflow-y-auto p-4 text-sm">
              {/* Brief text */}
              {wizard.briefText && (
                <div className="mb-4">
                  <h4 className="text-xs font-semibold text-gray-500 uppercase mb-2">
                    Brief
                  </h4>
                  <div className="prose prose-sm max-w-none whitespace-pre-wrap text-gray-700">
                    {wizard.briefText}
                  </div>
                </div>
              )}

              {/* Uploaded files */}
              {wizard.uploadedFiles.length > 0 && (
                <div>
                  <h4 className="text-xs font-semibold text-gray-500 uppercase mb-2">
                    Uploaded Files
                  </h4>
                  <div className="space-y-2">
                    {wizard.uploadedFiles.map((f, i) => {
                      // Count how many slides this file is linked to
                      const linkedCount = Object.values(
                        wizard.slideAttachments
                      ).filter((names) => names.includes(f.name)).length;

                      return (
                        <div
                          key={i}
                          className="flex items-center gap-2 p-2 rounded-lg bg-gray-50 text-xs"
                        >
                          <FileText className="w-3.5 h-3.5 text-[#5146E5] flex-shrink-0" />
                          <span className="truncate flex-1">{f.name}</span>

                          {/* Link to slides popover */}
                          {outlines && outlines.length > 0 && (
                            <Popover>
                              <PopoverTrigger asChild>
                                <button
                                  className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium text-gray-500 hover:text-[#5146E5] hover:bg-[#5146E5]/5 transition-colors flex-shrink-0"
                                  title="Link to slides"
                                >
                                  <Paperclip className="w-3 h-3" />
                                  {linkedCount > 0 && (
                                    <span className="text-[#5146E5]">
                                      {linkedCount}
                                    </span>
                                  )}
                                </button>
                              </PopoverTrigger>
                              <PopoverContent
                                side="right"
                                align="start"
                                className="w-64 p-3"
                              >
                                <p className="text-xs font-semibold text-gray-700 mb-2">
                                  Link to slides
                                </p>
                                <div className="space-y-1.5 max-h-48 overflow-y-auto">
                                  {outlines.map((outline, slideIdx) => {
                                    const title =
                                      (outline.content || "")
                                        .split("\n")[0]
                                        ?.replace(/^#+\s*/, "")
                                        .trim() || `Slide ${slideIdx + 1}`;
                                    const isLinked = (
                                      wizard.slideAttachments[slideIdx] || []
                                    ).includes(f.name);

                                    return (
                                      <label
                                        key={slideIdx}
                                        className="flex items-center gap-2 p-1.5 rounded hover:bg-gray-50 cursor-pointer text-xs"
                                      >
                                        <Checkbox
                                          checked={isLinked}
                                          onCheckedChange={() =>
                                            dispatch(
                                              toggleSlideAttachment({
                                                slideIndex: slideIdx,
                                                fileName: f.name,
                                              })
                                            )
                                          }
                                          className="h-3.5 w-3.5"
                                        />
                                        <span className="text-gray-600 font-medium w-5 flex-shrink-0">
                                          {slideIdx + 1}.
                                        </span>
                                        <span className="truncate text-gray-700">
                                          {title}
                                        </span>
                                      </label>
                                    );
                                  })}
                                </div>
                              </PopoverContent>
                            </Popover>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Decomposed preview */}
              {wizard.decomposedFiles.length > 0 && (
                <div className="mt-4">
                  <h4 className="text-xs font-semibold text-gray-500 uppercase mb-2">
                    Extracted Content
                  </h4>
                  {wizard.decomposedFiles.map((doc: any, i: number) => (
                    <div key={i} className="mb-3 p-2 rounded bg-gray-50">
                      <p className="text-xs text-gray-500 mb-1">
                        {doc.file_name || `Document ${i + 1}`}
                      </p>
                      <p className="text-xs text-gray-700 line-clamp-6 whitespace-pre-wrap">
                        {typeof doc === "string"
                          ? doc
                          : doc.content || doc.text || JSON.stringify(doc).slice(0, 300)}
                      </p>
                    </div>
                  ))}
                </div>
              )}

              {!wizard.briefText && wizard.uploadedFiles.length === 0 && (
                <p className="text-gray-400 text-center mt-8">No source content</p>
              )}
            </div>
          </div>

          {/* RIGHT: Outline + Template Tabs */}
          <div className="flex-1 flex flex-col min-w-0">
            <Tabs
              value={activeTab}
              onValueChange={setActiveTab}
              className="flex-1 flex flex-col min-h-0"
            >
              <TabsList className="grid w-[50%] mx-auto grid-cols-2 mb-4">
                <TabsTrigger value="outline">Outline</TabsTrigger>
                <TabsTrigger value="template">
                  <Layers className="w-4 h-4 mr-1" />
                  Template
                </TabsTrigger>
              </TabsList>

              <div className="flex-1 overflow-y-auto">
                <TabsContent value="outline" className="h-full">
                  <OutlineContent
                    outlines={outlines}
                    isLoading={streamState.isLoading}
                    isStreaming={streamState.isStreaming}
                    activeSlideIndex={streamState.activeSlideIndex}
                    highestActiveIndex={streamState.highestActiveIndex}
                    onDragEnd={handleDragEnd}
                    onAddSlide={handleAddSlide}
                    slideAttachments={wizard.slideAttachments}
                    uploadedFiles={wizard.uploadedFiles}
                  />
                </TabsContent>

                <TabsContent value="template" className="h-full">
                  <TemplateSelection
                    selectedTemplate={selectedTemplate}
                    onSelectTemplate={setSelectedTemplate}
                  />
                </TabsContent>
              </div>
            </Tabs>
          </div>
        </div>

        {/* Bottom Bar */}
        <div className="pt-4 border-t mt-4 flex justify-between items-center">
          <Button
            variant="outline"
            onClick={handleBack}
            className="rounded-full px-6 py-6"
          >
            <ChevronLeft className="w-4 h-4 mr-1" />
            Back
          </Button>

          <div className="flex items-center gap-3">
            {streamState.isStreaming && (
              <span className="inline-flex items-center gap-1 text-sm text-blue-600">
                <Loader2 className="w-4 h-4 animate-spin" />
                Streaming outlines...
              </span>
            )}
            <Button
              onClick={handleApproveAndGenerate}
              disabled={
                isGenerating ||
                streamState.isStreaming ||
                !outlines ||
                outlines.length === 0
              }
              className="px-8 py-6 bg-[#5146E5] hover:bg-[#5146E5]/90 text-white font-semibold text-base rounded-full"
            >
              {isGenerating ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Generating...
                </>
              ) : (
                <>
                  Approve & Generate
                  <ChevronRight className="w-5 h-5 ml-1" />
                </>
              )}
            </Button>
          </div>
        </div>
      </Wrapper>
    </div>
  );
}
