"use client";

import { useEffect, useMemo, useRef } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useInternetCatalog, useInternetPlan } from ".";
import { useCatalogStore } from "../services/catalog.store";
import type { AccessModeValue } from "@customer-portal/domain/orders";
import type {
  InternetPlanCatalogItem,
  InternetInstallationCatalogItem,
  InternetAddonCatalogItem,
} from "@customer-portal/domain/catalog";

type InstallationTerm = NonNullable<
  NonNullable<InternetInstallationCatalogItem["catalogMetadata"]>["installationTerm"]
>;

export type UseInternetConfigureResult = {
  plan: InternetPlanCatalogItem | null;
  loading: boolean;
  addons: InternetAddonCatalogItem[];
  installations: InternetInstallationCatalogItem[];

  mode: AccessModeValue | null;
  setMode: (mode: AccessModeValue) => void;
  selectedInstallation: InternetInstallationCatalogItem | null;
  setSelectedInstallationSku: (sku: string | null) => void;
  selectedInstallationType: InstallationTerm | null;
  selectedAddonSkus: string[];
  setSelectedAddonSkus: (skus: string[]) => void;

  currentStep: number;
  setCurrentStep: (step: number) => void;

  buildCheckoutSearchParams: () => URLSearchParams | null;
};

/**
 * Hook for managing internet service configuration state
 * Uses Zustand store for centralized state management with persistence
 */
export function useInternetConfigure(): UseInternetConfigureResult {
  const router = useRouter();
  const searchParams = useSearchParams();
  const paramsSignature = useMemo(() => searchParams.toString(), [searchParams]);
  const urlPlanSku = searchParams.get("plan");

  // Get state from Zustand store (persisted)
  const configState = useCatalogStore(state => state.internet);
  const setConfig = useCatalogStore(state => state.setInternetConfig);
  const restoreFromParams = useCatalogStore(state => state.restoreInternetFromParams);
  const buildParams = useCatalogStore(state => state.buildInternetCheckoutParams);
  const lastRestoredSignatureRef = useRef<string | null>(null);

  // Fetch catalog data from BFF
  const { data: internetData, isLoading: internetLoading } = useInternetCatalog();
  const { plan: selectedPlan } = useInternetPlan(configState.planSku || urlPlanSku || undefined);

  // Initialize/restore state on mount
  useEffect(() => {
    // If URL has plan param but store doesn't, this is a fresh entry
    if (urlPlanSku && configState.planSku !== urlPlanSku) {
      setConfig({ planSku: urlPlanSku });
    }

    // If URL has configuration params (back navigation from checkout), restore them
    const params = new URLSearchParams(paramsSignature);
    const hasConfigParams = params.has("plan") ? params.size > 1 : params.size > 0;
    const shouldRestore =
      hasConfigParams && lastRestoredSignatureRef.current !== paramsSignature && paramsSignature;
    if (shouldRestore) {
      restoreFromParams(params);
      lastRestoredSignatureRef.current = paramsSignature;
    }

    // Redirect if no plan selected
    if (!urlPlanSku && !configState.planSku) {
      router.push("/catalog/internet");
    }
  }, [configState.planSku, paramsSignature, restoreFromParams, router, setConfig, urlPlanSku]);

  // Auto-set default mode for Gold/Platinum plans if not already set
  useEffect(() => {
    if (selectedPlan && !configState.accessMode) {
      if (
        selectedPlan.internetPlanTier === "Gold" ||
        selectedPlan.internetPlanTier === "Platinum"
      ) {
        setConfig({ accessMode: "IPoE-BYOR" });
      }
    }
  }, [selectedPlan, configState.accessMode, setConfig]);

  // Derive catalog items
  const addons = useMemo(() => internetData?.addons ?? [], [internetData]);
  const installations = useMemo(() => internetData?.installations ?? [], [internetData]);

  // Derive selected installation from SKU
  const selectedInstallation = useMemo(() => {
    if (!configState.installationSku) return null;
    return (
      installations.find(installation => installation.sku === configState.installationSku) || null
    );
  }, [installations, configState.installationSku]);

  const selectedInstallationType = useMemo(() => {
    if (!selectedInstallation) return null;
    return selectedInstallation.catalogMetadata?.installationTerm ?? null;
  }, [selectedInstallation]);

  // Wrapper functions for state updates
  const setMode = (mode: AccessModeValue) => {
    setConfig({ accessMode: mode });
  };

  const setSelectedInstallationSku = (sku: string | null) => {
    setConfig({ installationSku: sku });
  };

  const setSelectedAddonSkus = (skus: string[]) => {
    setConfig({ addonSkus: skus });
  };

  const setCurrentStep = (step: number) => {
    setConfig({ currentStep: step });
  };

  return {
    plan: selectedPlan || null,
    loading: internetLoading,
    addons,
    installations,
    mode: configState.accessMode,
    setMode,
    selectedInstallation,
    setSelectedInstallationSku,
    selectedInstallationType,
    selectedAddonSkus: configState.addonSkus,
    setSelectedAddonSkus,
    currentStep: configState.currentStep,
    setCurrentStep,
    buildCheckoutSearchParams: buildParams,
  };
}
