"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Link } from "@/i18n/navigation";
import { CONTACT_EMAIL } from "@/constants/contact";

function formatMoney(amount: number): string {
  return Number.isInteger(amount) ? `${amount}` : amount.toFixed(2);
}

function calculateSavings(monthlyPrice: number, yearlyPrice: number) {
  const yearlyAtMonthlyRate = monthlyPrice * 12;
  const savingsAmount = yearlyAtMonthlyRate - yearlyPrice;
  const savingsPercent = Math.round((savingsAmount / yearlyAtMonthlyRate) * 100);
  const effectiveMonthly = yearlyPrice / 12;
  const twoMonthsFreeEligible = savingsPercent >= 16;
  return { savingsAmount, savingsPercent, effectiveMonthly, twoMonthsFreeEligible };
}

export default function Pricing() {
  const t = useTranslations("pricing");
  const [activeTab, setActiveTab] = useState<"individuals" | "practitioners">("practitioners");
  const [billing, setBilling] = useState<"monthly" | "yearly">("monthly");

  const INDIVIDUAL_MONTHLY = 25;
  const INDIVIDUAL_YEARLY = 250;
  const MANAGER_MONTHLY = 75;
  const MANAGER_YEARLY = 750;
  const isYearly = billing === "yearly";

  const practitionerCards = [
    {
      monthly: INDIVIDUAL_MONTHLY,
      yearly: INDIVIDUAL_YEARLY,
      title: t("plans.monthly.title"),
      subtitle: t("plans.monthly.subtitle"),
      features: [
        t("features.unlimited"),
        t("features.license"),
        t("features.dashboard"),
        t("features.roster"),
        t("features.pdf"),
        t("features.tracking"),
        t("features.language"),
        t("features.secure"),
      ],
      featured: true,
      isManager: false,
    },
    {
      monthly: MANAGER_MONTHLY,
      yearly: MANAGER_YEARLY,
      title: t("plans.manager.title"),
      subtitle: t("plans.manager.subtitle"),
      features: [
        t("features.practitioners"),
        t("features.unlimitedScreenings"),
        t("features.accountManager"),
        t("features.retention"),
        t("features.security"),
        t("features.onPremise"),
        t("features.support"),
        t("features.training"),
      ],
      featured: false,
      isManager: true,
    },
  ];

  const individualPlans = [
    {
      price: "$5",
      period: t("perScreening"),
      title: t("plans.individual.title"),
      subtitle: t("plans.individual.subtitle"),
      features: [
        t("features.completeScreening"),
        t("features.instantPdf"),
        t("features.trackProgress"),
        t("features.language"),
        t("features.secure"),
      ],
      cta: t("startScreening"),
      ctaLink: "/signup",
      featured: false,
    },
  ];

  const isPractitioners = activeTab === "practitioners";

  return (
    <section id="pricing" className="py-20 bg-white">
      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Section Header */}
        <div className="text-center mb-10">
          <h2 className="text-3xl sm:text-4xl font-bold text-gray-900 mb-4">
            {t("title")}
          </h2>
          <p className="text-gray-500 max-w-2xl mx-auto mb-8 text-sm">
            {t("subtitle")}
          </p>

          {/* Audience Tab Toggle */}
          <div className="inline-flex items-center p-1.5 bg-gray-100 rounded-full gap-1">
            <button
              onClick={() => setActiveTab("individuals")}
              className={`flex items-center gap-2 px-5 py-2.5 text-sm font-medium rounded-full transition cursor-pointer ${
                activeTab === "individuals"
                  ? "bg-[#3B9EC9] text-white shadow-sm"
                  : "text-gray-500 hover:text-gray-700"
              }`}
            >
              <svg className="w-6 h-6" viewBox="0 0 36 36" fill="none">
                <circle cx="18" cy="10" r="7" fill="#FFDBB4"/>
                <path d="M11 10c0-1 1-4 3-5s5-1 7 0 3 3 3 5" fill="#E8913C"/>
                <path d="M11 10c1-1 2-2 4-2s4 0 5 1 2 2 2 3" fill="#F4A534"/>
                <rect x="8" y="22" width="20" height="12" rx="3" fill="#3B9EC9"/>
                <circle cx="18" cy="10" r="5" fill="#FFDBB4"/>
                <circle cx="15.5" cy="9" r="0.8" fill="#5D4037"/>
                <circle cx="20.5" cy="9" r="0.8" fill="#5D4037"/>
                <path d="M16 12.5c0.8 0.8 2.2 0.8 3 0" stroke="#5D4037" strokeWidth="0.8" strokeLinecap="round" fill="none"/>
              </svg>
              {t("forIndividuals")}
            </button>
            <button
              onClick={() => setActiveTab("practitioners")}
              className={`flex items-center gap-2 px-5 py-2.5 text-sm font-medium rounded-full transition cursor-pointer ${
                activeTab === "practitioners"
                  ? "bg-[#3B9EC9] text-white shadow-sm"
                  : "text-gray-500 hover:text-gray-700"
              }`}
            >
              <svg className="w-6 h-6" viewBox="0 0 36 36" fill="none">
                <circle cx="18" cy="10" r="7" fill="#FFDBB4"/>
                <path d="M11 8c0-1 1-3 3-4s5-1 7 0 3 2 3 4" fill="#3E2723"/>
                <rect x="8" y="22" width="20" height="12" rx="3" fill="#FFFFFF" stroke="#E0E0E0"/>
                <circle cx="18" cy="10" r="5" fill="#FFDBB4"/>
                <circle cx="15.5" cy="9" r="0.8" fill="#5D4037"/>
                <circle cx="20.5" cy="9" r="0.8" fill="#5D4037"/>
                <path d="M16 12.5c0.8 0.8 2.2 0.8 3 0" stroke="#5D4037" strokeWidth="0.8" strokeLinecap="round" fill="none"/>
                <circle cx="18" cy="28" r="2" fill="none" stroke="#3B9EC9" strokeWidth="1.5"/>
                <path d="M16 26V24M20 26V24" stroke="#3B9EC9" strokeWidth="1.5" strokeLinecap="round"/>
                <path d="M16 24C16 23 17 22 18 22S20 23 20 24" stroke="#3B9EC9" strokeWidth="1.5" fill="none"/>
              </svg>
              {t("forPractitioners")}
            </button>
          </div>
        </div>

        {/* Pricing Cards */}
        {isPractitioners ? (
          <>
            {/* Global Monthly/Yearly toggle + 2 months free pill */}
            <div className="flex items-center justify-center gap-3 mb-8">
              <span
                className={`text-sm font-medium ${
                  billing === "monthly" ? "text-gray-900" : "text-gray-500"
                }`}
              >
                {t("monthly")}
              </span>
              <button
                onClick={() => setBilling(isYearly ? "monthly" : "yearly")}
                aria-pressed={isYearly}
                aria-label={isYearly ? t("monthly") : t("yearly")}
                className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none cursor-pointer ${
                  isYearly ? "bg-[#3B9EC9]" : "bg-gray-300"
                }`}
              >
                <span
                  className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                    isYearly ? "translate-x-6" : "translate-x-1"
                  }`}
                />
              </button>
              <span
                className={`text-sm font-medium ${
                  isYearly ? "text-gray-900" : "text-gray-500"
                }`}
              >
                {t("yearly")}
              </span>
              {isYearly && (
                <span className="inline-flex items-center rounded-full bg-green-50 border border-green-200 px-2.5 py-0.5 text-xs font-semibold text-green-700">
                  {t("twoMonthsFree")}
                </span>
              )}
            </div>

            <div className="grid gap-6 grid-cols-1 md:grid-cols-2 max-w-4xl mx-auto">
              {practitionerCards.map((card, index) => {
                const price = isYearly ? card.yearly : card.monthly;
                const period = isYearly ? t("perYear") : t("perMonth");
                const savings = calculateSavings(card.monthly, card.yearly);
                const showSavings = isYearly;

                return (
                  <div
                    key={index}
                    className="relative bg-white rounded-2xl p-6 border border-gray-200"
                  >
                    {isYearly && card.featured && (
                      <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                        <span className="inline-flex items-center rounded-full bg-[#3B9EC9] px-3 py-1 text-xs font-semibold text-white shadow-sm">
                          {t("mostPopular")}
                        </span>
                      </div>
                    )}

                    <div className="mb-4">
                      {showSavings && (
                        <div className="mb-1">
                          <span className="text-sm text-gray-400 line-through">
                            ${card.monthly}
                            {t("perMonth")}
                          </span>
                        </div>
                      )}
                      <div className="flex items-baseline">
                        <span className="text-4xl font-bold text-gray-900">${price}</span>
                        <span className="text-sm text-gray-400 ml-0.5">{period}</span>
                      </div>
                      {showSavings && (
                        <p className="text-xs text-gray-500 mt-1">
                          {t("billedYearly", {
                            amount: formatMoney(savings.effectiveMonthly),
                          })}
                        </p>
                      )}
                      <h3 className="text-base font-semibold text-gray-900 mt-2">
                        {card.title}
                      </h3>
                    </div>

                    {/* Savings pills (yearly only) */}
                    {showSavings && savings.savingsAmount > 0 && (
                      <div className="flex flex-wrap gap-1.5 mb-3">
                        <span className="inline-flex items-center rounded-full bg-green-50 border border-green-200 px-2 py-0.5 text-[11px] font-semibold text-green-700">
                          {t("saveAmount", { amount: savings.savingsAmount })}
                        </span>
                        <span className="inline-flex items-center rounded-full bg-green-50 border border-green-200 px-2 py-0.5 text-[11px] font-semibold text-green-700">
                          {t("savePercent", { percent: savings.savingsPercent })}
                        </span>
                        {savings.twoMonthsFreeEligible && (
                          <span className="inline-flex items-center rounded-full bg-green-50 border border-green-200 px-2 py-0.5 text-[11px] font-semibold text-green-700">
                            {t("twoMonthsFree")}
                          </span>
                        )}
                      </div>
                    )}

                    <p className="text-xs mb-4 text-gray-500">{card.subtitle}</p>

                    <div className="mb-6">
                      <p className="text-sm font-semibold text-gray-900 mb-3">
                        {t("whatsIncluded")}
                      </p>
                      <ul className="space-y-2.5">
                        {card.features.map((feature, idx) => (
                          <li key={idx} className="flex items-start gap-2 text-sm">
                            <svg
                              className="w-4 h-4 flex-shrink-0 text-[#3B9EC9] mt-0.5"
                              fill="none"
                              viewBox="0 0 24 24"
                              stroke="currentColor"
                              strokeWidth={2.5}
                            >
                              <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                d="M5 13l4 4L19 7"
                              />
                            </svg>
                            <span className="text-gray-600 text-[13px]">{feature}</span>
                          </li>
                        ))}
                      </ul>
                    </div>

                    {card.isManager && (
                      <p className="text-xs text-gray-500 mb-4 leading-relaxed">
                        {t.rich("plans.manager.contactNote", {
                          email: () => (
                            <a
                              href={`mailto:${CONTACT_EMAIL}`}
                              className="font-medium text-[#3B9EC9] underline hover:text-[#2d8ab5]"
                            >
                              {CONTACT_EMAIL}
                            </a>
                          ),
                        })}
                      </p>
                    )}

                    <Link
                      href="/signup"
                      className={`flex items-center justify-center gap-1.5 w-full py-2.5 text-sm font-medium rounded-lg transition ${
                        card.featured
                          ? "bg-[#3B9EC9] text-white hover:bg-[#2d8ab5]"
                          : "text-gray-700 bg-white border border-gray-300 hover:bg-gray-50"
                      }`}
                    >
                      {card.featured && (
                        <svg
                          className="w-4 h-4"
                          fill="none"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                          strokeWidth={2.5}
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            d="M5 13l4 4L19 7"
                          />
                        </svg>
                      )}
                      {t("subscribeNow")}
                      {!card.featured && (
                        <svg
                          className="w-4 h-4"
                          fill="none"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                          strokeWidth={2}
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            d="M17 8l4 4m0 0l-4 4m4-4H3"
                          />
                        </svg>
                      )}
                    </Link>
                  </div>
                );
              })}
            </div>
          </>
        ) : (
          <div className="grid gap-6 grid-cols-1 max-w-md mx-auto w-full">
            {individualPlans.map((plan, index) => (
              <div
                key={index}
                className="bg-white rounded-2xl p-6 border border-gray-200"
              >
                <div className="mb-5">
                  <div className="flex items-baseline">
                    <span className="text-4xl font-bold text-gray-900">{plan.price}</span>
                    <span className="text-sm text-gray-400 ml-0.5">{plan.period}</span>
                  </div>
                  <h3 className="text-base font-semibold text-gray-900 mt-1">{plan.title}</h3>
                </div>

                <p className="text-xs mb-4 text-gray-500">{plan.subtitle}</p>

                <div className="mb-6">
                  <p className="text-sm font-semibold text-gray-900 mb-3">{t("whatsIncluded")}</p>
                  <ul className="space-y-2.5">
                    {plan.features.map((feature, idx) => (
                      <li key={idx} className="flex items-start gap-2 text-sm">
                        <svg
                          className="w-4 h-4 flex-shrink-0 text-[#3B9EC9] mt-0.5"
                          fill="none"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                          strokeWidth={2.5}
                        >
                          <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                        </svg>
                        <span className="text-gray-600 text-[13px]">{feature}</span>
                      </li>
                    ))}
                  </ul>
                </div>

                <Link
                  href={plan.ctaLink}
                  className="flex items-center justify-center gap-1.5 w-full py-2.5 text-sm font-medium rounded-lg transition text-gray-700 bg-white border border-gray-300 hover:bg-gray-50"
                >
                  {plan.cta}
                  <svg
                    className="w-4 h-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M17 8l4 4m0 0l-4 4m4-4H3"
                    />
                  </svg>
                </Link>
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}
