"use client";

import { useCallback, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import { Sparkles, Wand2, CalendarCheck, Settings2, Plus, Loader2, ArrowLeft, Zap } from "lucide-react";
import Landing from "@/components/studio/landing";
import Onboarding from "@/components/studio/onboarding";
import StudioView from "@/components/studio/studio-view";
import CalendarView from "@/components/studio/calendar-view";
import SettingsView from "@/components/studio/settings-view";
import type { Brand, Campaign, Workspace } from "@/components/studio/types";

type View = "landing" | "onboarding" | "studio" | "calendar" | "settings";

const NAV: Array<{ id: View; label: string; icon: typeof Wand2 }> = [
  { id: "studio", label: "Studio", icon: Wand2 },
  { id: "calendar", label: "Calendar", icon: CalendarCheck },
  { id: "settings", label: "Insights", icon: Settings2 },
];

export default function Home() {
  const { toast } = useToast();
  const [view, setView] = useState<View>("landing");
  const [workspace, setWorkspace] = useState<Workspace | null>(null);
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);
  const [selectedBrandId, setSelectedBrandId] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const loadWorkspace = useCallback(async () => {
    try {
      const res = await fetch("/api/workspace");
      if (!res.ok) return;
      const data: Workspace = await res.json();
      setWorkspace(data);
      setSelectedBrandId((prev) => prev ?? (data.brands[0]?.id ?? null));
    } catch {
      /* silent — landing still works */
    }
  }, []);

  const loadCampaigns = useCallback(async () => {
    try {
      const res = await fetch("/api/campaigns");
      if (!res.ok) return;
      const data = await res.json();
      setCampaigns(data.campaigns || []);
    } catch {
      /* silent */
    }
  }, []);

  useEffect(() => {
    loadWorkspace();
    loadCampaigns();
  }, [loadWorkspace, loadCampaigns]);

  async function switchPlan(plan: string) {
    if (!workspace) return;
    const prev = workspace.user.plan;
    setWorkspace({ ...workspace, user: { ...workspace.user, plan } });
    try {
      const res = await fetch("/api/workspace", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ plan }),
      });
      if (!res.ok) throw new Error();
      const planName = workspace.plans.find((p) => p.id === plan)?.name || plan;
      toast({ title: `Switched to ${planName}`, description: "Plan limits updated across the studio." });
      loadWorkspace();
    } catch {
      setWorkspace({ ...workspace, user: { ...workspace.user, plan: prev } });
      toast({ title: "Could not switch plan", description: "Please try again." });
    }
  }

  async function deleteBrand(id: string) {
    try {
      const res = await fetch(`/api/brands?id=${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error();
      toast({ title: "Brand removed" });
      await loadWorkspace();
      await loadCampaigns();
      setSelectedBrandId((cur) => (cur === id ? null : cur));
    } catch {
      toast({ title: "Could not remove brand", description: "Try again." });
    }
  }

  function onBrandCreated(brand: Brand) {
    setWorkspace((w) =>
      w
        ? {
            ...w,
            brands: [...w.brands, brand],
            usage: { ...w.usage, brands: w.usage.brands + 1 },
          }
        : w
    );
    setSelectedBrandId(brand.id);
    setView("studio");
    toast({ title: `${brand.name} is ready 🎉`, description: "Type one line and generate your first campaign." });
  }

  async function enterApp() {
    setLoading(true);
    await loadWorkspace();
    await loadCampaigns();
    setLoading(false);
    setView(workspace?.brands.length ? "studio" : "onboarding");
  }

  /* ---------------- Landing ---------------- */
  if (view === "landing") {
    return (
      <div className="flex min-h-screen flex-col">
        <div className="flex-1">
          <Landing onEnter={enterApp} />
        </div>
        {loading && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-stone-950/40 backdrop-blur-sm">
            <div className="flex items-center gap-3 rounded-2xl bg-white px-6 py-4 shadow-xl">
              <Loader2 className="h-5 w-5 animate-spin text-orange-600" />
              <span className="text-sm font-medium">Opening your studio…</span>
            </div>
          </div>
        )}
      </div>
    );
  }

  const brands = workspace?.brands ?? [];
  const activeBrand = brands.find((b) => b.id === selectedBrandId) ?? null;

  /* ---------------- App shell ---------------- */
  return (
    <div className="flex min-h-screen flex-col bg-stone-50">
      {/* app header */}
      <header className="sticky top-0 z-40 border-b border-stone-200 bg-white/90 backdrop-blur">
        <div className="mx-auto flex h-14 max-w-6xl items-center gap-3 px-4">
          <button onClick={() => setView("landing")} className="flex items-center gap-2 text-stone-500 transition-colors hover:text-stone-900" title="Back to landing">
            <ArrowLeft className="h-4 w-4" />
            <div className="flex items-center gap-1.5">
              <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-orange-600 text-white">
                <Sparkles className="h-3.5 w-3.5" />
              </div>
              <span className="hidden text-base font-bold tracking-tight text-stone-900 sm:block">AdStudio<span className="text-orange-600">AI</span></span>
            </div>
          </button>

          <nav className="ml-4 flex items-center gap-1">
            {NAV.map((item) => (
              <button
                key={item.id}
                onClick={() => setView(item.id)}
                className={`flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors ${
                  view === item.id ? "bg-orange-100 text-orange-800" : "text-stone-600 hover:bg-stone-100 hover:text-stone-900"
                }`}
              >
                <item.icon className="h-4 w-4" />
                <span className="hidden sm:inline">{item.label}</span>
                {item.id === "calendar" && campaigns.some((c) => c.creatives.some((cr) => cr.status === "PENDING" && !cr.scheduledFor)) && (
                  <span className="h-1.5 w-1.5 rounded-full bg-orange-500" />
                )}
              </button>
            ))}
          </nav>

          <div className="ml-auto flex items-center gap-2">
            {workspace && (
              <Badge variant="outline" className="hidden border-stone-200 text-[11px] font-medium text-stone-600 md:inline-flex">
                <Zap className="mr-1 h-3 w-3 text-orange-600" />
                {workspace.plan.name} · {workspace.usage.monthlyCreatives}{workspace.usage.creativeCap !== null ? `/${workspace.usage.creativeCap}` : ""} creatives
              </Badge>
            )}
            <Button size="sm" onClick={() => setView("onboarding")} className="h-8 bg-stone-900 hover:bg-stone-800">
              <Plus className="mr-1 h-3.5 w-3.5" /> New brand
            </Button>
          </div>
        </div>
      </header>

      {/* main */}
      <main className="flex-1">
        {view === "onboarding" && (
          <Onboarding
            hasBrands={brands.length > 0}
            onDone={onBrandCreated}
            onSkip={() => {
              setSelectedBrandId(brands[0]?.id ?? null);
              setView("studio");
            }}
          />
        )}

        {view === "studio" && (
          <StudioView
            brands={brands}
            selectedBrandId={selectedBrandId}
            onSelectBrand={setSelectedBrandId}
            onCampaignCreated={() => loadCampaigns()}
            planName={workspace?.plan.name ?? "Starter"}
            monthlyCreatives={workspace?.usage.monthlyCreatives ?? 0}
            creativeCap={workspace?.usage.creativeCap ?? null}
          />
        )}

        {view === "calendar" && (
          <CalendarView campaigns={campaigns} onRefresh={loadCampaigns} />
        )}

        {view === "settings" && (
          <SettingsView
            workspace={workspace}
            brands={brands}
            campaigns={campaigns}
            onPlanSwitch={switchPlan}
            onRefresh={() => { loadWorkspace(); loadCampaigns(); }}
            onDeleteBrand={deleteBrand}
          />
        )}
      </main>

      {/* footer — sticky bottom, pushed down naturally on long pages */}
      <footer className="mt-auto border-t border-stone-200 bg-white py-4">
        <div className="mx-auto flex max-w-6xl flex-wrap items-center justify-between gap-2 px-4 text-xs text-stone-400">
          <div className="flex items-center gap-3">
            <span className="font-semibold text-stone-600">AdStudioAI</span>
            <span>Organic-first social automation</span>
          </div>
          <div className="flex items-center gap-3">
            {activeBrand && <span>Active: <strong className="text-stone-600">{activeBrand.name}</strong></span>}
            <span>© 2026</span>
          </div>
        </div>
      </footer>
    </div>
  );
}
