"use client";

import { useState, useEffect, useMemo } from "react";
import { PageLayout } from "@/components/templates/PageLayout";
import { WifiIcon, ServerIcon, HomeIcon, BuildingOfficeIcon } from "@heroicons/react/24/outline";
import { useInternetCatalog } from "@/features/catalog/hooks";
import { useActiveSubscriptions } from "@/features/subscriptions/hooks/useSubscriptions";
import type {
  InternetPlanCatalogItem,
  InternetInstallationCatalogItem,
} from "@customer-portal/domain/catalog";
import { Skeleton } from "@/components/atoms/loading-skeleton";
import { AsyncBlock } from "@/components/molecules/AsyncBlock/AsyncBlock";
import { InternetPlanCard } from "@/features/catalog/components/internet/InternetPlanCard";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { CatalogBackLink } from "@/features/catalog/components/base/CatalogBackLink";
import { CatalogHero } from "@/features/catalog/components/base/CatalogHero";

export function InternetPlansContainer() {
  const { data, isLoading, error } = useInternetCatalog();
  const plans: InternetPlanCatalogItem[] = useMemo(() => data?.plans ?? [], [data?.plans]);
  const installations: InternetInstallationCatalogItem[] = useMemo(
    () => data?.installations ?? [],
    [data?.installations]
  );
  const [eligibility, setEligibility] = useState<string>("");
  const { data: activeSubs } = useActiveSubscriptions();
  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]
  );

  useEffect(() => {
    if (plans.length > 0) {
      setEligibility(plans[0].internetOfferingType || "Home 1G");
    }
  }, [plans]);

  const getEligibilityIcon = (offeringType?: string) => {
    const lower = (offeringType || "").toLowerCase();
    if (lower.includes("home")) return <HomeIcon className="h-5 w-5" />;
    if (lower.includes("apartment")) return <BuildingOfficeIcon className="h-5 w-5" />;
    return <HomeIcon className="h-5 w-5" />;
  };

  const getEligibilityColor = (offeringType?: string) => {
    const lower = (offeringType || "").toLowerCase();
    if (lower.includes("home")) return "text-blue-600 bg-blue-50 border-blue-200";
    if (lower.includes("apartment")) return "text-green-600 bg-green-50 border-green-200";
    return "text-gray-600 bg-gray-50 border-gray-200";
  };

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

              {/* Title + eligibility */}
              <div className="text-center mb-12">
                <div className="h-10 w-96 bg-gray-200 rounded mx-auto mb-4" />
                <div className="mt-6 inline-flex items-center gap-2 px-6 py-3 rounded-2xl border">
                  <div className="h-5 w-5 bg-gray-200 rounded" />
                  <div className="h-4 w-56 bg-gray-200 rounded" />
                </div>
                <div className="h-4 w-[32rem] max-w-full bg-gray-200 rounded mx-auto mt-2" />
              </div>

              {/* Active internet warning slot */}
              <div className="mb-8 h-20 bg-yellow-50 border border-yellow-200 rounded-xl" />

              {/* 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>

              {/* Important Notes */}
              <div className="mt-12 h-24 bg-blue-50 border border-blue-200 rounded-xl" />
            </div>
          </AsyncBlock>
        </PageLayout>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-slate-50">
      <PageLayout
        title="Internet Plans"
        description="High-speed internet services for your home or business"
        icon={<WifiIcon className="h-6 w-6" />}
      >
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-20">
          <CatalogBackLink href="/catalog" label="Back to Services" />

          <CatalogHero
            title="Choose Your Internet Plan"
            description="High-speed fiber internet with reliable connectivity for your home or business."
          >
            {eligibility && (
              <div className="flex flex-col items-center gap-2 animate-in fade-in duration-300">
                <div
                  className={`inline-flex items-center gap-2 px-4 py-2 rounded-full border-2 ${getEligibilityColor(eligibility)} shadow-sm`}
                >
                  {getEligibilityIcon(eligibility)}
                  <span className="font-semibold">Available for: {eligibility}</span>
                </div>
                <p className="text-sm text-gray-600 text-center max-w-md">
                  Plans shown are tailored to your house type and local infrastructure.
                </p>
              </div>
            )}
          </CatalogHero>

          {hasActiveInternet && (
            <AlertBanner
              variant="warning"
              title="You already have an Internet subscription"
              className="mb-8 animate-in fade-in duration-300"
            >
              <p>
                You already have an Internet subscription with us. If you want another subscription
                for a different residence, please{" "}
                <a
                  href="/support/new"
                  className="underline text-blue-700 hover:text-blue-600 font-medium transition-colors"
                >
                  contact us
                </a>
                .
              </p>
            </AlertBanner>
          )}

          {plans.length > 0 ? (
            <>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 lg:gap-8">
                {plans.map((plan, index) => (
                  <div
                    key={plan.id}
                    className="animate-in fade-in duration-300"
                    style={{ animationDelay: `${index * 50}ms` }}
                  >
                    <InternetPlanCard
                      plan={plan}
                      installations={installations}
                      disabled={hasActiveInternet}
                      disabledReason={
                        hasActiveInternet
                          ? "Already subscribed — contact us to add another residence"
                          : undefined
                      }
                    />
                  </div>
                ))}
              </div>

              <div className="mt-16 animate-in fade-in duration-300">
                <AlertBanner variant="info" title="Important Notes">
                  <ul className="list-disc list-inside space-y-2 text-sm">
                    <li>Theoretical internet speed is the same for all three packages</li>
                    <li>
                      One-time fee (¥22,800) can be paid upfront or in 12- or 24-month installments
                    </li>
                    <li>
                      Home phone line (Hikari Denwa) can be added to GOLD or PLATINUM plans
                      (¥450/month + ¥1,000-3,000 one-time)
                    </li>
                    <li>In-home technical assistance available (¥15,000 onsite visiting fee)</li>
                  </ul>
                </AlertBanner>
              </div>
            </>
          ) : (
            <div className="text-center py-16 animate-in fade-in duration-300">
              <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-12 max-w-md mx-auto">
                <ServerIcon className="h-16 w-16 text-gray-400 mx-auto mb-6" />
                <h3 className="text-xl font-semibold text-gray-900 mb-2">No Plans Available</h3>
                <p className="text-gray-600 mb-8">
                  We couldn&apos;t find any internet plans available for your location at this time.
                </p>
                <CatalogBackLink
                  href="/catalog"
                  label="Back to Services"
                  align="center"
                  className="mt-0 mb-0"
                />
              </div>
            </div>
          )}
        </div>
      </PageLayout>
    </div>
  );
}

// InternetPlanCard extracted to components/internet/InternetPlanCard
