"use client";

import { useEffect, useMemo, useState } from "react";
import { PageLayout } from "@/components/templates/PageLayout";
import {
  DevicePhoneMobileIcon,
  CheckIcon,
  PhoneIcon,
  GlobeAltIcon,
  ArrowLeftIcon,
} from "@heroicons/react/24/outline";
import { Skeleton } from "@/components/atoms/loading-skeleton";
import { Button } from "@/components/atoms/button";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { useSimCatalog } from "@/features/catalog/hooks";
import type { SimCatalogProduct } from "@customer-portal/domain/catalog";
import { SimPlanTypeSection } from "@/features/catalog/components/sim/SimPlanTypeSection";
import { CatalogBackLink } from "@/features/catalog/components/base/CatalogBackLink";
import { CatalogHero } from "@/features/catalog/components/base/CatalogHero";

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

export function SimPlansContainer() {
  const { data, isLoading, error } = useSimCatalog();
  const simPlans: SimCatalogProduct[] = useMemo(() => data?.plans ?? [], [data?.plans]);
  const [hasExistingSim, setHasExistingSim] = useState(false);
  const [activeTab, setActiveTab] = useState<"data-voice" | "data-only" | "voice-only">(
    "data-voice"
  );

  useEffect(() => {
    setHasExistingSim(simPlans.some(p => p.simHasFamilyDiscount));
  }, [simPlans]);

  if (isLoading) {
    return (
      <div className="min-h-screen bg-slate-50">
        <PageLayout
          title="SIM Plans"
          description="Loading plans..."
          icon={<DevicePhoneMobileIcon className="h-6 w-6" />}
        >
          <div className="max-w-6xl mx-auto px-4">
            <CatalogBackLink href="/catalog" label="Back to Services" />

            {/* Title block */}
            <div className="text-center mb-12">
              <div className="h-10 w-80 bg-gray-200 rounded mx-auto mb-4" />
              <div className="h-6 w-[36rem] max-w-full bg-gray-200 rounded mx-auto" />
            </div>

            {/* Family discount banner slot */}
            <div className="mb-8">
              <div className="h-20 w-full bg-green-50 border border-green-200 rounded-xl" />
            </div>

            {/* Tabs */}
            <div className="mb-8 flex justify-center">
              <div className="h-10 w-[32rem] max-w-full bg-gray-200 rounded" />
            </div>

            {/* Plans grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {Array.from({ length: 6 }).map((_, i) => (
                <div key={i} className="bg-white rounded-xl border border-gray-200 p-6 space-y-3">
                  <Skeleton className="h-6 w-1/2" />
                  <Skeleton className="h-4 w-2/3" />
                  <Skeleton className="h-10 w-full" />
                </div>
              ))}
            </div>

            {/* Terms section */}
            <div className="mt-8 bg-gray-50 rounded-2xl p-8">
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {Array.from({ length: 6 }).map((_, i) => (
                  <div key={i} className="flex items-start gap-3">
                    <div className="h-5 w-5 bg-gray-200 rounded" />
                    <div className="space-y-2 flex-1">
                      <Skeleton className="h-4 w-40" />
                      <Skeleton className="h-3 w-56" />
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Important terms banner */}
            <div className="mt-8 h-28 bg-yellow-50 border border-yellow-200 rounded-xl" />
          </div>
        </PageLayout>
      </div>
    );
  }

  if (error) {
    const errorMessage = error instanceof Error ? error.message : "An unexpected error occurred";
    return (
      <PageLayout
        title="SIM Plans"
        description="Error loading plans"
        icon={<DevicePhoneMobileIcon className="h-6 w-6" />}
      >
        <div className="rounded-lg bg-red-50 border border-red-200 p-6">
          <div className="text-red-800 font-medium">Failed to load SIM plans</div>
          <div className="text-red-600 text-sm mt-1">{errorMessage}</div>
          <Button
            as="a"
            href="/catalog"
            className="mt-4"
            leftIcon={<ArrowLeftIcon className="w-4 h-4" />}
          >
            Back to Services
          </Button>
        </div>
      </PageLayout>
    );
  }

  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: [] }
  );

  return (
    <div className="min-h-screen bg-slate-50">
      <PageLayout
        title="SIM Plans"
        description="Choose your mobile plan with flexible options"
        icon={<DevicePhoneMobileIcon className="h-6 w-6" />}
      >
        <div className="max-w-6xl mx-auto px-4 pb-16">
          <CatalogBackLink href="/catalog" label="Back to Services" />

          <CatalogHero
            title="Choose Your SIM Plan"
            description="Flexible mobile plans with physical SIM and eSIM options for any device."
          />

          {hasExistingSim && (
            <AlertBanner variant="success" title="Family Discount Applied" className="mb-8">
              <div className="space-y-2">
                <p>
                  You already have a SIM subscription with us. Family discount pricing is
                  automatically applied to eligible additional lines below.
                </p>
                <ul className="list-disc list-inside">
                  <li>Reduced monthly pricing automatically reflected</li>
                  <li>Same great features</li>
                  <li>Easy to manage multiple lines</li>
                </ul>
              </div>
            </AlertBanner>
          )}

          <div className="mb-8 flex justify-center">
            <div className="border-b border-gray-200">
              <nav className="-mb-px flex space-x-6" aria-label="Tabs">
                <button
                  onClick={() => setActiveTab("data-voice")}
                  className={`py-2 px-1 border-b-2 font-medium text-sm flex items-center gap-2 transition-colors duration-200 ${
                    activeTab === "data-voice"
                      ? "border-blue-500 text-blue-600"
                      : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                  }`}
                >
                  <PhoneIcon className="h-5 w-5" />
                  Data + SMS + Voice
                  {plansByType.DataSmsVoice.length > 0 && (
                    <span
                      className={`text-xs font-semibold px-2 py-0.5 rounded-full border ${
                        activeTab === "data-voice"
                          ? "border-blue-100 bg-blue-50 text-blue-600"
                          : "border-gray-200 text-gray-500"
                      }`}
                    >
                      {plansByType.DataSmsVoice.length}
                    </span>
                  )}
                </button>
                <button
                  onClick={() => setActiveTab("data-only")}
                  className={`py-2 px-1 border-b-2 font-medium text-sm flex items-center gap-2 transition-colors duration-200 ${
                    activeTab === "data-only"
                      ? "border-blue-500 text-blue-600"
                      : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                  }`}
                >
                  <GlobeAltIcon className="h-5 w-5" />
                  Data Only
                  {plansByType.DataOnly.length > 0 && (
                    <span
                      className={`text-xs font-semibold px-2 py-0.5 rounded-full border ${
                        activeTab === "data-only"
                          ? "border-blue-100 bg-blue-50 text-blue-600"
                          : "border-gray-200 text-gray-500"
                      }`}
                    >
                      {plansByType.DataOnly.length}
                    </span>
                  )}
                </button>
                <button
                  onClick={() => setActiveTab("voice-only")}
                  className={`py-2 px-1 border-b-2 font-medium text-sm flex items-center gap-2 transition-colors duration-200 ${
                    activeTab === "voice-only"
                      ? "border-blue-500 text-blue-600"
                      : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                  }`}
                >
                  <CheckIcon className="h-5 w-5" />
                  Voice Only
                  {plansByType.VoiceOnly.length > 0 && (
                    <span
                      className={`text-xs font-semibold px-2 py-0.5 rounded-full border ${
                        activeTab === "voice-only"
                          ? "border-blue-100 bg-blue-50 text-blue-600"
                          : "border-gray-200 text-gray-500"
                      }`}
                    >
                      {plansByType.VoiceOnly.length}
                    </span>
                  )}
                </button>
              </nav>
            </div>
          </div>

          <div className="min-h-[500px] relative">
            {activeTab === "data-voice" && (
              <div className="animate-in fade-in duration-300">
                <SimPlanTypeSection
                  title="Data + SMS + Voice Plans"
                  description={
                    hasExistingSim
                      ? "Family discount shown where eligible"
                      : "Comprehensive plans with high-speed data, messaging, and calling"
                  }
                  icon={<DevicePhoneMobileIcon className="h-6 w-6 text-blue-600" />}
                  plans={plansByType.DataSmsVoice}
                  showFamilyDiscount={hasExistingSim}
                />
              </div>
            )}
            {activeTab === "data-only" && (
              <div className="animate-in fade-in duration-300">
                <SimPlanTypeSection
                  title="Data Only Plans"
                  description={
                    hasExistingSim
                      ? "Family discount shown where eligible"
                      : "Flexible data-only plans for internet usage"
                  }
                  icon={<GlobeAltIcon className="h-6 w-6 text-purple-600" />}
                  plans={plansByType.DataOnly}
                  showFamilyDiscount={hasExistingSim}
                />
              </div>
            )}
            {activeTab === "voice-only" && (
              <div className="animate-in fade-in duration-300">
                <SimPlanTypeSection
                  title="Voice + SMS Only Plans"
                  description={
                    hasExistingSim
                      ? "Family discount shown where eligible"
                      : "Plans focused on voice calling and messaging without data bundles"
                  }
                  icon={<PhoneIcon className="h-6 w-6 text-orange-600" />}
                  plans={plansByType.VoiceOnly}
                  showFamilyDiscount={hasExistingSim}
                />
              </div>
            )}
          </div>

          <div className="mt-8 bg-gray-50 rounded-2xl p-8 max-w-4xl mx-auto">
            <h3 className="font-bold text-gray-900 text-xl mb-6 text-center">
              Plan Features & Terms
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 text-sm">
              <div className="flex items-start gap-3">
                <CheckIcon className="h-5 w-5 text-green-500 mt-0.5 flex-shrink-0" />
                <div>
                  <div className="font-medium text-gray-900">3-Month Contract</div>
                  <div className="text-gray-600">Minimum 3 billing months</div>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <CheckIcon className="h-5 w-5 text-green-500 mt-0.5 flex-shrink-0" />
                <div>
                  <div className="font-medium text-gray-900">First Month Free</div>
                  <div className="text-gray-600">Basic fee waived initially</div>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <CheckIcon className="h-5 w-5 text-green-500 mt-0.5 flex-shrink-0" />
                <div>
                  <div className="font-medium text-gray-900">5G Network</div>
                  <div className="text-gray-600">High-speed coverage</div>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <CheckIcon className="h-5 w-5 text-green-500 mt-0.5 flex-shrink-0" />
                <div>
                  <div className="font-medium text-gray-900">eSIM Support</div>
                  <div className="text-gray-600">Digital activation</div>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <CheckIcon className="h-5 w-5 text-green-500 mt-0.5 flex-shrink-0" />
                <div>
                  <div className="font-medium text-gray-900">Family Discounts</div>
                  <div className="text-gray-600">Multi-line savings</div>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <CheckIcon className="h-5 w-5 text-green-500 mt-0.5 flex-shrink-0" />
                <div>
                  <div className="font-medium text-gray-900">Plan Switching</div>
                  <div className="text-gray-600">Free data plan changes</div>
                </div>
              </div>
            </div>
          </div>

          <AlertBanner
            variant="info"
            title="Important Terms & Conditions"
            className="mt-8 max-w-4xl mx-auto"
          >
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
              <div className="space-y-3">
                <div>
                  <div className="font-medium">Contract Period</div>
                  <p>
                    Minimum 3 full billing months required. First month (sign-up to end of month) is
                    free and doesn&apos;t count toward contract.
                  </p>
                </div>
                <div>
                  <div className="font-medium">Billing Cycle</div>
                  <p>
                    Monthly billing from 1st to end of month. Regular billing starts on 1st of
                    following month after sign-up.
                  </p>
                </div>
                <div>
                  <div className="font-medium">Cancellation</div>
                  <p>
                    Can be requested online after 3rd month. Service terminates at end of billing
                    cycle.
                  </p>
                </div>
              </div>
              <div className="space-y-3">
                <div>
                  <div className="font-medium">Plan Changes</div>
                  <p>
                    Data plan switching is free and takes effect next month. Voice plan changes
                    require new SIM and cancellation policies apply.
                  </p>
                </div>
                <div>
                  <div className="font-medium">Calling/SMS Charges</div>
                  <p>
                    Pay-per-use charges apply separately. Billed 5-6 weeks after usage within
                    billing cycle.
                  </p>
                </div>
                <div>
                  <div className="font-medium">SIM Replacement</div>
                  <p>
                    Reissue fee of 1,500 JPY applies for damaged, lost, or replacement SIM cards.
                  </p>
                </div>
              </div>
            </div>
          </AlertBanner>
        </div>
      </PageLayout>
    </div>
  );
}

export default SimPlansContainer;
