"use client";

import { useMemo } from "react";
import { Wifi, MapPin, Settings, Calendar, Router } from "lucide-react";
import { usePublicInternetCatalog } from "@/features/services/hooks";
import type {
  InternetPlanCatalogItem,
  InternetInstallationCatalogItem,
} from "@customer-portal/domain/services";
import { Skeleton } from "@/components/atoms/loading-skeleton";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { ServicesBackLink } from "@/features/services/components/base/ServicesBackLink";
import { useServicesBasePath } from "@/features/services/hooks/useServicesBasePath";
import { PublicOfferingCard } from "@/features/services/components/internet/PublicOfferingCard";
import type { TierInfo } from "@/features/services/components/internet/PublicOfferingCard";
import { ServiceHighlights } from "@/features/services/components/base/ServiceHighlights";
import { HowItWorks, type HowItWorksStep } from "@/features/services/components/base/HowItWorks";
import { ServiceCTA } from "@/features/services/components/base/ServiceCTA";
import { ServiceFAQ, type FAQItem } from "@/features/services/components/base/ServiceFAQ";
import {
  OFFERING_CONFIGS,
  TIER_ORDER_MAP,
  getSpeedBadge,
  getTierDescription,
  getTierFeatures,
  INTERNET_FEATURES,
} from "@/features/services/utils";

// Types
interface GroupedOffering {
  offeringType: string;
  title: string;
  speedBadge: string;
  description: string;
  iconType: "home" | "apartment";
  startingPrice: number;
  setupFee: number;
  tiers: TierInfo[];
  isPremium?: boolean;
  showConnectionInfo?: boolean;
}

// FAQ data
const faqItems: FAQItem[] = [
  {
    question: "How can I check if 10Gbps service is available at my address?",
    answer:
      "10Gbps service is currently available in select areas, primarily in Tokyo and surrounding regions. When you check availability with your address, we'll show you exactly which speed options are available at your location.",
  },
  {
    question: "Why do apartment speeds vary by building?",
    answer:
      "Apartment buildings have different NTT fiber infrastructure. Newer buildings often have FTTH (fiber-to-the-home) supporting up to 1Gbps, while older buildings may use VDSL or LAN connections at 100Mbps. The good news: all apartment types have the same monthly price.",
  },
  {
    question: "My home needs multiple WiFi routers for full coverage. Can you help?",
    answer:
      "Yes! Our Platinum tier includes a mesh WiFi system designed for larger homes. During setup, our team will assess your space and recommend the best equipment configuration for full coverage.",
  },
  {
    question: "Can I transfer my existing internet service to Assist Solutions?",
    answer:
      "In most cases, yes. If you already have an NTT line, we can often take over the service without a new installation. Contact us with your current provider details and we'll guide you through the process.",
  },
  {
    question: "What is the contract period?",
    answer:
      "Our standard contract is 2 years. Early termination fees may apply if you cancel before the contract ends. The setup fee can be paid upfront or spread across 12 or 24 monthly installments.",
  },
  {
    question: "How are invoices sent?",
    answer:
      "E-statements (available only in English) will be sent to your primary email address. The service fee will be charged automatically to your registered credit card on file. For corporate plans, please contact us with your requests.",
  },
];

// How It Works steps - reflects actual flow
const internetSteps: HowItWorksStep[] = [
  {
    icon: <MapPin className="h-6 w-6" />,
    title: "Enter Address",
    description: "Submit your address for coverage check",
  },
  {
    icon: <Settings className="h-6 w-6" />,
    title: "We Verify",
    description: "Our team checks with NTT (1-2 days)",
  },
  {
    icon: <Calendar className="h-6 w-6" />,
    title: "Sign Up & Order",
    description: "Create account and select your plan",
  },
  {
    icon: <Router className="h-6 w-6" />,
    title: "Get Connected",
    description: "NTT installs fiber at your home",
  },
];

export interface PublicInternetPlansContentProps {
  onCtaClick?: (e: React.MouseEvent) => void;
  ctaPath?: string;
  ctaLabel?: string;
  heroTitle?: string;
  heroDescription?: string;
}

/**
 * Public Internet Plans Content - Reusable component
 */
