"use client";

import { useMemo } from "react";
import {
  Smartphone,
  Phone,
  Globe,
  ArrowLeft,
  Signal,
  CreditCard,
  CircleDollarSign,
  Calendar,
  ArrowRightLeft,
  ArrowRight,
  Users,
  FileCheck,
  Send,
  CheckCircle,
} from "lucide-react";
import { Skeleton } from "@/components/atoms/loading-skeleton";
import { Button } from "@/components/atoms/button";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import type { SimCatalogProduct } from "@customer-portal/domain/services";
import { ServicesBackLink } from "@/features/services/components/base/ServicesBackLink";
import { useServicesBasePath } from "@/features/services/hooks/useServicesBasePath";
import { CardPricing } from "@/features/services/components/base/CardPricing";
import {
  ServiceHighlights,
  type HighlightFeature,
} 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";

export type SimPlansTab = "data-voice" | "data-only" | "voice-only";

interface PlansByType {
  DataOnly: SimCatalogProduct[];
  DataSmsVoice: SimCatalogProduct[];
  VoiceOnly: SimCatalogProduct[];
}

// SIM FAQ items - consolidated from the collapsible sections
const simFaqItems: FAQItem[] = [
  {
    question: "What are the calling and SMS rates?",
    answer:
      "Domestic voice calls are ¥10/30 seconds, SMS is ¥3/message. Incoming calls and SMS are free. You can add unlimited domestic calling for ¥3,000/month at checkout. International rates vary by country (¥31-148/30 sec).",
  },
  {
    question: "What fees should I expect?",
    answer:
      "Activation fee is ¥1,500 (one-time). SIM replacement or eSIM re-download is also ¥1,500 if needed. Family discount gives ¥300/month off per additional Voice SIM on your account. All prices exclude 10% consumption tax.",
  },
  {
    question: "What is the contract period?",
    answer:
      "Minimum contract is 3 full billing months. First month (sign-up to end of month) is free and doesn't count. You can request cancellation after the 3rd month. Monthly fee is incurred in full for the cancellation month.",
  },
  {
    question: "What do I need to get started?",
    answer:
      "You'll need: (1) Valid ID with name, DOB, address and photo for verification, (2) A compatible unlocked device, (3) Credit card for payment. SIM is activated as 4G by default; 5G can be requested via your account portal.",
  },
  {
    question: "Can I keep my current phone number?",
    answer:
      "Yes! We support number portability (MNP). You can transfer your existing Japanese phone number when signing up. The process is handled during checkout and typically takes 1-2 business days.",
  },
  {
    question: "Can I use my SIM abroad?",
    answer:
      "International data roaming is not available. Voice/SMS roaming can be enabled upon request with a ¥50,000/month limit. We recommend using local SIMs or eSIMs for international travel.",
  },
];

// How It Works steps for SIM - no eligibility check needed
const simSteps: HowItWorksStep[] = [
  {
    icon: <Signal className="h-6 w-6" />,
    title: "Choose Plan",
    description: "Select your data and voice options",
  },
  {
    icon: <FileCheck className="h-6 w-6" />,
    title: "Create Account",
    description: "Sign up with email verification",
  },
  {
    icon: <Send className="h-6 w-6" />,
    title: "Place Order",
    description: "Configure SIM type and pay",
  },
  {
    icon: <CheckCircle className="h-6 w-6" />,
    title: "Get Connected",
    description: "Receive SIM and activate",
  },
];

