"use client";

import { Tabs, Tab } from "@heroui/react";
import { useEffect, useMemo, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { useAtomCallback } from "jotai/utils";
import { resetAuctionAtoms } from "@/components/state/autionAtoms";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Card, CardBody } from "@heroui/react";
import { useSession } from "@/auth/session-provider";
import { useGeneralSettings, useProfile } from "@/lib/clientQueries";
import Image from "next/image";
import {
  Bell,
  Circle,
  CreditCard,
  Gavel,
  HandCoins,
  Heart,
  Home,
  ListChecks,
  PlusSquare,
  ShoppingBag,
  UserRound,
  Wallet,
  type LucideIcon,
} from "lucide-react";

import ProfileSection from "@/components/sections/ProfileSection";
import SettingsSection from "@/components/sections/SettingsSection";
import SalesTable from "@/components/table/SalesTable";
import PurchasesTable from "@/components/table/PurchasesTable";
import MyAuctionsTable from "@/components/table/MyAuctionsTable";
import LiveListingsTable from "@/components/table/LiveAuctionsTable";
import AnnualGroupAuctionsTable from "@/components/table/AnnualGroupAuctionsTable";
import MyYearlyAuctionGroupsTable from "@/components/table/MyYearlyAuctionGroupsTable";
import WalletSection from "@/components/wallet/WalletSection";
import ComplaintsSection from "@/components/complemants/ComplaintsSection";
import NotificationsSection from "@/components/sections/NotificationSection";
import FavoritesSection from "@/components/sections/FavoriteSection";
import MyReviewsSection from "@/components/sections/MyReviewSection";
import AddListingWizard from "./AddListingWizard";
import WalletRequestsTable from "@/components/sections/WalletRequestSection";
import PaymentsSection from "@/components/sections/PaymentsSection";
import ParticipatedAuctionsSection from "@/components/sections/ParticipatedAuctionsSection";
import AnimatedCounter from "@/components/ui/AnimatedCounter";
import PurchaseOffersTable from "@/components/table/PurchaseOffersTable";

