"use client";

import { motion } from "framer-motion";
import { useTranslations } from "next-intl";

import type { BillingPeriod } from "@/components/sections/pricing-data";
import { ANNUAL_SAVINGS_PERCENT } from "@/components/sections/pricing-data";
import { cn } from "@/lib/utils";

interface PricingBillingToggleProps {
  billing: BillingPeriod;
  onChange: (billing: BillingPeriod) => void;
  layoutId?: string;
}

export function PricingBillingToggle({
  billing,
  onChange,
  layoutId = "pricing-billing-pill",
}: PricingBillingToggleProps) {
  const t = useTranslations("auto.componentsSectionsPricingBillingToggle");
  return (
    <div className="flex flex-col items-center gap-2">
      <div className="inline-flex rounded-full border border-gray-200 bg-white p-1 shadow-sm">
        {(["monthly", "annual"] as const).map((period) => {
          const isActive = billing === period;
          const label = period === "monthly" ? t("monthly") : t("yearly");
          return (
            <button
              key={period}
              type="button"
              onClick={() => onChange(period)}
              className={cn(
                "relative rounded-full px-6 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-rf-blue focus-visible:ring-offset-2",
                isActive ? "text-white" : "text-neutral-600 hover:text-neutral-900"
              )}
            >
              {isActive ? (
                <motion.span
                  layoutId={layoutId}
                  className="absolute inset-0 rounded-full bg-rf-blue"
                  transition={{ type: "spring", stiffness: 400, damping: 30 }}
                />
              ) : null}
              <span className="relative z-10">{label}</span>
            </button>
          );
        })}
      </div>
      {billing === "annual" ? (
        <span className="rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-semibold text-green-700">
          {t("savePercent", { percent: ANNUAL_SAVINGS_PERCENT })}
        </span>
      ) : (
        <p className="text-sm text-neutral-400">{t("switchToYearly")}</p>
      )}
    </div>
  );
}
