"use client";

import { useGetProfileQuery } from "@/api/auth.api";
import MyAccountProfile from "@/components/MyAccount/MyAccountProfile";
import PaymentHistorySection from "@/components/MyAccount/PaymentHistorySection";
import SubscriptionSection from "@/components/MyAccount/SubscriptionSection";
import SubscriptionSummaryCard from "@/components/MyAccount/SubscriptionSummaryCard";
import ErrorCard from "@/components/common/ErrorCard";
import MyAccountSkeleton from "@/components/skeleton/MyAccountSkeleton";
import { useAppSelector } from "@/redux/hooks";
import { useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";

const tabs = [
  { id: "edit-profile", label: "My Account" },
  { id: "subscription", label: "Subscription" },
  { id: "payment-history", label: "Payment History" },
];

const TAB_IDS = new Set(tabs.map((t) => t.id));
const DEFAULT_TAB = "edit-profile";
const SECTION_PARAM = "current-section";

const readInitialTab = (): string => {
  if (typeof window === "undefined") return DEFAULT_TAB;
  const params = new URLSearchParams(window.location.search);
  const section = params.get(SECTION_PARAM);
  return section && TAB_IDS.has(section) ? section : DEFAULT_TAB;
};

export default function MyProfilePage() {
  const [activeTab, setActiveTab] = useState<string>(readInitialTab);
  const searchParams = useSearchParams();
  const { user } = useAppSelector((state) => state.auth);

  useEffect(() => {
    const section = searchParams.get(SECTION_PARAM);
    const tab = section && TAB_IDS.has(section) ? section : DEFAULT_TAB;
    setActiveTab(tab);
  }, [searchParams]);

  const { data, isLoading, error, refetch } = useGetProfileQuery(
    user?.id || "",
    {
      skip: !user?.id,
    },
  );

  const handleTabChange = (tabId: string) => {
    if (tabId === activeTab) return;
    setActiveTab(tabId);
    const params = new URLSearchParams(window.location.search);
    params.set(SECTION_PARAM, tabId);
    window.history.replaceState(
      null,
      "",
      `${window.location.pathname}?${params.toString()}`,
    );
  };

  // The My Account (profile) tab is a two-column layout: the full edit form on
  // the left, a subscription summary on the right (matching the mockup).
  const renderProfileTab = (profileData: NonNullable<typeof data>) => (
    <div className="flex flex-col lg:flex-row gap-6">
      <div className="w-full lg:w-[650px] flex-shrink-0">
        <MyAccountProfile
          userProfile={profileData.userProfile}
          email={profileData.email}
        />
      </div>
      <div className="flex-1 min-w-0">
        <SubscriptionSummaryCard
          userSubscription={profileData.userSubscription}
        />
      </div>
    </div>
  );

  const renderContent = () => {
    if (isLoading) {
      return <MyAccountSkeleton tab={activeTab} />;
    }

    if (error || !data) {
      return (
        <ErrorCard
          message="Failed to load profile data. Please try again."
          onRetry={() => refetch()}
        />
      );
    }

    const profileData = data;

    switch (activeTab) {
      case "subscription": {
        const contact =
          profileData.countryCode && profileData.mobile
            ? `${profileData.countryCode}${profileData.mobile}`
            : (profileData.mobile ?? undefined);
        return (
          <SubscriptionSection
            userSubscription={profileData.userSubscription}
            billingRegion={profileData.userSetting?.billingRegion ?? null}
            prefill={{
              name: profileData.userProfile?.name,
              email: profileData.email,
              contact,
            }}
          />
        );
      }
      case "payment-history":
        return <PaymentHistorySection />;
      case "edit-profile":
      default:
        return renderProfileTab(profileData);
    }
  };

  return (
    <div className="py-6 sm:py-8 lg:py-8 w-full max-w-[1074px] mx-auto px-4 font-system">
      {/* <h1 className="text-black font-semibold text-[24px] sm:text-[28px] lg:text-[32px] leading-[1.2] tracking-[-0.32px] mb-5">
        My Account
      </h1> */}

      {/* Top tab bar */}
      <div className="flex gap-1 border-b border-gray-235 mb-6 overflow-x-auto overflow-y-hidden">
        {tabs.map((tab) => {
          const active = activeTab === tab.id;
          return (
            <button
              key={tab.id}
              onClick={() => handleTabChange(tab.id)}
              className={`relative px-4 py-2.5 text-sm font-semibold! transition-colors whitespace-nowrap ${
                active
                  ? "text-blue-600 after:absolute after:-bottom-px after:left-0 after:right-0 after:h-0.5 after:bg-blue-500"
                  : "text-coolgray-500 hover:text-coolgray-700"
              }`}
            >
              {tab.label}
            </button>
          );
        })}
      </div>

      {/* Content */}
      <div className="w-full">{renderContent()}</div>
    </div>
  );
}
