"use client";
import { Card } from "@/components/ui/card";
import { useTranslations } from "next-intl";
import PackageSelector from "./PackageSelector";
import PackageDurationSelector from "./PackageDurationSelector";
import PackagePrice from "./PackagePrice";
import PackageFeatures from "./PackageFeatures";
import { useWatch, useFormContext } from "react-hook-form";
import { useEffect, useMemo } from "react";
import { Package } from "@/types/package";
import { Info } from "lucide-react";

interface PackageSummaryCardProps {
  packages: Package[];
  // Free trial sign-up: show a fixed, read-only summary of the trial package
  trialPackage?: Package | null;
}

export default function PackageSummaryCard({
  packages,
  trialPackage = null,
}: PackageSummaryCardProps) {
  const t = useTranslations("SubscribePage");
  const { control, setValue } = useFormContext();
  const package_id = useWatch({
    control,
    name: "package_id",
  });
  const pay_type = useWatch({
    control,
    name: "pay_type",
  });

  const selectedPackage = useMemo(() => {
    if (packages.length > 0) {
      return packages.find((pkg) => pkg.uuid === package_id) || null;
    }
    return null;
  }, [package_id, packages]);

  useEffect(() => {
    if (trialPackage) return;
    if (packages.length > 0 && (!package_id || package_id === "")) {
      setValue("package_id", packages[0].uuid);
    }
  }, [package_id, packages, setValue, trialPackage]);

  if (trialPackage) {
    const summaryItems = [
      { label: t("packageName"), value: t("trialPackage") },
      {
        label: t("duration"),
        value: t("trialDuration", {
          days: trialPackage.free_package_days_count ?? 0,
        }),
      },
      { label: t("packageValue"), value: t("free") },
    ];

    return (
      <Card className="gap-5 p-5 lg:p-10">
        <h3 className="text-[16px] sm:text-[20px] md:text-[24px] font-bold">
          {t("packageSummary")}
        </h3>
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-5 bg-vanilla-glass rounded-[8px] border border-secondary-light p-4">
          {summaryItems.map((item) => (
            <div key={item.label} className="flex items-center gap-2 font-bold">
              <span className="text-[14px] sm:text-[16px] md:text-[18px]">
                {item.label} :
              </span>
              <span className="text-[18px] sm:text-[22px] text-secondary-light">
                {item.value}
              </span>
            </div>
          ))}
        </div>
        <p className="flex items-start gap-2 text-[13px] sm:text-[15px] text-white/80">
          <Info className="size-4 sm:size-5 shrink-0 mt-0.5 text-secondary-main" />
          <span>{t("trialSummaryHint")}</span>
        </p>
        <PackageFeatures features={trialPackage.month_properties || []} />
      </Card>
    );
  }

  const isYearly = pay_type === "year";
  const price = isYearly
    ? (selectedPackage?.year_price ?? selectedPackage?.price)
    : (selectedPackage?.month_price ?? selectedPackage?.price);
  // 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 features = isYearly
    ? selectedPackage?.year_properties
    : selectedPackage?.month_properties;
  const otherCycleHasFeatures = isYearly
    ? (selectedPackage?.month_properties?.length ?? 0) > 0
    : (selectedPackage?.year_properties?.length ?? 0) > 0;
  const durationType = isYearly
    ? selectedPackage?.year_price
      ? "year"
      : selectedPackage?.duration_type
    : selectedPackage?.month_price
      ? "month"
      : selectedPackage?.duration_type;

  return (
    <Card className="gap-5 p-5 lg:p-10">
      <h3 className="text-[16px] sm:text-[20px] md:text-[24px] font-bold">
        {t("packageSummary")}
      </h3>
      <div className="flex flex-col gap-6">
        <div className="flex flex-col gap-5 sm:flex-row sm:justify-between items-center bg-vanilla-glass rounded-[8px] border border-secondary-light p-2.5">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
            <PackageSelector packages={packages} />
            <PackageDurationSelector />
          </div>
          <PackagePrice
            price={price || "0"}
            currency={selectedPackage?.currency || ""}
            durationType={durationType || "month"}
          />
        </div>
      </div>
      <PackageFeatures
        features={features || []}
        billingCycle={pay_type}
        otherCycleHasFeatures={otherCycleHasFeatures}
      />
    </Card>
  );
}
