"use client";
import { useState } from "react";
import { Package } from "@/types/package";
import PackageCard from "./PackageCard";
import { cn } from "@/lib/utils";
import { useLocale } from "next-intl";

import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel";

type Props = {
  packages: Package[];
  subscribeText: string;
  mostPopular: string;
  monthlyText: string;
  yearlyText: string;
};

export default function PackagesSliderClient({
  packages,
  subscribeText,
  mostPopular,
  monthlyText,
  yearlyText,
}: Props) {
  const [billingCycle, setBillingCycle] = useState<"month" | "year">("month");
  const locale = useLocale();
  const isRTL = locale === "ar";

  if (!packages?.length) return null;

  // Features are tagged to a single billing cycle — never fall back to the
  // mixed `properties` list, or the other cycle's features leak through.
  const featuresFor = (pkg: Package, isYearly: boolean) =>
    isYearly ? pkg.year_properties ?? [] : pkg.month_properties ?? [];

  const renderPackages = (pkgs: Package[]) => {
    return pkgs.map((pkg, index) => {
      const isYearly = billingCycle === "year";
      const price = isYearly
        ? (pkg.year_price ?? pkg.price)
        : (pkg.month_price ?? pkg.price);
      const features = featuresFor(pkg, isYearly);
      const otherCycleHasFeatures = featuresFor(pkg, !isYearly).length > 0;
      const durationType = isYearly
        ? pkg.year_price
          ? "year"
          : pkg.duration_type
        : pkg.month_price
          ? "month"
          : pkg.duration_type;

      return (
        <PackageCard
          key={pkg.uuid}
          name={pkg.name}
          price={price}
          currency={pkg.currency}
          durationType={durationType}
          features={features}
          subscribeText={subscribeText}
          uuid={pkg.uuid}
          billingCycle={billingCycle}
          otherCycleHasFeatures={otherCycleHasFeatures}
          isPopular={index === 1}
          popularText={index === 1 ? mostPopular : undefined}
        />
      );
    });
  };

  return (
    <div className="w-full flex flex-col items-center">
      {/* Duration Toggle */}
      <div className="relative flex items-center bg-gray-100 border border-gray-200 p-1 rounded-full mb-15 w-fit shadow-inner">
        <div
          className={cn(
            "absolute top-1 bottom-1 w-[calc(50%-4px)] bg-secondary-main rounded-full transition-all duration-300 ease-in-out shadow-md",
            billingCycle === "year"
              ? isRTL
                ? "-translate-x-[calc(100%-0px)]"
                : "translate-x-[calc(100%-0px)]"
              : "translate-x-0",
          )}
        />
        <button
          onClick={() => setBillingCycle("month")}
          className={cn(
            "relative z-10 px-8 py-2.5 rounded-full transition-colors duration-300 font-bold text-[16px] md:text-[18px] cursor-pointer",
            billingCycle === "month"
              ? "text-white"
              : "text-gray-500 hover:text-secondary-main",
          )}
        >
          {monthlyText}
        </button>
        <button
          onClick={() => setBillingCycle("year")}
          className={cn(
            "relative z-10 px-8 py-2.5 rounded-full transition-colors duration-300 font-bold text-[16px] md:text-[18px] cursor-pointer",
            billingCycle === "year"
              ? "text-white"
              : "text-gray-500 hover:text-secondary-main",
          )}
        >
          {yearlyText}
        </button>
      </div>

      {packages.length < 4 ? (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 lg:gap-12 md:justify-items-center w-full">
          {renderPackages(packages)}
        </div>
      ) : (
        <Carousel
          opts={{
            align: "start",
            loop: true,
          }}
          className="w-full flex flex-wrap justify-center gap-5 sm:block"
          dir="ltr"
        >
          <CarouselContent className="-ml-8 lg:-ml-12 pt-10">
            {packages.map((pkg, index) => {
              const isYearly = billingCycle === "year";
              const price = isYearly
                ? (pkg.year_price ?? pkg.price)
                : (pkg.month_price ?? pkg.price);
              const features = featuresFor(pkg, isYearly);
              const otherCycleHasFeatures =
                featuresFor(pkg, !isYearly).length > 0;
              const durationType = isYearly
                ? pkg.year_price
                  ? "year"
                  : pkg.duration_type
                : pkg.month_price
                  ? "month"
                  : pkg.duration_type;

              return (
                <CarouselItem
                  key={pkg.uuid}
                  className="md:basis-1/2 lg:basis-1/3 pl-8 lg:pl-12"
                >
                  <PackageCard
                    name={pkg.name}
                    price={price}
                    currency={pkg.currency}
                    durationType={durationType}
                    features={features}
                    subscribeText={subscribeText}
                    uuid={pkg.uuid}
                    billingCycle={billingCycle}
                    otherCycleHasFeatures={otherCycleHasFeatures}
                    isPopular={index === 1}
                    popularText={index === 1 ? mostPopular : undefined}
                  />
                </CarouselItem>
              );
            })}
          </CarouselContent>
          <CarouselPrevious />
          <CarouselNext />
        </Carousel>
      )}
    </div>
  );
}