function SimPlanCardCompact({
  plan,
  isFamily,
  onSelect,
}: {
  plan: SimCatalogProduct;
  isFamily?: boolean;
  onSelect: (sku: string) => void;
}) {
  const displayPrice = plan.monthlyPrice ?? plan.unitPrice ?? plan.oneTimePrice ?? 0;

  return (
    <div
      className={`group relative bg-card rounded-2xl p-5 transition-all duration-200 ${
        isFamily
          ? "border-2 border-success/50 hover:border-success hover:shadow-[var(--cp-shadow-2)]"
          : "border border-border hover:border-primary/50 hover:shadow-[var(--cp-shadow-2)]"
      }`}
    >
      {isFamily && (
        <div className="absolute -top-3 left-4 flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-success text-success-foreground text-xs font-medium">
          <Users className="w-3.5 h-3.5" />
          Family Discount
        </div>
      )}

      <div className="flex items-center justify-between mb-4 mt-1">
        <div className="flex items-center gap-2">
          <div
            className={`w-10 h-10 rounded-xl flex items-center justify-center ${
              isFamily ? "bg-success/10" : "bg-primary/10"
            }`}
          >
            <Signal className={`w-5 h-5 ${isFamily ? "text-success" : "text-primary"}`} />
          </div>
          <span className="text-lg font-bold text-foreground">{plan.simDataSize}</span>
        </div>
      </div>

      <div className="mb-4">
        <CardPricing monthlyPrice={displayPrice} size="sm" alignment="left" />
        {isFamily && (
          <div className="text-xs text-success font-medium mt-1">Discounted price applied</div>
        )}
      </div>

      <p className="text-sm text-muted-foreground mb-5 line-clamp-2">{plan.name}</p>

      <Button
        className={`w-full ${
          isFamily
            ? "group-hover:bg-success group-hover:text-success-foreground"
            : "group-hover:bg-primary group-hover:text-primary-foreground"
        }`}
        variant="outline"
        onClick={() => onSelect(plan.sku)}
        rightIcon={<ArrowRight className="w-4 h-4" />}
      >
        Select Plan
      </Button>
    </div>
  );
}