export default function MazadClient() {
  const t = useTranslations("DASHBOARD");
  const locale = useLocale();
  const isRTL = locale === "ar";
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const session = useSession();
  const { data: profile } = useProfile();
  const { data: settings } = useGeneralSettings();
  const [selected, setSelected] = useState("home");
  const resetAll = useAtomCallback((get, set) => {
    resetAuctionAtoms(set);
  });

  const stats = profile?.statistics || {
    offers_count: "0",
    auctions_count: "0",
    single_auctions_count: "0",
  };

  const tabs = useMemo(
    () =>
      [
        { key: "home", title: t("home") },
        { key: "add", title: t("add_listing") },
        { key: "auctions", title: t("my_auctions") },
        { key: "mazayadaty", title: t("mazayadaty") },
        /*         { key: "my-yearly-auction-rooms", title: t("my_yearly_auction_rooms") },
         */
        { key: "listings", title: t("live_listings") },
        { key: "sales", title: t("sales") },
        { key: "buyes", title: t("buyes") },
        { key: "purchase-offers-buyer", title: t("purchase_offers_buyer") },
        { key: "purchase-offers-seller", title: t("purchase_offers_seller") },
        { key: "Favorite", title: t("favorites") },

        { key: "wallet", title: t("wallet") },
        { key: "wallet-request", title: t("wallet-request") },
        { key: "payments", title: t("payments") },
        { key: "participated-auctions", title: t("participated_auctions") },

        { key: "notifications", title: t("notifications") },
        /*         { key: "complaints", title: t("complaints") },
         */ /* { key: "review", title: t("reviews") }, */
        /*         { key: "settings", title: t("settings") },
         */ { key: "profile", title: t("profile") },
      ] as const,
    [t],
  );

  const tabIcons = useMemo<Record<string, LucideIcon>>(
    () => ({
      home: Home,
      add: PlusSquare,
      auctions: Gavel,
      mazayadaty: ListChecks,
      listings: ListChecks,
      sales: ShoppingBag,
      buyes: ShoppingBag,
      "purchase-offers-buyer": HandCoins,
      "purchase-offers-seller": HandCoins,
      Favorite: Heart,
      wallet: Wallet,
      "wallet-request": Wallet,
      payments: CreditCard,
      "participated-auctions": Gavel,
      notifications: Bell,
      profile: UserRound,
    }),
    [],
  );

  const brandName = settings?.site_name
    ? String(settings.site_name)
    : isRTL
      ? "عطايا"
      : "Ataya";
  const brandLogo =
    settings?.colored_logo || settings?.main_logo || "/logo.png";

  const allowedTabKeys = useMemo(
    () => new Set<string>(tabs.map((x) => x.key)),
    [tabs],
  );

  useEffect(() => {
    const tabFromUrl = searchParams?.get("tab") ?? undefined;
    if (tabFromUrl && allowedTabKeys.has(tabFromUrl)) {
      setSelected(tabFromUrl);
      return;
    }

    try {
      const stored = window.localStorage.getItem("ataya_dashboard_tab") ?? "";
      if (stored && allowedTabKeys.has(stored)) {
        setSelected(stored);

        const params = new URLSearchParams(searchParams?.toString());
        params.set("tab", stored);
        router.replace(`${pathname}?${params.toString()}`);
      }
    } catch {
      // ignore
    }
  }, [allowedTabKeys, pathname, router, searchParams]);

  useEffect(() => {
    return () => {
      try {
        window.localStorage.removeItem("ataya_dashboard_tab");
      } catch (error) {
        console.error(error);
      }
    };
  }, []);

  const handleTabChange = (key: string) => {
    if (selected === "add" && key !== "add") {
      resetAll();
      if (typeof window !== "undefined") {
        window.localStorage.removeItem("ataya_auction_form");
      }
    }

    const nextKey = key.toString();
    setSelected(nextKey);

    try {
      window.localStorage.setItem("ataya_dashboard_tab", nextKey);
    } catch {
      // ignore
    }

    const params = new URLSearchParams(searchParams?.toString());
    params.set("tab", nextKey);
    router.replace(`${pathname}?${params.toString()}`);
  };

  const renderTabContent = (key: string) => {
    switch (key) {
      case "add":
        return <AddListingWizard />;
      case "auctions":
        return <MyAuctionsTable />;
      case "mazayadaty":
        return <AnnualGroupAuctionsTable />;
      /*  case "my-yearly-auction-rooms":
        return <MyYearlyAuctionGroupsTable />; */
      case "Favorite":
        return <FavoritesSection />;
      case "listings":
        return <LiveListingsTable />;
      case "sales":
        return <SalesTable />;
      case "buyes":
        return <PurchasesTable />;
      case "purchase-offers-buyer":
        return <PurchaseOffersTable actorType="buyer" />;
      case "purchase-offers-seller":
        return <PurchaseOffersTable actorType="seller" />;
      case "wallet":
        return <WalletSection />;
      case "wallet-request":
        return <WalletRequestsTable />;
      case "payments":
        return <PaymentsSection />;
      case "participated-auctions":
        return <ParticipatedAuctionsSection />;
      case "notifications":
        return <NotificationsSection />;
      case "complaints":
        return <ComplaintsSection />;
      case "review":
        return <MyReviewsSection />;
      case "settings":
        return <SettingsSection />;
      case "profile":
        return <ProfileSection />;

      default:
        return (
          <div className="space-y-6">
            {/* Welcome Section */}
            <div className="bg-gradient-to-br from-primary/5 via-primary/3 to-transparent rounded-2xl p-4 sm:p-6 border border-primary/10">
              <h1 className="text-lg sm:text-xl font-bold text-gray-800 mb-1">
                {t("welcome_title")}
              </h1>
              <p className="text-xs sm:text-sm text-gray-500">
                {t("welcome_subtitle")}
              </p>
            </div>

            {/* Stats Cards */}
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4">
              <div className="dashboard-stat-card card-hover p-4 sm:p-5 text-center">
                <div className="text-2xl sm:text-3xl font-bold text-primary mb-1">
                  <AnimatedCounter value={stats.offers_count} duration={1500} />
                </div>
                <div className="text-xs sm:text-sm text-gray-500 font-medium">
                  {t("stats.offers")}
                </div>
              </div>
              {/*   <div className="dashboard-stat-card card-hover p-4 sm:p-5 text-center">
                <div className="text-2xl sm:text-3xl font-bold text-primary mb-1">
                  <AnimatedCounter
                    value={stats.auctions_count}
                    duration={1500}
                  />
                </div>
                <div className="text-xs sm:text-sm text-gray-500 font-medium">
                  {t("stats.auctions")}
                </div>
              </div> */}
              <div className="dashboard-stat-card card-hover p-4 sm:p-5 text-center">
                <div className="text-2xl sm:text-3xl font-bold text-primary mb-1">
                  <AnimatedCounter
                    value={stats.single_auctions_count}
                    duration={1500}
                  />
                </div>
                <div className="text-xs sm:text-sm text-gray-500 font-medium">
                  {t("stats.single_auctions")}
                </div>
              </div>
            </div>

            {/* Quick Actions */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              <button
                onClick={() => handleTabChange("add")}
                className="dashboard-card card-hover p-4 text-center group"
              >
                <div className="w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-2 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors">
                  <span className="text-lg sm:text-xl">➕</span>
                </div>
                <span className="text-xs sm:text-sm font-medium text-gray-700">
                  {t("add_listing")}
                </span>
              </button>
              <button
                onClick={() => handleTabChange("auctions")}
                className="dashboard-card card-hover p-4 text-center group"
              >
                <div className="w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-2 rounded-xl bg-amber-500/10 flex items-center justify-center group-hover:bg-amber-500/20 transition-colors">
                  <span className="text-lg sm:text-xl">🔨</span>
                </div>
                <span className="text-xs sm:text-sm font-medium text-gray-700">
                  {t("my_auctions")}
                </span>
              </button>
              <button
                onClick={() => handleTabChange("wallet")}
                className="dashboard-card card-hover p-4 text-center group"
              >
                <div className="w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-2 rounded-xl bg-green-500/10 flex items-center justify-center group-hover:bg-green-500/20 transition-colors">
                  <span className="text-lg sm:text-xl">💰</span>
                </div>
                <span className="text-xs sm:text-sm font-medium text-gray-700">
                  {t("wallet")}
                </span>
              </button>
              <button
                onClick={() => handleTabChange("profile")}
                className="dashboard-card card-hover p-4 text-center group"
              >
                <div className="w-10 h-10 sm:w-12 sm:h-12 mx-auto mb-2 rounded-xl bg-blue-500/10 flex items-center justify-center group-hover:bg-blue-500/20 transition-colors">
                  <span className="text-lg sm:text-xl">👤</span>
                </div>
                <span className="text-xs sm:text-sm font-medium text-gray-700">
                  {t("profile")}
                </span>
              </button>
            </div>
          </div>
        );
    }
  };

  return (
    <div className="dashboard-container min-h-screen">
      <div className="max-w-7xl mx-auto px-3 sm:px-4 py-4 sm:py-8">
        {/* Mobile Tabs - Horizontal Scroll (scrollable without visible scrollbar) */}
        <div className="lg:hidden mb-4 sticky top-6 z-20">
          <div className="dashboard-sidebar rounded-2xl p-2 overflow-x-auto hide-scrollbar border border-slate-200 bg-[#f8fafc]">
            <div className="flex gap-1.5 min-w-max">
              {tabs.map((tab) => (
                <button
                  key={tab.key}
                  onClick={() => handleTabChange(tab.key)}
                  className={`dashboard-tab px-3 sm:px-4 text-xs sm:text-sm font-medium whitespace-nowrap rounded-lg border transition-colors ${selected === tab.key
                    ? "py-2.5 sm:py-3 min-h-[2.5rem] sm:min-h-[2.75rem] bg-[#eaf2ff] text-[#2563eb] border-[#c9dcff]"
                    : "py-2 sm:py-2.5 text-slate-600 border-transparent bg-transparent hover:bg-slate-100"
                    }`}
                >
                  {tab.title}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Desktop: fixed viewport band; main column scrolls inside (overflow-y) */}
        <div className="flex gap-4 sm:gap-6 mt-3 sm:mt-4 lg:h-[calc(150vh-9.5rem)] lg:max-h-[calc(150vh-9.5rem)] lg:min-h-0">
          <div className="hidden lg:block w-[220px] shrink-0">
            <div className="dashboard-sidebar rounded-2xl p-3 sticky top-24 border border-slate-200 bg-[#f8fafc] shadow-[0_10px_24px_rgba(15,23,42,0.07)]">
              <div className="mb-3 px-2 py-2.5 rounded-xl bg-white border border-slate-200">
                <div className="flex items-center gap-2">
                  <Image
                    src={brandLogo}
                    alt={brandName}
                    width={30}
                    height={30}
                    className="w-7 h-7 object-contain rounded-sm"
                  />
                  <span className="text-[15px] font-bold text-slate-800 truncate">
                    {brandName}
                  </span>
                </div>
              </div>
              <nav className="flex flex-col">
                {tabs.map((tab) =>
                  (() => {
                    const Icon = tabIcons[tab.key] || Circle;
                    const active = selected === tab.key;
                    return (
                      <button
                        key={tab.key}
                        onClick={() => handleTabChange(tab.key)}
                        className={`dashboard-tab w-full px-3 text-sm font-medium rounded-sm transition-colors border mb-1 ${active
                          ? "dashboard-tab-active-solid py-3.5 min-h-[3.25rem] bg-[#0F5132] text-white border-[#0a3d28]"
                          : "py-2.5 text-slate-600 border-transparent hover:bg-slate-100"
                          }`}
                      >
                        <span
                          className={`flex items-center gap-2 ${isRTL
                            ? "flex-row-reverse justify-end text-right"
                            : "justify-start text-left"
                            }`}
                        >
                          <span className="truncate">{tab.title}</span>
                          <Icon className="w-4 h-4 shrink-0" />
                        </span>
                      </button>
                    );
                  })(),
                )}
              </nav>
            </div>
          </div>

          {/* Main panel: fills row height on lg; scrolls when content is taller */}
          <div className="dashboard-content flex min-h-0 flex-1 flex-col p-4 text-start sm:p-6 rounded-2xl min-w-0 lg:overflow-y-auto lg:overscroll-y-contain">
            {renderTabContent(selected)}
          </div>
        </div>
      </div>
    </div>
  );
}
