import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { ArrowLeft, ArrowRight, Camera, Loader2, Sparkles, X } from "lucide-react";
import { EMOTIONS, EVENT_TYPES, PERSONALITIES, STYLES, type PhotoshootInput } from "@/lib/photoshoot-data";
import { generatePhotoshootPlan } from "@/lib/photoshoot.functions";
import { trackEvent } from "@/lib/analytics.functions";
import { clearExtraPrompts, type ExtraPromptSelection, loadExtraPrompts, saveExtraPrompts, saveInput, savePlan } from "@/lib/photoshoot-store";
import { toast } from "sonner";

export const Route = createFileRoute("/create")({
  head: () => ({
    meta: [
      { title: "Design your photoshoot — Personal Photoshoot Studio™" },
      { name: "description", content: "A four-step wizard that turns your occasion, emotion, personality, and style into a complete photoshoot plan." },
    ],
  }),
  component: CreateWizard,
});

const STEP_TITLES = ["The occasion", "The emotion", "Your personality", "Your style"];

function CreateWizard() {
  const navigate = useNavigate();
  const generateFn = useServerFn(generatePhotoshootPlan);
  const track = useServerFn(trackEvent);
  const [step, setStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [input, setInput] = useState<PhotoshootInput>({
    title: "",
    eventType: "Anniversary",
    date: "",
    location: "",
    emotion: "Romance",
    personality: "Elegant",
    style: "Luxury Editorial",
  });
  const [extras, setExtras] = useState<ExtraPromptSelection[]>([]);

  useEffect(() => { setExtras(loadExtraPrompts()); }, []);

  function removeExtra(id: string) {
    const next = extras.filter((e) => e.id !== id);
    setExtras(next);
    saveExtraPrompts(next);
  }

  const canAdvance =
    step === 0 ? input.title.trim().length > 0 && input.eventType :
    step === 1 ? !!input.emotion :
    step === 2 ? !!input.personality :
    !!input.style;

  async function handleGenerate() {
    setLoading(true);
    try {
      const payload: PhotoshootInput = {
        ...input,
        extraPromptIds: extras.map((e) => e.id),
        extraPromptTexts: extras.map((e) => e.prompt_text),
      };
      saveInput(payload);
      const plan = await generateFn({ data: payload });
      savePlan(plan);
      clearExtraPrompts();
      void track({
        data: {
          event: "photoshoot_plan_generated",
          props: { event_type: payload.eventType, emotion: payload.emotion, style: payload.style, extras: extras.length },
        },
      }).catch(() => {});
      navigate({ to: "/plan" });
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Something went wrong";
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen bg-background flex flex-col">
      <header className="border-b border-border bg-background/80 backdrop-blur sticky top-0 z-20">
        <div className="mx-auto max-w-5xl px-6 h-16 flex items-center justify-between">
          <Link to="/" className="flex items-center gap-2">
            <div className="h-8 w-8 rounded-full bg-gradient-gold flex items-center justify-center">
              <Camera className="h-4 w-4 text-primary" />
            </div>
            <span className="font-display text-lg font-semibold">Personal Photoshoot Studio<span className="text-gold">™</span></span>
          </Link>
          <span className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
            Step {step + 1} of 4 — {STEP_TITLES[step]}
          </span>
        </div>
        <div className="h-0.5 bg-border">
          <div className="h-full bg-gradient-gold transition-all duration-500" style={{ width: `${((step + 1) / 4) * 100}%` }} />
        </div>
      </header>

      <main className="flex-1 mx-auto w-full max-w-3xl px-6 py-16">
        {extras.length > 0 && (
          <div className="mb-10 rounded-2xl border border-gold/40 bg-gradient-warm p-5">
            <div className="flex items-center justify-between mb-3">
              <p className="text-xs uppercase tracking-[0.25em] text-gold flex items-center gap-2">
                <Sparkles className="h-3.5 w-3.5" /> {extras.length} prompt{extras.length === 1 ? "" : "s"} injected from your library
              </p>
              <Link to="/prompts" className="text-xs underline underline-offset-4 decoration-gold">Edit selection</Link>
            </div>
            <ul className="space-y-1.5">
              {extras.map((e) => (
                <li key={e.id} className="flex items-center justify-between gap-3 text-sm">
                  <span className="truncate">{e.title}</span>
                  <button onClick={() => removeExtra(e.id)} className="text-muted-foreground hover:text-foreground shrink-0"><X className="h-3.5 w-3.5" /></button>
                </li>
              ))}
            </ul>
          </div>
        )}
        {step === 0 && <StepOccasion input={input} setInput={setInput} />}
        {step === 1 && <StepEmotion input={input} setInput={setInput} />}
        {step === 2 && <StepPersonality input={input} setInput={setInput} />}
        {step === 3 && <StepStyle input={input} setInput={setInput} />}
      </main>

      <footer className="border-t border-border bg-card/50 sticky bottom-0">
        <div className="mx-auto max-w-3xl px-6 py-4 flex items-center justify-between">
          <button
            onClick={() => setStep((s) => Math.max(0, s - 1))}
            disabled={step === 0 || loading}
            className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground disabled:opacity-30 disabled:pointer-events-none"
          >
            <ArrowLeft className="h-4 w-4" /> Back
          </button>
          {step < 3 ? (
            <button
              onClick={() => setStep((s) => s + 1)}
              disabled={!canAdvance}
              className="inline-flex items-center gap-2 rounded-full bg-primary px-6 py-2.5 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-40 disabled:cursor-not-allowed transition"
            >
              Continue <ArrowRight className="h-4 w-4" />
            </button>
          ) : (
            <button
              onClick={handleGenerate}
              disabled={!canAdvance || loading}
              className="inline-flex items-center gap-2 rounded-full bg-primary px-6 py-2.5 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-40 transition shadow-elegant"
            >
              {loading ? <><Loader2 className="h-4 w-4 animate-spin" /> Crafting your plan…</> : <><Sparkles className="h-4 w-4" /> Generate plan</>}
            </button>
          )}
        </div>
      </footer>
    </div>
  );
}

function StepHeader({ eyebrow, title, subtitle }: { eyebrow: string; title: string; subtitle?: string }) {
  return (
    <div className="mb-10">
      <p className="text-xs uppercase tracking-[0.3em] text-gold mb-3">{eyebrow}</p>
      <h1 className="font-display text-4xl md:text-5xl leading-tight">{title}</h1>
      {subtitle && <p className="mt-4 text-muted-foreground text-lg">{subtitle}</p>}
    </div>
  );
}

type Setter = React.Dispatch<React.SetStateAction<PhotoshootInput>>;

function StepOccasion({ input, setInput }: { input: PhotoshootInput; setInput: Setter }) {
  return (
    <div>
      <StepHeader eyebrow="The occasion" title="What are we celebrating?" subtitle="A few quick details to anchor the shoot." />
      <div className="space-y-6">
        <Field label="Photoshoot name">
          <input
            value={input.title}
            onChange={(e) => setInput({ ...input, title: e.target.value })}
            placeholder="e.g. 25th Wedding Anniversary"
            className="w-full rounded-lg border border-input bg-card px-4 py-3 text-base focus:outline-none focus:ring-2 focus:ring-ring/40 focus:border-ring"
          />
        </Field>
        <Field label="Event type">
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
            {EVENT_TYPES.map((e) => (
              <Chip key={e} active={input.eventType === e} onClick={() => setInput({ ...input, eventType: e })}>{e}</Chip>
            ))}
          </div>
        </Field>
        <div className="grid sm:grid-cols-2 gap-6">
          <Field label="Date (optional)">
            <input type="date" value={input.date} onChange={(e) => setInput({ ...input, date: e.target.value })}
              className="w-full rounded-lg border border-input bg-card px-4 py-3 text-base focus:outline-none focus:ring-2 focus:ring-ring/40" />
          </Field>
          <Field label="Location context (optional)">
            <input value={input.location} onChange={(e) => setInput({ ...input, location: e.target.value })}
              placeholder="e.g. Tuscany, NYC, our backyard"
              className="w-full rounded-lg border border-input bg-card px-4 py-3 text-base focus:outline-none focus:ring-2 focus:ring-ring/40" />
          </Field>
        </div>
      </div>
    </div>
  );
}

function StepEmotion({ input, setInput }: { input: PhotoshootInput; setInput: Setter }) {
  return (
    <div>
      <StepHeader eyebrow="The emotion" title="How should these images make people feel?" subtitle="Pick the feeling we'll preserve forever." />
      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
        {EMOTIONS.map((e) => (
          <BigChip key={e} active={input.emotion === e} onClick={() => setInput({ ...input, emotion: e })}>{e}</BigChip>
        ))}
      </div>
    </div>
  );
}

function StepPersonality({ input, setInput }: { input: PhotoshootInput; setInput: Setter }) {
  return (
    <div>
      <StepHeader eyebrow="Your personality" title="Which best describes you?" subtitle="So every choice feels unmistakably yours." />
      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
        {PERSONALITIES.map((p) => (
          <BigChip key={p} active={input.personality === p} onClick={() => setInput({ ...input, personality: p })}>{p}</BigChip>
        ))}
      </div>
    </div>
  );
}

function StepStyle({ input, setInput }: { input: PhotoshootInput; setInput: Setter }) {
  return (
    <div>
      <StepHeader eyebrow="Your style" title="What photographic language?" subtitle="The visual grammar your images will speak." />
      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
        {STYLES.map((s) => (
          <BigChip key={s} active={input.style === s} onClick={() => setInput({ ...input, style: s })}>{s}</BigChip>
        ))}
      </div>
    </div>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <span className="block text-xs uppercase tracking-[0.2em] text-muted-foreground mb-2">{label}</span>
      {children}
    </label>
  );
}

function Chip({ active, children, onClick }: { active: boolean; children: React.ReactNode; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`rounded-full border px-4 py-2 text-sm transition ${active ? "border-primary bg-primary text-primary-foreground" : "border-border bg-card hover:border-gold"}`}
    >
      {children}
    </button>
  );
}

function BigChip({ active, children, onClick }: { active: boolean; children: React.ReactNode; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`group relative rounded-xl border px-5 py-6 text-left transition shadow-soft ${active ? "border-gold bg-gradient-warm ring-2 ring-gold/40" : "border-border bg-card hover:border-gold/60 hover:-translate-y-0.5"}`}
    >
      <span className="font-display text-xl">{children}</span>
    </button>
  );
}
