"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import type { SimCatalogProduct } from "@customer-portal/domain/services";
import { useAccountSimCatalog } from "@/features/services/hooks";
import { useServicesBasePath } from "@/features/services/hooks/useServicesBasePath";
import { useCatalogStore } from "@/features/services/stores/services.store";
import {
  SimPlansContent,
  type SimPlansTab,
} from "@/features/services/components/sim/SimPlansContent";

/**
 * Account SIM Plans Container
 *
 * Fetches account context (payment methods + personalised catalog) and
 * renders the shared SIM plans UI.
 */
export function SimPlansContainer() {
  const router = useRouter();
  const servicesBasePath = useServicesBasePath();
  const { data, error } = useAccountSimCatalog();
  const plans: SimCatalogProduct[] = useMemo(() => data?.plans ?? [], [data?.plans]);
  // Simple loading check: show skeleton until we have data or an error
  const isLoading = !data && !error;
  const [activeTab, setActiveTab] = useState<SimPlansTab>("data-voice");

  const handleSelectPlan = (planSku: string) => {
    const { resetSimConfig, setSimConfig } = useCatalogStore.getState();
    resetSimConfig();
    setSimConfig({ planSku, currentStep: 1 });
    router.push(`${servicesBasePath}/sim/configure?planSku=${encodeURIComponent(planSku)}`);
  };

  return (
    <SimPlansContent
      variant="account"
      plans={plans}
      isLoading={isLoading}
      error={error}
      activeTab={activeTab}
      onTabChange={setActiveTab}
      onSelectPlan={handleSelectPlan}
    />
  );
}

export default SimPlansContainer;
