"use client";

import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store/store";
import {
  setSelectedClient,
  setSelectedDeck,
  setSlideCount,
  setInstructions,
  setTone,
  setLanguage,
  setWizardStep,
  setJobId,
  setPresentationId as setWizardPresentationId,
} from "@/store/slices/wizardSlice";
import {
  setPresentationId,
  clearOutlines,
} from "@/store/slices/presentationGeneration";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ChevronLeft, ChevronRight, Layers, MessageCircleQuestion } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { OverlayLoader } from "@/components/ui/overlay-loader";
import Wrapper from "@/components/Wrapper";
import { WizardApi, ClientOption, MasterDeckOption } from "../../services/api/wizard";

const TONE_OPTIONS = [
  { value: "professional", label: "Professional" },
  { value: "casual", label: "Casual" },
  { value: "educational", label: "Educational" },
  { value: "sales_pitch", label: "Sales Pitch" },
  { value: "default", label: "Neutral" },
];

const LANGUAGE_OPTIONS = [
  "English",
  "Spanish (Espanol)",
  "French (Francais)",
  "German (Deutsch)",
  "Portuguese (Portugues)",
  "Italian (Italiano)",
  "Russian (Русский)",
  "Chinese (Simplified)",
  "Japanese (日本語)",
  "Korean (한국어)",
  "Arabic (العربية)",
  "Hindi (हिन्दी)",
];