export function SimPlansContent({
  variant,
  plans,
  isLoading,
  error,
  activeTab,
  onTabChange,
  onSelectPlan,
}: {
  variant: "public" | "account";
  plans: SimCatalogProduct[];
  isLoading: boolean;
  error: unknown;
  activeTab: SimPlansTab;
  onTabChange: (tab: SimPlansTab) => void;
  onSelectPlan: (sku: string) => void;
}) {
  const servicesBasePath = useServicesBasePath();

  const simPlans: SimCatalogProduct[] = useMemo(() => plans ?? [], [plans]);
  const hasExistingSim = useMemo(() => simPlans.some(p => p.simHasFamilyDiscount), [simPlans]);

  const simFeatures: HighlightFeature[] = [
    {
      icon: <Signal className="h-6 w-6" />,
      title: "NTT Docomo Network",
      description: "Best area coverage among the main three carriers in Japan",
      highlight: "Nationwide coverage",
    },
    {
      icon: <CircleDollarSign className="h-6 w-6" />,
      title: "First Month Free",
      description: "Basic fee waived on signup to get you started risk-free",
      highlight: "Great value",
    },
    {
      icon: <CreditCard className="h-6 w-6" />,
      title: "Foreign Cards Accepted",
      description: "We accept both foreign and Japanese credit cards",
      highlight: "No hassle",
    },
    {
      icon: <Calendar className="h-6 w-6" />,
      title: "No Binding Contract",
      description: "Minimum 4 months service (1st month free + 3 billing months)",
      highlight: "Flexible contract",
    },
    {
      icon: <ArrowRightLeft className="h-6 w-6" />,
      title: "Number Portability",
      description: "Easily switch to us keeping your current Japanese number",
      highlight: "Keep your number",
    },
    {
      icon: <Smartphone className="h-6 w-6" />,
      title: "Free Plan Changes",
      description: "Switch data plans anytime for the next billing cycle",
      highlight: "Flexibility",
    },
  ];

  if (isLoading) {
    return (
      <div className="max-w-6xl mx-auto px-4 pb-16 pt-8">
        <ServicesBackLink href={servicesBasePath} label="Back to Services" />
        <div className="text-center mb-12 pt-8">
          <Skeleton className="h-10 w-80 mx-auto mb-4" />
          <Skeleton className="h-6 w-96 max-w-full mx-auto" />
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="bg-card rounded-2xl border border-border p-5">
              <div className="flex items-center justify-between mb-6 mt-1">
                <div className="flex items-center gap-2">
                  <Skeleton className="h-10 w-10 rounded-xl" />
                  <Skeleton className="h-6 w-16" />
                </div>
              </div>
              <div className="mb-6 space-y-2">
                <Skeleton className="h-8 w-32" />
              </div>
              <div className="space-y-2 mb-6">
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-3/4" />
              </div>
              <Skeleton className="h-10 w-full rounded-md" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    const errorMessage = error instanceof Error ? error.message : "An unexpected error occurred";
    return (
      <div className="max-w-6xl mx-auto px-4 pb-16 pt-8">
        <ServicesBackLink href={servicesBasePath} label="Back to Services" />
        <div className="rounded-xl bg-destructive/10 border border-destructive/20 p-8 text-center mt-8">
          <div className="text-destructive font-medium text-lg mb-2">Failed to load SIM plans</div>
          <div className="text-destructive/80 text-sm mb-6">{errorMessage}</div>
          <Button as="a" href={servicesBasePath} leftIcon={<ArrowLeft className="w-4 h-4" />}>
            Back to Services
          </Button>
        </div>
      </div>
    );
  }

  const plansByType = simPlans.reduce<PlansByType>(
    (acc, plan) => {
      const planType = plan.simPlanType || "DataOnly";
      if (planType === "DataOnly") acc.DataOnly.push(plan);
      else if (planType === "VoiceOnly") acc.VoiceOnly.push(plan);
      else acc.DataSmsVoice.push(plan);
      return acc;
    },
    { DataOnly: [], DataSmsVoice: [], VoiceOnly: [] }
  );

  const getCurrentPlans = () => {
    const tabPlans =
      activeTab === "data-voice"
        ? plansByType.DataSmsVoice
        : activeTab === "data-only"
          ? plansByType.DataOnly
          : plansByType.VoiceOnly;

    const regularPlans = tabPlans.filter(p => !p.simHasFamilyDiscount);
    const familyPlans = tabPlans.filter(p => p.simHasFamilyDiscount);

    return { regularPlans, familyPlans };
  };

  const { regularPlans, familyPlans } = getCurrentPlans();

  return (
    <div className="space-y-8 pb-16">
      <ServicesBackLink href={servicesBasePath} label="Back to Services" />

      {/* Hero Section */}
      <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-green-500/10 border border-green-500/20 px-4 py-1.5 text-sm text-green-600 dark:text-green-400 font-medium mb-4">
            <Signal className="h-4 w-4" />
            NTT Docomo Network
          </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" }}
        >
          Choose Your SIM Plan
        </h1>
        <p
          className="text-lg text-muted-foreground mt-3 max-w-2xl mx-auto leading-relaxed animate-in fade-in slide-in-from-bottom-8 duration-700"
          style={{ animationDelay: "200ms" }}
        >
          Get connected with Japan&apos;s best network coverage. Choose eSIM for quick digital
          delivery or physical SIM shipped to your door.
        </p>
      </div>

      {variant === "account" && hasExistingSim && (
        <div className="space-y-4 mb-8">
          <AlertBanner variant="success" title="Family Discount Available">
            <p className="text-sm">
              You already have a SIM subscription. Discounted pricing is automatically shown for
              additional lines.
            </p>
          </AlertBanner>
        </div>
      )}

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

      {/* Plans Section Header */}
      <section
        className="animate-in fade-in slide-in-from-bottom-8 duration-700"
        style={{ animationDelay: "400ms" }}
      >
        <div className="text-center mb-6">
          <p className="text-sm font-semibold text-primary uppercase tracking-wider mb-2">
            Select Plan Type
          </p>
          <h2 className="text-display-sm font-display text-foreground">Available Plans</h2>
        </div>

        <div className="flex justify-center mb-8">
          <div className="inline-flex rounded-2xl bg-muted/50 p-1.5 border border-border">
            <button
              type="button"
              onClick={() => onTabChange("data-voice")}
              className={`flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-medium transition-all duration-[var(--cp-duration-normal)] ${
                activeTab === "data-voice"
                  ? "bg-card text-foreground shadow-md"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <Phone className="h-4 w-4" />
              <span className="hidden sm:inline">Data + Voice</span>
              <span className="sm:hidden">All-in</span>
              <span className="text-xs px-1.5 py-0.5 rounded-full bg-green-500/10 text-green-600 dark:text-green-400">
                {plansByType.DataSmsVoice.length}
              </span>
            </button>
            <button
              type="button"
              onClick={() => onTabChange("data-only")}
              className={`flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-medium transition-all duration-[var(--cp-duration-normal)] ${
                activeTab === "data-only"
                  ? "bg-card text-foreground shadow-md"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <Globe className="h-4 w-4" />
              <span className="hidden sm:inline">Data Only</span>
              <span className="sm:hidden">Data</span>
              <span className="text-xs px-1.5 py-0.5 rounded-full bg-green-500/10 text-green-600 dark:text-green-400">
                {plansByType.DataOnly.length}
              </span>
            </button>
            <button
              type="button"
              onClick={() => onTabChange("voice-only")}
              className={`flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-medium transition-all duration-[var(--cp-duration-normal)] ${
                activeTab === "voice-only"
                  ? "bg-card text-foreground shadow-md"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              <Phone className="h-4 w-4" />
              <span className="hidden sm:inline">Voice Only</span>
              <span className="sm:hidden">Voice</span>
              <span className="text-xs px-1.5 py-0.5 rounded-full bg-green-500/10 text-green-600 dark:text-green-400">
                {plansByType.VoiceOnly.length}
              </span>
            </button>
          </div>
        </div>
      </section>

      <div id="plans" className="min-h-[300px]">
        {regularPlans.length > 0 || familyPlans.length > 0 ? (
          <div className="space-y-8 animate-in fade-in duration-300">
            {regularPlans.length > 0 && (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
                {regularPlans.map(plan => (
                  <SimPlanCardCompact key={plan.id} plan={plan} onSelect={onSelectPlan} />
                ))}
              </div>
            )}

            {variant === "account" && hasExistingSim && familyPlans.length > 0 && (
              <div>
                <div className="flex items-center gap-2 mb-4">
                  <Users className="h-5 w-5 text-success" />
                  <h3 className="text-lg font-semibold text-foreground">Family Discount Plans</h3>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
                  {familyPlans.map(plan => (
                    <SimPlanCardCompact
                      key={plan.id}
                      plan={plan}
                      isFamily
                      onSelect={onSelectPlan}
                    />
                  ))}
                </div>
              </div>
            )}
          </div>
        ) : (
          <div className="text-center py-16 text-muted-foreground">
            No plans available in this category.
          </div>
        )}
      </div>

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

      {/* CTA Section */}
      <ServiceCTA
        eyebrow="Get started in minutes"
        headline="Ready to get connected?"
        description="Choose your plan and get connected to Japan's best network"
        primaryAction={{
          label: "View Plans",
          href: "#plans",
          onClick: e => {
            e.preventDefault();
            document.getElementById("plans")?.scrollIntoView({ behavior: "smooth" });
          },
        }}
      />

      {/* FAQ Section */}
      <ServiceFAQ
        items={simFaqItems}
        eyebrow="Common Questions"
        title="Frequently Asked Questions"
      />

      {/* Footer Note */}
      <div className="text-center text-sm text-muted-foreground">
        <p>
          All prices exclude 10% consumption tax.{" "}
          <a href="#" className="text-primary hover:underline">
            View full Terms of Service
          </a>
        </p>
      </div>
    </div>
  );
}

export default SimPlansContent;
