"use client";

import { useState, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Wand2, Clapperboard, Film } from "lucide-react";
import { cn } from "@/lib/utils";
import { PromptHistoryTab }     from "@/components/history/PromptHistoryTab";
import { StoryboardHistoryTab } from "@/components/history/StoryboardHistoryTab";
import { UGCHistoryTab }        from "@/components/history/UGCHistoryTab";

export default function HistoryPage() {
  return (
    <Suspense>
      <HistoryPageInner />
    </Suspense>
  );
}

function HistoryPageInner() {
  const searchParams = useSearchParams();
  const router       = useRouter();
  const rawTab       = searchParams.get("tab");
  const defaultTab   = rawTab === "storyboard" ? "storyboard" : rawTab === "ugc" ? "ugc" : "prompt";

  const [activeTab, setActiveTab] = useState<"prompt" | "storyboard" | "ugc">(defaultTab);

  const handleTabChange = (tab: "prompt" | "storyboard" | "ugc") => {
    setActiveTab(tab);
    const query = tab === "prompt" ? "" : `?tab=${tab}`;
    router.replace(`/history${query}`, { scroll: false });
  };

  const tabs = [
    { id: "prompt"     as const, label: "Prompt Generator", icon: Wand2,       active: "from-amber-500/20 text-amber-200" },
    { id: "storyboard" as const, label: "Storyboard",       icon: Clapperboard, active: "from-violet-500/20 text-violet-200" },
    { id: "ugc"        as const, label: "Generator UGC",    icon: Film,         active: "from-pink-500/20 text-pink-200" },
  ];

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Riwayat</h1>
        <p className="text-muted-foreground text-sm mt-1">
          Semua prompt, storyboard, dan UGC yang pernah kamu buat
        </p>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 p-1 rounded-xl bg-card border border-border w-fit">
        {tabs.map(({ id, label, icon: Icon, active }) => (
          <button
            key={id}
            onClick={() => handleTabChange(id)}
            className={cn(
              "flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all",
              activeTab === id
                ? `bg-gradient-to-r ${active} to-transparent shadow-sm`
                : "text-muted-foreground hover:text-foreground"
            )}
          >
            <Icon className="w-4 h-4" /> {label}
          </button>
        ))}
      </div>

      {activeTab === "prompt"     && <PromptHistoryTab />}
      {activeTab === "storyboard" && <StoryboardHistoryTab />}
      {activeTab === "ugc"        && <UGCHistoryTab />}
    </div>
  );
}