export default function WizardConfigurePage() {
  const router = useRouter();
  const dispatch = useDispatch();
  const wizard = useSelector((s: RootState) => s.wizard);

  const [clients, setClients] = useState<ClientOption[]>([]);
  const [masterDecks, setMasterDecks] = useState<MasterDeckOption[]>([]);
  const [loadingClients, setLoadingClients] = useState(true);
  const [loadingDecks, setLoadingDecks] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);
  const [followUpQuestions, setFollowUpQuestions] = useState<string[]>([]);
  const [followUpAnswers, setFollowUpAnswers] = useState<Record<string, string>>({});
  const [loadingFollowUp, setLoadingFollowUp] = useState(false);

  // Fetch clients on mount
  useEffect(() => {
    WizardApi.getClients()
      .then(setClients)
      .finally(() => setLoadingClients(false));
  }, []);

  // Fetch master decks when client changes
  useEffect(() => {
    if (!wizard.selectedClientId) {
      setMasterDecks([]);
      return;
    }
    setLoadingDecks(true);
    WizardApi.getMasterDecks(wizard.selectedClientId)
      .then(setMasterDecks)
      .finally(() => setLoadingDecks(false));
  }, [wizard.selectedClientId]);

  // Fetch follow-up questions if brief is short
  useEffect(() => {
    const briefContent = wizard.briefText;
    if (!briefContent || briefContent.trim().length < 10) {
      setFollowUpQuestions([]);
      return;
    }
    setLoadingFollowUp(true);
    WizardApi.checkFollowUpQuestions(briefContent)
      .then((questions) => {
        setFollowUpQuestions(questions);
        setFollowUpAnswers({});
      })
      .finally(() => setLoadingFollowUp(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Run once on page load

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

  const handleGenerateOutline = async () => {
    if (!wizard.briefText.trim() && wizard.uploadedFiles.length === 0) {
      toast.error("No content provided. Please go back and add a brief or files.");
      return;
    }

    try {
      setIsGenerating(true);

      // Gather file server paths
      const filePaths = wizard.uploadedFiles
        .map((f) => f.serverPath)
        .filter(Boolean) as string[];

      // Append follow-up Q&A to instructions if any answers are provided
      let finalInstructions = wizard.instructions;
      const answeredPairs = followUpQuestions
        .filter((q) => followUpAnswers[q]?.trim())
        .map((q) => `Q: ${q}\nA: ${followUpAnswers[q].trim()}`);
      if (answeredPairs.length > 0) {
        const qaSuffix = "\n\n--- Follow-up Context ---\n" + answeredPairs.join("\n\n");
        finalInstructions = (finalInstructions || "") + qaSuffix;
      }

      // Create presentation (outline mode)
      const result = await WizardApi.createPresentation({
        content: wizard.briefText,
        n_slides: wizard.slideCount,
        file_paths: filePaths,
        language: wizard.language,
        tone: wizard.tone,
        instructions: finalInstructions,
        client_id: wizard.selectedClientId ?? undefined,
        master_deck_id: wizard.selectedDeckId ?? undefined,
      });

      dispatch(setPresentationId(result.id));
      dispatch(setWizardPresentationId(result.id));
      dispatch(clearOutlines());
      dispatch(setWizardStep(3));
      router.push("/generate/outline");
    } catch (error: any) {
      toast.error("Failed to generate outline", {
        description: error.message || "Please try again.",
      });
    } finally {
      setIsGenerating(false);
    }
  };

  return (
    <Wrapper className="py-8 max-w-3xl">
      <OverlayLoader
        show={isGenerating}
        text="Generating outline..."
        showProgress
        duration={30}
      />

      <h1 className="text-2xl font-semibold mb-1">Configure Presentation</h1>
      <p className="text-sm text-gray-500 mb-8">
        Set up your presentation preferences before generating the outline.
      </p>

      <div className="space-y-6">
        {/* Client Selector */}
        <div>
          <Label className="mb-2 block">Client</Label>
          <Select
            value={wizard.selectedClientId ?? ""}
            onValueChange={(v) => dispatch(setSelectedClient(v || null))}
          >
            <SelectTrigger className="w-full">
              <SelectValue placeholder={loadingClients ? "Loading..." : "Select a client"} />
            </SelectTrigger>
            <SelectContent>
              {clients.map((c) => (
                <SelectItem key={c.id} value={c.id}>
                  {c.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Master Deck Selector */}
        <div>
          <Label className="mb-2 block">Master Deck (Template)</Label>
          {!wizard.selectedClientId ? (
            <p className="text-sm text-gray-400">Select a client first to see available decks.</p>
          ) : loadingDecks ? (
            <p className="text-sm text-gray-400">Loading decks...</p>
          ) : masterDecks.length === 0 ? (
            <p className="text-sm text-gray-400">No master decks available for this client.</p>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              {masterDecks.map((deck) => (
                <button
                  key={deck.id}
                  onClick={() => dispatch(setSelectedDeck(deck.id))}
                  className={cn(
                    "flex flex-col items-center gap-2 p-4 rounded-xl border-2 transition-all text-left",
                    wizard.selectedDeckId === deck.id
                      ? "border-[#5146E5] bg-[#5146E5]/5"
                      : "border-gray-200 hover:border-gray-300"
                  )}
                >
                  <div className="w-full aspect-video bg-gray-100 rounded-lg flex items-center justify-center overflow-hidden">
                    {deck.thumbnail_url ? (
                      <img src={deck.thumbnail_url} alt={deck.name} className="w-full h-full object-cover" />
                    ) : (
                      <Layers className="w-8 h-8 text-gray-300" />
                    )}
                  </div>
                  <span className="text-sm font-medium truncate w-full">{deck.name}</span>
                  <span className="text-xs text-gray-400">{deck.layout_count} layouts</span>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Slide Count */}
        <div>
          <Label className="mb-2 block">
            Number of Slides: <span className="font-semibold text-[#5146E5]">{wizard.slideCount}</span>
          </Label>
          <Slider
            value={[wizard.slideCount]}
            onValueChange={([v]) => dispatch(setSlideCount(v))}
            min={5}
            max={40}
            step={1}
            className="w-full"
          />
          <div className="flex justify-between text-xs text-gray-400 mt-1">
            <span>5</span>
            <span>40</span>
          </div>
        </div>

        {/* Language */}
        <div>
          <Label className="mb-2 block">Language</Label>
          <Select
            value={wizard.language}
            onValueChange={(v) => dispatch(setLanguage(v))}
          >
            <SelectTrigger className="w-full">
              <SelectValue placeholder="Select language" />
            </SelectTrigger>
            <SelectContent>
              {LANGUAGE_OPTIONS.map((lang) => (
                <SelectItem key={lang} value={lang}>
                  {lang}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Tone */}
        <div>
          <Label className="mb-2 block">Tone</Label>
          <Select
            value={wizard.tone}
            onValueChange={(v) => dispatch(setTone(v))}
          >
            <SelectTrigger className="w-full">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {TONE_OPTIONS.map((t) => (
                <SelectItem key={t.value} value={t.value}>
                  {t.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Follow-Up Questions */}
        {loadingFollowUp && (
          <div className="rounded-xl border border-amber-200 bg-amber-50 p-4">
            <p className="text-sm text-amber-700">Checking if we need more context...</p>
          </div>
        )}
        {followUpQuestions.length > 0 && !loadingFollowUp && (
          <div className="rounded-xl border border-amber-200 bg-amber-50 p-4 space-y-4">
            <div className="flex items-center gap-2 text-amber-800">
              <MessageCircleQuestion className="w-5 h-5 flex-shrink-0" />
              <p className="text-sm font-medium">
                A few quick questions to improve your presentation
              </p>
            </div>
            {followUpQuestions.map((question, idx) => (
              <div key={idx} className="space-y-1.5">
                <Label className="text-sm text-amber-900">{question}</Label>
                <Input
                  placeholder="Your answer (optional)"
                  value={followUpAnswers[question] ?? ""}
                  onChange={(e) =>
                    setFollowUpAnswers((prev) => ({
                      ...prev,
                      [question]: e.target.value,
                    }))
                  }
                  className="bg-white border-amber-200 focus:border-amber-400"
                />
              </div>
            ))}
          </div>
        )}

        {/* Instructions */}
        <div>
          <Label className="mb-2 block">Additional Instructions</Label>
          <Textarea
            placeholder='e.g. "Focus on Q4 results", "Skip market comparison", "Emphasize growth metrics"'
            value={wizard.instructions}
            onChange={(e) => dispatch(setInstructions(e.target.value))}
            className="min-h-[100px] resize-y"
          />
        </div>
      </div>

      {/* Navigation */}
      <div className="mt-8 flex justify-between">
        <Button
          variant="outline"
          onClick={handleBack}
          className="rounded-full px-6 py-6"
        >
          <ChevronLeft className="w-4 h-4 mr-1" />
          Back
        </Button>
        <Button
          onClick={handleGenerateOutline}
          disabled={isGenerating}
          className="px-8 py-6 bg-[#5146E5] hover:bg-[#5146E5]/90 text-white font-semibold text-base rounded-full"
        >
          Generate Outline
          <ChevronRight className="w-5 h-5 ml-1" />
        </Button>
      </div>
    </Wrapper>
  );
}
