"use client";

import { useEffect, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Server } from "lucide-react";
import { useAccountInternetCatalog, useInternetEligibility } from "@/features/services/hooks";
import { useActiveSubscriptions } from "@/features/subscriptions/hooks/useSubscriptions";
import type {
  InternetPlanCatalogItem,
  InternetInstallationCatalogItem,
} from "@customer-portal/domain/services";
import { Skeleton } from "@/components/atoms/loading-skeleton";
import { AsyncBlock } from "@/components/molecules/AsyncBlock/AsyncBlock";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { ServicesBackLink } from "@/features/services/components/base/ServicesBackLink";
import { useServicesBasePath } from "@/features/services/hooks/useServicesBasePath";
import { InternetImportantNotes } from "@/features/services/components/internet/InternetImportantNotes";
import {
  InternetOfferingCard,
  type TierInfo,
} from "@/features/services/components/internet/InternetOfferingCard";
import { PublicInternetPlansContent } from "@/features/services/views/PublicInternetPlans";
import { PlanComparisonGuide } from "@/features/services/components/internet/PlanComparisonGuide";
import { EligibilityStatusBadge } from "@/features/services/components/internet/EligibilityStatusBadge";
import { InternetPendingState } from "@/features/services/components/internet/InternetPendingState";
import { InternetIneligibleState } from "@/features/services/components/internet/InternetIneligibleState";
import { useAuthSession, useAuthStore } from "@/features/auth/stores/auth.store";
import {
  TIER_ORDER,
  TIER_CONFIGS,
  formatEligibilityDisplay,
  getAvailableOfferings,
} from "@/features/services/utils";

// ============================================================================
// Helper Functions
// ============================================================================

function getTierInfo(plans: InternetPlanCatalogItem[], offeringType: string): TierInfo[] {
  const filtered = plans.filter(p => p.internetOfferingType === offeringType);

  const result: TierInfo[] = [];
  for (const tier of TIER_ORDER) {
    const plan = filtered.find(p => p.internetPlanTier?.toLowerCase() === tier.toLowerCase());
    if (!plan) continue;
    const config = TIER_CONFIGS[tier];
    result.push({
      tier,
      planSku: plan.sku,
      monthlyPrice: plan.monthlyPrice ?? 0,
      description: config.description,
      features: config.features,
      recommended: config.isRecommended ?? false,
      pricingNote: config.pricingNote,
    });
  }
  return result;
}

function getSetupFee(installations: InternetInstallationCatalogItem[]): number {
  const basic = installations.find(i => i.sku?.toLowerCase().includes("basic"));
  return basic?.oneTimePrice ?? 22800;
}

// ============================================================================
// Loading Skeleton Component
// ============================================================================

