import Link from "next/link";
import { Wand2, Clapperboard, Film } from "lucide-react";
import { createClient }        from "@/lib/supabase/server";
import { PLATFORM_CONFIGS }    from "@/types/platform";
import type { Platform }       from "@/types/platform";
import { StatCards }           from "@/components/dashboard/StatCards";
import { UsageBar }            from "@/components/dashboard/UsageBar";
import { QuickToolsGrid }      from "@/components/dashboard/QuickToolsGrid";
import { RecentStoryboards, RecentPromptHistory } from "@/components/dashboard/RecentActivity";

export default async function DashboardPage() {
  const supabase = createClient();
  const { data: { user } } = await supabase.auth.getUser();

  const [
    profileResult,
    historyResult,
    statsResult,
    favoritesResult,
    storyboardCountResult,
    recentStoryboardResult,
  ] = await Promise.all([
    supabase.from("profiles").select("*").eq("id", user!.id).single(),
    supabase.from("prompt_history").select("*").eq("user_id", user!.id)
      .order("created_at", { ascending: false }).limit(4),
    supabase.from("prompt_history").select("platform").eq("user_id", user!.id),
    supabase.from("prompt_history").select("id", { count: "exact", head: true })
      .eq("user_id", user!.id).eq("is_favorite", true),
    supabase.from("storyboard_history").select("id", { count: "exact", head: true })
      .eq("user_id", user!.id),
    supabase.from("storyboard_history")
      .select("id, source_title, source_platform, style, output, created_at")
      .eq("user_id", user!.id).order("created_at", { ascending: false }).limit(3),
  ]);

  const profile           = profileResult.data;
  const recentHistory     = historyResult.data ?? [];
  const allHistory        = statsResult.data ?? [];
  const favoritesCount    = favoritesResult.count ?? 0;
  const storyboardCount   = storyboardCountResult.count ?? 0;
  const recentStoryboards = recentStoryboardResult.data ?? [];

  // Top platform
  const platformCounts   = allHistory.reduce((acc: Record<string, number>, h) => {
    acc[h.platform] = (acc[h.platform] ?? 0) + 1; return acc;
  }, {});
  const topPlatformEntry = Object.entries(platformCounts).sort((a, b) => b[1] - a[1])[0];
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const _topPlatformName = topPlatformEntry
    ? (PLATFORM_CONFIGS[topPlatformEntry[0] as Platform]?.name ?? "—") : "—";

  return (
    <div className="max-w-6xl mx-auto space-y-8">

      {/* Welcome */}
      <div className="flex items-end justify-between">
        <div>
          <h1 className="text-2xl font-bold">
            Halo, {profile?.full_name?.split(" ")[0] ?? "Kreator"} 👋
          </h1>
          <p className="text-muted-foreground mt-1 text-sm">Siap buat konten keren hari ini?</p>
        </div>
        <div className="hidden sm:flex items-center gap-2">
          <Link href="/storyboard"
            className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium border border-violet-500/40 text-violet-300 hover:bg-violet-500/10 transition-all">
            <Clapperboard className="w-4 h-4" /> Storyboard
          </Link>
          <Link href="/ugc-generator"
            className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium border border-pink-500/40 text-pink-300 hover:bg-pink-500/10 transition-all">
            <Film className="w-4 h-4" /> UGC
          </Link>
          <Link href="/generator/seedance"
            className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium transition-all hover:opacity-90"
            style={{ background: "linear-gradient(135deg,#7c3aed,#06b6d4)", boxShadow: "0 4px 16px rgba(124,58,237,0.3)" }}>
            <Wand2 className="w-4 h-4" /> Generate
          </Link>
        </div>
      </div>

      {/* Stat cards */}
      <StatCards
        totalGenerations={allHistory.length}
        usageCount={profile?.usage_count ?? 0}
        usageLimit={profile?.usage_limit ?? 50}
        storyboardCount={storyboardCount}
        favoritesCount={favoritesCount}
      />

      {/* Storyboard onboarding CTA — hanya kalau belum pernah buat */}
      {storyboardCount === 0 && (
        <Link href="/storyboard"
          className="flex items-center gap-4 rounded-2xl p-5 transition-all hover:opacity-90 group"
          style={{ background: "linear-gradient(135deg,rgba(124,58,237,0.15),rgba(37,99,235,0.1))", border: "1px solid rgba(124,58,237,0.3)" }}>
          <div className="w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0"
            style={{ background: "linear-gradient(135deg,#7c3aed,#2563eb)" }}>
            <Clapperboard className="w-6 h-6 text-white" />
          </div>
          <div className="flex-1">
            <p className="font-semibold text-sm">Coba Storyboard Generator 🎬</p>
            <p className="text-xs text-muted-foreground mt-0.5">
              Ubah link postingan atau artikel jadi storyboard video dalam hitungan detik.
            </p>
          </div>
        </Link>
      )}

      {/* Usage bar */}
      {profile && <UsageBar profile={profile} />}

      {/* Quick tools + platform grid */}
      <QuickToolsGrid />

      {/* Recent activity */}
      <RecentStoryboards  items={recentStoryboards} />
      <RecentPromptHistory items={recentHistory} />

    </div>
  );
}
