"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import type { Locale } from "@/config/i18n";
import type { Dictionary } from "@allai/i18n/server";
import { useMockAuth } from "@/providers/auth/MockAuthProvider";
import { AccountOverview } from "@/features/account/AccountOverview";
import {
  AppShell,
  AppShellNavigationItem,
  AppShellStatusPill
} from "@/components/layouts/app-shell";
import { Button } from "@allai/ui";

type AccountClientProps = {
  locale: Locale;
  dictionaryAccount: Dictionary["account"];
  fullDictionary: Dictionary;
};

export function AccountClient({ locale, dictionaryAccount, fullDictionary }: AccountClientProps) {
  const router = useRouter();
  const { user } = useMockAuth();

  useEffect(() => {
    if (!user) {
      router.replace(`/${locale}/login`);
    }
  }, [user, router, locale]);

  if (!user) {
    return null;
  }

  const navigation: AppShellNavigationItem[] = [
    { key: "generator", label: fullDictionary.navigation.imageGenerator, icon: "Sparkles" },
    { key: "veo", label: "Veo workbench", icon: "Film" },
    { key: "account", label: dictionaryAccount.title, icon: "UserRound", active: true },
    { key: "pricing", label: fullDictionary.navigation.pricing, icon: "CreditCard" }
  ];

  const statusPills: AppShellStatusPill[] = [
    {
      key: "balance",
      label: `${dictionaryAccount.balanceLabel}: ${user.balance} cr`,
      icon: { name: "Wallet" }
    },
    {
      key: "email",
      label: user.email,
      icon: { name: "Mail" }
    }
  ];

  const footerHighlight = {
    label: dictionaryAccount.balanceLabel,
    helper: dictionaryAccount.balanceHint,
    value: `${user.balance} cr`,
    cta: (
      <Button size="sm" variant="primary">
        {dictionaryAccount.topUpCta}
      </Button>
    )
  };

  function handlePrimarySelect(key: string) {
    if (key === "account") return;
    if (key === "generator") {
      router.push(`/${locale}`);
      return;
    }
    if (key === "veo") {
      router.push(`/${locale}/veo`);
      return;
    }
    if (key === "pricing") {
      router.push(`/${locale}/pricing`);
    }
  }

  return (
    <AppShell
      title={dictionaryAccount.title}
      description={dictionaryAccount.subtitle}
      primaryNavigation={navigation}
      statusPills={statusPills}
      footerHighlight={footerHighlight}
      user={{ name: user.email, email: user.email }}
      onPrimarySelect={handlePrimarySelect}
      showSearch={false}
    >
      <AccountOverview
        email={user.email}
        balance={user.balance}
        history={user.history}
        dictionary={dictionaryAccount}
        locale={locale}
      />
    </AppShell>
  );
}