function InternetPlansLoadingSkeleton({ servicesBasePath }: { servicesBasePath: string }) {
  return (
    <div className="max-w-4xl mx-auto px-4">
      <ServicesBackLink href={servicesBasePath} label="Back to Services" />
      <div className="text-center mb-12">
        <Skeleton className="h-10 w-96 mx-auto mb-4" />
        <Skeleton className="h-4 w-[32rem] max-w-full mx-auto" />
      </div>
      <div className="space-y-4">
        {[1, 2].map(i => (
          <div
            key={i}
            className="bg-card rounded-xl border border-border p-6 shadow-[var(--cp-shadow-1)]"
          >
            <div className="flex items-start gap-4">
              <Skeleton className="h-12 w-12 rounded-xl" />
              <div className="flex-1 space-y-2">
                <Skeleton className="h-6 w-48" />
                <Skeleton className="h-4 w-72" />
                <Skeleton className="h-6 w-32" />
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============================================================================
// Eligible State Component
// ============================================================================

interface EligibleStateProps {
  offeringCards: Array<{
    offeringType: string;
    title: string;
    speedBadge: string;
    description: string;
    iconType: "home" | "apartment";
    isPremium: boolean;
    isAlternative?: boolean | undefined;
    alternativeNote?: string | undefined;
    tiers: TierInfo[];
    startingPrice: number;
    setupFee: number;
    ctaPath: string;
  }>;
  hasActiveInternet: boolean;
  servicesBasePath: string;
}

function InternetEligibleState({
  offeringCards,
  hasActiveInternet,
  servicesBasePath,
}: EligibleStateProps) {
  return (
    <>
      {/* Plan comparison guide */}
      <div className="mb-6">
        <PlanComparisonGuide />
      </div>

      {/* Speed options header (only if multiple) */}
      {offeringCards.length > 1 && (
        <div className="mb-4">
          <h2 className="text-lg font-semibold text-foreground">Choose your speed</h2>
          <p className="text-sm text-muted-foreground">Your address supports multiple options</p>
        </div>
      )}

      {/* Offering cards */}
      <div className="space-y-4 mb-6">
        {offeringCards.map(card => (
          <div key={card.offeringType}>
            {card.isAlternative && (
              <div className="flex items-center gap-2 mb-3">
                <div className="h-px flex-1 bg-border" />
                <span className="text-xs font-medium text-muted-foreground">
                  Alternative option
                </span>
                <div className="h-px flex-1 bg-border" />
              </div>
            )}
            <InternetOfferingCard
              offeringType={card.offeringType}
              title={card.title}
              speedBadge={card.speedBadge}
              description={card.alternativeNote ?? card.description}
              iconType={card.iconType}
              startingPrice={card.startingPrice}
              setupFee={card.setupFee}
              tiers={card.tiers}
              ctaPath={card.ctaPath}
              isPremium={card.isPremium}
              defaultExpanded={false}
              disabled={hasActiveInternet}
              disabledReason={
                hasActiveInternet ? "Contact support for additional lines" : undefined
              }
            />
          </div>
        ))}
      </div>

      {/* Important notes - collapsed by default */}
      <InternetImportantNotes />

      <ServicesBackLink
        href={servicesBasePath}
        label="Back to Services"
        align="center"
        className="mt-10"
      />
    </>
  );
}

// ============================================================================
// No Plans Available Component
// ============================================================================

function NoPlansAvailable({ servicesBasePath }: { servicesBasePath: string }) {
  return (
    <div className="text-center py-16">
      <div className="bg-card rounded-2xl shadow-[var(--cp-shadow-1)] border border-border p-12 max-w-md mx-auto">
        <Server className="h-16 w-16 text-muted-foreground mx-auto mb-6" />
        <h3 className="text-xl font-semibold text-foreground mb-2">No Plans Available</h3>
        <p className="text-muted-foreground mb-8">
          We couldn&apos;t find any internet plans at this time.
        </p>
        <ServicesBackLink href={servicesBasePath} label="Back to Services" align="center" />
      </div>
    </div>
  );
}

// ============================================================================
// Active Internet Warning Component
// ============================================================================

function ActiveInternetWarning() {
  return (
    <AlertBanner variant="warning" title="Active subscription found" className="mb-6">
      You already have an internet subscription. For additional residences, please{" "}
      <a href="/account/support/new" className="underline font-medium">
        contact support
      </a>
      .
    </AlertBanner>
  );
}

// ============================================================================
// Main Container Component
// ============================================================================

function useInternetPlansData() {
  const { data, error } = useAccountInternetCatalog();
  const isLoading = !data && !error;
  const eligibilityQuery = useInternetEligibility();
  const { data: activeSubs } = useActiveSubscriptions();

  const plans = useMemo(() => data?.plans ?? [], [data?.plans]);
  const installations = useMemo(() => data?.installations ?? [], [data?.installations]);

  const hasActiveInternet = useMemo(
    () =>
      Array.isArray(activeSubs)
        ? activeSubs.some(
            s =>
              String(s.productName || "")
                .toLowerCase()
                .includes("sonixnet via ntt optical fiber") &&
              String(s.status || "").toLowerCase() === "active"
          )
        : false,
    [activeSubs]
  );

  const eligibilityValue = eligibilityQuery.data?.eligibility;
  const eligibilityStatus = eligibilityQuery.data?.status;

  const isEligible =
    eligibilityStatus === "eligible" &&
    typeof eligibilityValue === "string" &&
    eligibilityValue.trim().length > 0;

  const eligibility = useMemo(() => {
    if (!isEligible) return null;
    return eligibilityValue?.trim() ?? null;
  }, [eligibilityValue, isEligible]);

  const setupFee = useMemo(() => getSetupFee(installations), [installations]);
  const availableOfferings = useMemo(() => {
    if (!eligibility) return [];
    return getAvailableOfferings(eligibility, plans);
  }, [eligibility, plans]);

  const eligibilityDisplay = useMemo(() => {
    if (!eligibility) return null;
    return formatEligibilityDisplay(eligibility);
  }, [eligibility]);

  return {
    plans,
    isLoading,
    error,
    eligibilityQuery,
    hasActiveInternet,
    eligibilityStatus,
    isEligible,
    isPending: eligibilityStatus === "pending",
    isNotRequested: eligibilityStatus === "not_requested",
    isIneligible: eligibilityStatus === "ineligible",
    eligibility,
    setupFee,
    availableOfferings,
    eligibilityDisplay,
    requestedAt: eligibilityQuery.data?.requestedAt,
    rejectionNotes: eligibilityQuery.data?.notes,
  };
}

function InternetPlansPortalView({
  data,
  servicesBasePath,
}: {
  data: ReturnType<typeof useInternetPlansData>;
  servicesBasePath: string;
}) {
  const {
    plans,
    eligibilityQuery,
    hasActiveInternet,
    isEligible,
    isPending,
    isIneligible,
    isLoading,
    eligibilityDisplay,
    requestedAt,
    rejectionNotes,
  } = data;

  const offeringCards = useMemo(() => {
    return data.availableOfferings
      .map(config => {
        const tiers = getTierInfo(plans, config.offeringType);
        const startingPrice = tiers.length > 0 ? Math.min(...tiers.map(t => t.monthlyPrice)) : 0;
        return {
          ...config,
          tiers,
          startingPrice,
          setupFee: data.setupFee,
          ctaPath: `${servicesBasePath}/internet/configure`,
        };
      })
      .filter(card => card.tiers.length > 0);
  }, [data.availableOfferings, plans, data.setupFee, servicesBasePath]);

  const currentStatus = (() => {
    if (isEligible) return "eligible";
    if (isPending) return "pending";
    if (isIneligible) return "ineligible";
    return "not_requested";
  })();

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 pb-20 pt-8">
      <ServicesBackLink href={servicesBasePath} label="Back to Services" className="mb-6" />
      <div className="text-center mb-8">
        <h1 className="text-2xl md:text-3xl font-bold text-foreground mb-2">
          Your Internet Options
        </h1>
        <p className="text-muted-foreground mb-4">
          Plans tailored to your residence and available infrastructure
        </p>
        {!eligibilityQuery.isLoading && (
          <EligibilityStatusBadge status={currentStatus} speed={eligibilityDisplay?.speed} />
        )}
        {eligibilityQuery.isLoading && (
          <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full border border-border bg-muted">
            <div className="h-4 w-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
            <span className="font-medium text-sm text-foreground">Checking status...</span>
          </div>
        )}
      </div>
      {hasActiveInternet && <ActiveInternetWarning />}
      {isEligible && eligibilityDisplay && offeringCards.length > 0 && (
        <InternetEligibleState
          offeringCards={offeringCards}
          hasActiveInternet={hasActiveInternet}
          servicesBasePath={servicesBasePath}
        />
      )}
      {isPending && (
        <InternetPendingState requestedAt={requestedAt} servicesBasePath={servicesBasePath} />
      )}
      {isIneligible && <InternetIneligibleState rejectionNotes={rejectionNotes} />}
      {plans.length === 0 && !isLoading && <NoPlansAvailable servicesBasePath={servicesBasePath} />}
    </div>
  );
}

export function InternetPlansContainer() {
  const router = useRouter();
  const servicesBasePath = useServicesBasePath();
  const searchParams = useSearchParams();
  const { user } = useAuthSession();
  const hasCheckedAuth = useAuthStore(state => state.hasCheckedAuth);
  const data = useInternetPlansData();

  const autoEligibilityRequest = searchParams?.get("autoEligibilityRequest") === "1";
  const autoPlanSku = searchParams?.get("planSku");

  useEffect(() => {
    if (!autoEligibilityRequest || !hasCheckedAuth || !user) return;
    const params = new URLSearchParams();
    if (autoPlanSku) params.set("planSku", autoPlanSku);
    params.set("autoEligibilityRequest", "1");
    const query = params.toString();
    const queryString = query.length > 0 ? `?${query}` : "";
    router.replace(`${servicesBasePath}/internet/request${queryString}`);
  }, [autoEligibilityRequest, autoPlanSku, hasCheckedAuth, servicesBasePath, user, router]);

  if (data.isLoading || data.error) {
    return (
      <div className="max-w-4xl mx-auto px-4 pt-8">
        <AsyncBlock isLoading={false} error={data.error}>
          <InternetPlansLoadingSkeleton servicesBasePath={servicesBasePath} />
        </AsyncBlock>
      </div>
    );
  }

  if (data.isNotRequested) {
    const handleCheckAvailability = (e?: React.MouseEvent) => {
      if (e) e.preventDefault();
      router.push(`${servicesBasePath}/internet/request`);
    };
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 pb-20 pt-8">
        {data.hasActiveInternet && <ActiveInternetWarning />}
        <PublicInternetPlansContent
          onCtaClick={handleCheckAvailability}
          ctaLabel="Check Availability"
        />
      </div>
    );
  }

  return <InternetPlansPortalView data={data} servicesBasePath={servicesBasePath} />;
}

export default InternetPlansContainer;