export function PublicInternetPlansContent({
  onCtaClick,
  ctaPath: propCtaPath,
  ctaLabel = "Check Availability",
  heroTitle = "Internet Service Plans",
  heroDescription = "NTT Optical Fiber with full English support",
}: PublicInternetPlansContentProps) {
  const { data: servicesCatalog, error } = usePublicInternetCatalog();
  // Simple loading check: show skeleton until we have data or an error
  const isLoading = !servicesCatalog && !error;
  const servicesBasePath = useServicesBasePath();
  const defaultCtaPath = `${servicesBasePath}/internet/configure`;
  const ctaPath = propCtaPath ?? defaultCtaPath;

  // Group services items by offering type
  const groupedOfferings = useMemo(() => {
    if (!servicesCatalog?.plans) return [];

    const plansByType = servicesCatalog.plans.reduce(
      (acc, plan) => {
        const key = plan.internetOfferingType ?? "unknown";
        if (!acc[key]) acc[key] = [];
        acc[key].push(plan);
        return acc;
      },
      {} as Record<string, InternetPlanCatalogItem[]>
    );

    // Get installation item for setup fee
    const installationItem = servicesCatalog.installations?.[0] as
      | InternetInstallationCatalogItem
      | undefined;
    const setupFee = installationItem?.oneTimePrice ?? 22800;

    // Create grouped offerings
    const offerings: GroupedOffering[] = [];

    // Consolidate apartment types (they all have the same price)
    // Connection type (FTTH, VDSL, LAN) depends on building infrastructure
    const apartmentTypes = ["Apartment 1G", "Apartment 100M"];
    const apartmentPlans: InternetPlanCatalogItem[] = [];

    for (const type of apartmentTypes) {
      if (plansByType[type]) {
        apartmentPlans.push(...plansByType[type]);
      }
    }

    // Use shared offering configs with display order override for public view
    const offeringDisplayOrder: Record<string, number> = {
      "Home 10G": 1,
      "Home 1G": 2,
      Apartment: 3,
    };

    // Process Home offerings
    for (const [offeringType, plans] of Object.entries(plansByType)) {
      // Skip apartment types - we'll handle them separately
      if (apartmentTypes.includes(offeringType)) continue;

      const meta = OFFERING_CONFIGS[offeringType];
      if (!meta) continue;

      // Sort plans by tier using shared tier order
      const sortedPlans = [...plans].sort(
        (a, b) =>
          (TIER_ORDER_MAP[a.internetPlanTier ?? ""] ?? 99) -
          (TIER_ORDER_MAP[b.internetPlanTier ?? ""] ?? 99)
      );

      // Calculate starting price
      const startingPrice = Math.min(...sortedPlans.map(p => p.monthlyPrice ?? 0));

      // Get speed from offering type using shared utility
      const speedBadge = getSpeedBadge(offeringType);

      // Build tier info using shared tier descriptions/features (public version)
      const tiers: TierInfo[] = sortedPlans.map(plan => ({
        tier: (plan.internetPlanTier ?? "Silver") as TierInfo["tier"],
        monthlyPrice: plan.monthlyPrice ?? 0,
        description: getTierDescription(plan.internetPlanTier ?? "", true),
        features:
          plan.catalogMetadata?.features ?? getTierFeatures(plan.internetPlanTier ?? "", true),
        pricingNote: plan.internetPlanTier === "Platinum" ? "+ equipment fees" : undefined,
      }));

      offerings.push({
        offeringType,
        title: meta.title,
        speedBadge,
        description: meta.description,
        iconType: meta.iconType,
        startingPrice,
        setupFee,
        tiers,
        isPremium: meta.isPremium,
      });
    }

    // Add consolidated Apartment offering (use any apartment plan for tiers - prices are the same)
    if (apartmentPlans.length > 0) {
      const meta = OFFERING_CONFIGS["Apartment"];

      // Get unique tiers from apartment plans (they all have same prices)
      const uniqueTiers = new Map<string, InternetPlanCatalogItem>();

      for (const plan of apartmentPlans) {
        const tier = plan.internetPlanTier ?? "Silver";
        // Keep first occurrence of each tier (prices are same across apartment types)
        if (!uniqueTiers.has(tier)) {
          uniqueTiers.set(tier, plan);
        }
      }

      const sortedTierPlans = [...uniqueTiers.values()].sort(
        (a, b) =>
          (TIER_ORDER_MAP[a.internetPlanTier ?? ""] ?? 99) -
          (TIER_ORDER_MAP[b.internetPlanTier ?? ""] ?? 99)
      );

      const startingPrice = Math.min(...sortedTierPlans.map(p => p.monthlyPrice ?? 0));

      const tiers: TierInfo[] = sortedTierPlans.map(plan => ({
        tier: (plan.internetPlanTier ?? "Silver") as TierInfo["tier"],
        monthlyPrice: plan.monthlyPrice ?? 0,
        description: getTierDescription(plan.internetPlanTier ?? "", true),
        features:
          plan.catalogMetadata?.features ?? getTierFeatures(plan.internetPlanTier ?? "", true),
        pricingNote: plan.internetPlanTier === "Platinum" ? "+ equipment fees" : undefined,
      }));

      offerings.push({
        offeringType: "Apartment",
        title: meta?.title ?? "Apartment",
        speedBadge: meta?.speedBadge ?? "Up to 1Gbps",
        description:
          meta?.description ??
          "For mansions and apartment buildings. Speed depends on your building.",
        iconType: meta?.iconType ?? "apartment",
        startingPrice,
        setupFee,
        tiers,
        showConnectionInfo: true, // Show the info tooltip for Apartment
      });
    }

    // Sort by display order
    return offerings.sort((a, b) => {
      const orderA = offeringDisplayOrder[a.offeringType] ?? 99;
      const orderB = offeringDisplayOrder[b.offeringType] ?? 99;
      return orderA - orderB;
    });
  }, [servicesCatalog]);

  // Error state
  if (error) {
    return (
      <div className="space-y-6">
        <ServicesBackLink href={servicesBasePath} />
        <AlertBanner variant="error" title="Unable to load plans">
          We couldn&apos;t load internet plans. Please try again later.
        </AlertBanner>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Back link */}
      <ServicesBackLink href={servicesBasePath} />

      {/* Hero - Clean and impactful */}
      <div className="text-center py-6">
        <div
          className="animate-in fade-in slide-in-from-bottom-4 duration-500"
          style={{ animationDelay: "0ms" }}
        >
          <span className="inline-flex items-center gap-2 rounded-full bg-blue-500/10 border border-blue-500/20 px-4 py-1.5 text-sm text-blue-600 dark:text-blue-400 font-medium mb-4">
            <Wifi className="h-4 w-4" />
            NTT Optical Fiber
          </span>
        </div>
        <h1
          className="text-display-md md:text-display-lg font-display text-foreground tracking-tight animate-in fade-in slide-in-from-bottom-6 duration-700"
          style={{ animationDelay: "100ms" }}
        >
          {heroTitle}
        </h1>
        <p
          className="text-lg text-muted-foreground mt-3 max-w-xl mx-auto leading-relaxed animate-in fade-in slide-in-from-bottom-8 duration-700"
          style={{ animationDelay: "200ms" }}
        >
          {heroDescription}
        </p>
      </div>

      {/* Service Highlights - uses cp-stagger-children internally */}
      <section>
        <ServiceHighlights features={INTERNET_FEATURES} />
      </section>

      {/* Connection types section */}
      <section className="space-y-4">
        <div
          className="text-center mb-6 animate-in fade-in slide-in-from-bottom-8 duration-700"
          style={{ animationDelay: "300ms" }}
        >
          <p className="text-sm font-semibold text-primary uppercase tracking-wider mb-2">
            Choose Your Connection
          </p>
          <h2 className="text-display-sm font-display text-foreground">Available Plans</h2>
        </div>

        {isLoading ? (
          <div className="space-y-4">
            {[1, 2, 3].map(i => (
              <Skeleton key={i} className="h-32 w-full rounded-2xl" />
            ))}
          </div>
        ) : (
          <div className="space-y-4 cp-stagger-children">
            {groupedOfferings.map((offering, index) => (
              <PublicOfferingCard
                key={offering.offeringType}
                offeringType={offering.offeringType}
                title={offering.title}
                speedBadge={offering.speedBadge}
                description={offering.description}
                iconType={offering.iconType}
                startingPrice={offering.startingPrice}
                setupFee={offering.setupFee}
                tiers={offering.tiers}
                isPremium={offering.isPremium}
                ctaPath={ctaPath}
                customCtaLabel={ctaLabel}
                onCtaClick={onCtaClick}
                defaultExpanded={index === 0}
                showConnectionInfo={offering.showConnectionInfo}
              />
            ))}
          </div>
        )}
      </section>

      {/* How It Works */}
      <HowItWorks steps={internetSteps} eyebrow="Getting Started" title="How It Works" />

      {/* CTA Section */}
      <ServiceCTA
        eyebrow="Get started in minutes"
        headline="Ready to get connected?"
        description="Enter your address to see what's available at your location"
        primaryAction={{
          label: ctaLabel,
          href: ctaPath,
          onClick: onCtaClick,
        }}
      />

      {/* FAQ Section */}
      <ServiceFAQ items={faqItems} eyebrow="Common Questions" title="Frequently Asked Questions" />
    </div>
  );
}

/**
 * Public Internet Plans page - Marketing/Conversion focused
 * Clean, polished design optimized for conversion
 */
export function PublicInternetPlansView() {
  return (
    <PublicInternetPlansContent
      ctaPath="/services/internet/check-availability"
      ctaLabel="Check Availability"
    />
  );
}
