"use client";

import { useMemo, useState, type ElementType, type ReactNode } from "react";
import {
  Smartphone,
  Check,
  Phone,
  Globe,
  ArrowLeft,
  Signal,
  Sparkles,
  CreditCard,
  ChevronDown,
  Info,
  CircleDollarSign,
  TriangleAlert,
  Calendar,
  ArrowRightLeft,
  ArrowRight,
  Users,
} 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 { DeviceCompatibility } from "./DeviceCompatibility";
import {
  ServiceHighlights,
  type HighlightFeature,
} from "@/features/services/components/base/ServiceHighlights";
import { SimHowItWorksSection } from "@/features/services/components/sim/SimHowItWorksSection";

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

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

function CollapsibleSection({
  title,
  icon: Icon,
  defaultOpen = false,
  children,
}: {
  title: string;
  icon: ElementType;
  defaultOpen?: boolean;
  children: ReactNode;
}) {
  const [isOpen, setIsOpen] = useState(defaultOpen);

  return (
    <div className="border border-border rounded-xl overflow-hidden bg-card">
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full flex items-center justify-between p-4 text-left hover:bg-muted/50 transition-colors"
      >
        <div className="flex items-center gap-3">
          <Icon className="w-5 h-5 text-primary" />
          <span className="font-medium text-foreground">{title}</span>
        </div>
        <ChevronDown
          className={`w-5 h-5 text-muted-foreground transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`}
        />
      </button>
      <div
        className={`overflow-hidden transition-all duration-300 ${isOpen ? "max-h-[2000px]" : "max-h-0"}`}
      >
        <div className="p-4 pt-0 border-t border-border">{children}</div>
      </div>
    </div>
  );
}

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: <CreditCard className="h-6 w-6" />,
      title: "Foreign Cards Accepted",
      description: "Use your overseas credit card. No Japanese bank account needed",
      highlight: "Easy payment",
    },
    {
      icon: <Signal className="h-6 w-6" />,
      title: "Japan's Best Network",
      description: "NTT Docomo coverage reaches 99.9% of Japan's population",
      highlight: "Nationwide",
    },
    {
      icon: <CircleDollarSign className="h-6 w-6" />,
      title: "First Month Free",
      description: "Try risk-free. Your first month's basic fee is waived",
      highlight: "Great value",
    },
    {
      icon: <Calendar className="h-6 w-6" />,
      title: "Flexible Terms",
      description: "No multi-year contracts. Stay as long as you need",
      highlight: "No lock-in",
    },
    {
      icon: <ArrowRightLeft className="h-6 w-6" />,
      title: "Keep Your Number",
      description: "Switching from another carrier? Bring your Japanese number with you",
      highlight: "Easy transfer",
    },
    {
      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-4 gap-5">
          {Array.from({ length: 4 }).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="max-w-6xl mx-auto px-4 pb-16 pt-8">
      <ServicesBackLink href={servicesBasePath} label="Back to Services" />

      <div className="text-center pt-8 pb-8">
        <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-primary/10 border border-primary/20 mb-6">
          <Sparkles className="w-4 h-4 text-primary" />
          <span className="text-sm font-medium text-primary">Powered by NTT DOCOMO</span>
        </div>
        <h1 className="text-3xl md:text-4xl font-bold text-foreground mb-4">
          SIM Cards for Foreigners in Japan
        </h1>
        <p className="text-lg text-muted-foreground max-w-2xl mx-auto">
          No hanko, no complicated Japanese forms. Get a SIM card with your foreign credit card and
          English support. eSIM for instant 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>
      )}

      <ServiceHighlights features={simFeatures} className="mb-12" />

      <div className="flex justify-center mb-8">
        <div className="inline-flex rounded-xl bg-muted p-1 border border-border">
          <button
            type="button"
            onClick={() => onTabChange("data-voice")}
            className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-sm font-medium transition-all ${
              activeTab === "data-voice"
                ? "bg-card text-foreground shadow-sm"
                : "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-primary/10 text-primary">
              {plansByType.DataSmsVoice.length}
            </span>
          </button>
          <button
            type="button"
            onClick={() => onTabChange("data-only")}
            className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-sm font-medium transition-all ${
              activeTab === "data-only"
                ? "bg-card text-foreground shadow-sm"
                : "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-primary/10 text-primary">
              {plansByType.DataOnly.length}
            </span>
          </button>
          <button
            type="button"
            onClick={() => onTabChange("voice-only")}
            className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-sm font-medium transition-all ${
              activeTab === "voice-only"
                ? "bg-card text-foreground shadow-sm"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >
            <Check 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-primary/10 text-primary">
              {plansByType.VoiceOnly.length}
            </span>
          </button>
        </div>
      </div>

      <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-4 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-4 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>

      {/* Device Compatibility Section - below plans */}
      <DeviceCompatibility />

      {/* How It Works Section */}
      <div className="mt-12">
        <SimHowItWorksSection />
      </div>

      <div className="mt-8 space-y-4">
        <CollapsibleSection title="Calling & SMS Rates" icon={Phone}>
          <div className="space-y-6 pt-4">
            <div>
              <h4 className="text-sm font-medium text-foreground mb-3 flex items-center gap-2">
                <span className="w-5 h-3 rounded-sm bg-[#BC002D] relative overflow-hidden flex items-center justify-center">
                  <span className="w-2 h-2 rounded-full bg-white" />
                </span>
                Domestic (Japan)
              </h4>
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-muted/50 rounded-lg p-4 border border-border">
                  <div className="text-sm text-muted-foreground mb-1">Voice Calls</div>
                  <div className="text-xl font-bold text-foreground">
                    ¥10<span className="text-sm font-normal text-muted-foreground">/30 sec</span>
                  </div>
                </div>
                <div className="bg-muted/50 rounded-lg p-4 border border-border">
                  <div className="text-sm text-muted-foreground mb-1">SMS</div>
                  <div className="text-xl font-bold text-foreground">
                    ¥3<span className="text-sm font-normal text-muted-foreground">/message</span>
                  </div>
                </div>
              </div>
              <p className="text-xs text-muted-foreground mt-2">
                Incoming calls and SMS are free. Pay-per-use charges billed 5-6 weeks after usage.
              </p>
            </div>

            <div className="p-4 bg-success/5 border border-success/20 rounded-lg">
              <div className="flex items-start gap-3">
                <Phone className="w-5 h-5 text-success mt-0.5" />
                <div>
                  <h4 className="font-medium text-foreground">Unlimited Domestic Calling</h4>
                  <p className="text-sm text-muted-foreground">
                    Add unlimited domestic calls for{" "}
                    <span className="font-semibold text-success">¥3,000/month</span> (available at
                    checkout)
                  </p>
                </div>
              </div>
            </div>

            <div className="text-sm text-muted-foreground">
              <p>
                International calling rates vary by country (¥31-148/30 sec). See{" "}
                <a
                  href="https://www.docomo.ne.jp/service/world/worldcall/call/"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-primary hover:underline"
                >
                  NTT Docomo&apos;s website
                </a>{" "}
                for full details.
              </p>
            </div>
          </div>
        </CollapsibleSection>

        <CollapsibleSection title="Fees & Discounts" icon={CircleDollarSign}>
          <div className="space-y-6 pt-4">
            <div>
              <h4 className="text-sm font-medium text-foreground mb-3">One-time Fees</h4>
              <div className="space-y-3">
                <div className="flex items-center justify-between py-2 border-b border-border">
                  <span className="text-muted-foreground">Activation Fee</span>
                  <span className="font-medium text-foreground">¥1,500</span>
                </div>
                <div className="flex items-center justify-between py-2 border-b border-border">
                  <span className="text-muted-foreground">SIM Replacement (lost/damaged)</span>
                  <span className="font-medium text-foreground">¥1,500</span>
                </div>
                <div className="flex items-center justify-between py-2">
                  <span className="text-muted-foreground">eSIM Re-download</span>
                  <span className="font-medium text-foreground">¥1,500</span>
                </div>
              </div>
            </div>

            <div className="p-4 bg-success/5 border border-success/20 rounded-lg">
              <h4 className="font-medium text-foreground mb-2">Family Discount</h4>
              <p className="text-sm text-muted-foreground">
                <span className="font-semibold text-success">¥300/month off</span> per additional
                Voice SIM on your account
              </p>
            </div>

            <p className="text-xs text-muted-foreground">All prices exclude 10% consumption tax.</p>
          </div>
        </CollapsibleSection>

        <CollapsibleSection title="Important Information & Terms" icon={Info}>
          <div className="space-y-6 pt-4 text-sm">
            <div>
              <h4 className="font-medium text-foreground mb-3 flex items-center gap-2">
                <TriangleAlert className="w-4 h-4 text-warning" />
                Important Notices
              </h4>
              <ul className="space-y-2 text-muted-foreground">
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>
                    ID verification with official documents (name, date of birth, address, photo) is
                    required during checkout.
                  </span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>
                    A compatible unlocked device is required. Check compatibility on our website.
                  </span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>
                    Service may not be available in areas with weak signal. See{" "}
                    <a
                      href="https://www.nttdocomo.co.jp/English/support/area/index.html"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-primary hover:underline"
                    >
                      NTT Docomo coverage map
                    </a>
                    .
                  </span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>
                    SIM is activated as 4G by default. 5G can be requested via your account portal.
                  </span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>
                    International data roaming is not available. Voice/SMS roaming can be enabled
                    upon request (¥50,000/month limit).
                  </span>
                </li>
              </ul>
            </div>

            <div>
              <h4 className="font-medium text-foreground mb-3">Contract Terms</h4>
              <ul className="space-y-2 text-muted-foreground">
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>
                    <strong className="text-foreground">Minimum contract:</strong> 3 full billing
                    months. First month (sign-up to end of month) is free and doesn&apos;t count.
                  </span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>
                    <strong className="text-foreground">Billing cycle:</strong> 1st to end of month.
                    Regular billing starts the 1st of the following month after sign-up.
                  </span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>
                    <strong className="text-foreground">Cancellation:</strong> Can be requested
                    after 3rd month via cancellation form. Monthly fee is incurred in full for
                    cancellation month.
                  </span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>
                    <strong className="text-foreground">SIM return:</strong> SIM card must be
                    returned after service termination.
                  </span>
                </li>
              </ul>
            </div>

            <div>
              <h4 className="font-medium text-foreground mb-3">Additional Options</h4>
              <ul className="space-y-2 text-muted-foreground">
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>Call waiting and voice mail available as separate paid options.</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>Data plan changes are free and take effect next billing month.</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-foreground">•</span>
                  <span>
                    Voice plan changes require new SIM issuance and standard policies apply.
                  </span>
                </li>
              </ul>
            </div>

            <div className="p-4 bg-muted/50 rounded-lg">
              <p className="text-xs text-muted-foreground">
                Payment is by credit card only. Data service is not suitable for activities
                requiring continuous large data transfers. See full Terms of Service for complete
                details.
              </p>
            </div>
          </div>
        </CollapsibleSection>
      </div>

      {/* FAQ Section */}
      <div className="mt-12 mb-8">
        <h2 className="text-2xl font-bold text-foreground mb-6 text-center">
          Frequently Asked Questions
        </h2>
        <div className="space-y-4 max-w-3xl mx-auto">
          <FaqItem
            question="What is the service contract period?"
            answer="The minimum service requirement period is activation month + 3 billing months. After this period, the service will switch to a monthly service and you will be able to cancel at the end of each month."
          />
          <FaqItem
            question="I've changed my phone and the SIM card is not working on the new device."
            answer="Whenever the SIM card is used with a new device, the APN profile would need to be installed on said device. Please refer to the APN Setup Guide in the Documents section to check how the profile can be installed."
          />
          <FaqItem
            question="Are international calling features available?"
            answer={
              <>
                Enter &quot;+&quot; or &quot;010&quot;, &quot;recipient&apos;s country code&quot;,
                and &quot;recipient&apos;s phone number (regular phone number/mobile phone
                number)&quot; → Make a call.
                <br />
                <br />
                If the recipient&apos;s phone number begins with a 0, enter it without the first 0
                (except in some countries and regions).
                <br />
                International calling rate is on the following Docomo&apos;s website:{" "}
                <a
                  href="https://www.docomo.ne.jp/english/service/world/roaming/charges/kaigai/"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-primary hover:underline"
                >
                  Docomo International Calling Rates
                </a>
              </>
            }
          />
          <FaqItem
            question="How do I cancel the service?"
            answer="To cancel, please log into the SonixNet SIM Management Website and send us a cancellation request before the 25th to cancel your account at the end of the month. For example, cancellation requests will need to be sent in by May 25th, in order to cancel at the end of May."
          />
        </div>
      </div>

      <div className="mt-8 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>
  );
}

function FaqItem({ question, answer }: { question: string; answer: React.ReactNode }) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div className="border border-border rounded-xl overflow-hidden bg-card">
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full flex items-start justify-between gap-3 p-4 text-left hover:bg-muted/50 transition-colors"
      >
        <span className="font-medium text-foreground">{question}</span>
        <ChevronDown
          className={`w-5 h-5 text-muted-foreground flex-shrink-0 mt-0.5 transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`}
        />
      </button>
      {isOpen && (
        <div className="px-4 pb-4 text-sm text-muted-foreground leading-relaxed">{answer}</div>
      )}
    </div>
  );
}

export default SimPlansContent;
