"use client";

import Link from "next/link";
import { Check, Minus, Plus } from "lucide-react";
import { useMemo, useState } from "react";

import {
  addOnsPageCopy,
  getProductAddOns,
  type ProductAddOn,
} from "@/data/product-addons.data";
import type { Locale } from "@/lib/locales";
import type { ProductSlug } from "@/lib/routes";

type SelectedAddOn = {
  selected: boolean;
  quantity: number;
};

const toneClasses = {
  pureestate: {
    bg: "bg-[#f5f7ff]",
    accent: "text-[#5264ee]",
    button: "bg-[#5264ee] text-white",
    pill: "bg-[#eef0ff] text-[#5264ee]",
    border: "border-[#5264ee]",
    ring: "ring-[#5264ee]/25",
  },
  buildpro: {
    bg: "bg-[#f2fbf7]",
    accent: "text-[#0f8f68]",
    button: "bg-[#0f8f68] text-white",
    pill: "bg-[#e4f8f1] text-[#0f8f68]",
    border: "border-[#0f8f68]",
    ring: "ring-[#0f8f68]/25",
  },
  societypro: {
    bg: "bg-[#f4faf6]",
    accent: "text-[#0f8f68]",
    button: "bg-[#0f8f68] text-white",
    pill: "bg-[#e4f6ef] text-[#0f8f68]",
    border: "border-[#0f8f68]",
    ring: "ring-[#0f8f68]/25",
  },
} satisfies Record<ProductSlug, Record<string, string>>;

const addOnFeatures: Record<ProductSlug, Record<string, string[]>> = {
  pureestate: {
    "extra-telecaller": [
      "Lead follow-up calling",
      "Customer communication",
      "Team-level access",
    ],
    "extra-visit-person": [
      "Site visit scheduling",
      "Client meeting updates",
      "Field user access",
    ],
    "whatsapp-automation": [
      "Follow-up reminders",
      "Customer updates",
      "Message automation",
    ],
    "property-data-import": [
      "Property records",
      "Lead records",
      "Customer records",
    ],
    "advanced-reports": [
      "Sales reports",
      "Team performance",
      "Source and revenue insights",
    ],
    "priority-support": [
      "Faster onboarding",
      "Priority assistance",
      "Product support",
    ],
  },
  buildpro: {
    "extra-telecaller": [
      "Project enquiry calls",
      "Buyer follow-ups",
      "Sales team access",
    ],
    "extra-visit-person": [
      "Site visit users",
      "Customer meeting updates",
      "Field coordination",
    ],
    "extra-project-pack": [
      "More project capacity",
      "Project-wise setup",
      "Builder workspace scale",
    ],
    "extra-units-pack": [
      "More unit inventory",
      "Large project support",
      "Availability tracking",
    ],
    "whatsapp-automation": [
      "Booking notifications",
      "Payment reminders",
      "Progress updates",
    ],
    "project-data-migration": [
      "Project data",
      "Unit inventory",
      "Booking and customer records",
    ],
    "priority-support": [
      "Priority onboarding",
      "Builder team support",
      "Setup assistance",
    ],
  },
  societypro: {
    "extra-admin-account": [
      "Committee access",
      "Admin permissions",
      "Society management users",
    ],
    "extra-flats-pack": [
      "More flat capacity",
      "Resident records",
      "Vehicle directory scale",
    ],
    "visitor-security-app": [
      "Visitor entry",
      "Security desk workflow",
      "Gate records",
    ],
    "maintenance-billing": ["Dues tracking", "Receipts", "Payment reminders"],
    "notice-pack": ["Resident notices", "Alerts", "Reminder broadcasts"],
    "facility-booking": [
      "Amenity booking",
      "Hall and garden slots",
      "Common facility calendar",
    ],
    "priority-support": [
      "Faster onboarding",
      "Admin support",
      "Setup assistance",
    ],
  },
};

function formatPrice(price: number, locale: Locale) {
  return new Intl.NumberFormat(`${locale}-IN`).format(price);
}

export default function ProductAddOnsPage({
  locale,
  productSlug,
  productHref,
  registerHref,
}: {
  locale: Locale;
  productSlug: ProductSlug;
  productHref: string;
  registerHref: string;
}) {
  const copy = addOnsPageCopy[locale] || addOnsPageCopy.en;
  const addOns = getProductAddOns(productSlug);
  const tone = toneClasses[productSlug];

  const [selected, setSelected] = useState<Record<string, SelectedAddOn>>({});

  const summary = useMemo(() => {
    let yearlyTotal = 0;
    let oneTimeTotal = 0;
    const selectedItems: Array<ProductAddOn & { quantity: number }> = [];

    for (const addOn of addOns) {
      const state = selected[addOn.id];
      if (!state?.selected) continue;

      const quantity = addOn.quantityEnabled ? state.quantity : 1;
      selectedItems.push({ ...addOn, quantity });

      if (addOn.billing === "yearly") {
        yearlyTotal += addOn.price * quantity;
      } else {
        oneTimeTotal += addOn.price * quantity;
      }
    }

    return { yearlyTotal, oneTimeTotal, selectedItems };
  }, [addOns, selected]);

  function toggleAddOn(addOn: ProductAddOn) {
    setSelected((current) => {
      const item = current[addOn.id];

      return {
        ...current,
        [addOn.id]: {
          selected: !item?.selected,
          quantity: item?.quantity ?? 1,
        },
      };
    });
  }

  function updateQuantity(addOnId: string, type: "inc" | "dec") {
    setSelected((current) => {
      const item = current[addOnId] ?? { selected: true, quantity: 1 };
      const nextQuantity =
        type === "inc"
          ? Math.min(item.quantity + 1, 20)
          : Math.max(item.quantity - 1, 1);

      return {
        ...current,
        [addOnId]: {
          selected: true,
          quantity: nextQuantity,
        },
      };
    });
  }

  return (
    <main className={`min-h-screen ${tone.bg}`}>
      <section className="mx-auto max-w-7xl px-6 py-10 lg:px-8 lg:py-14">
        <div className="mb-8">
          <Link
            href={productHref}
            className={`inline-flex rounded-full bg-white px-4 py-2 text-sm font-bold shadow-sm ${tone.accent}`}
          >
            ← {copy.backToProduct}
          </Link>

          <p
            className={`mt-8 text-xs font-extrabold uppercase tracking-[0.18em] ${tone.accent}`}
          >
            {copy.eyebrow}
          </p>

          <h1 className="mt-3 max-w-3xl text-4xl font-extrabold tracking-[-0.055em] text-[#111a35] md:text-5xl">
            {copy.title}
          </h1>

          <p className="mt-4 max-w-2xl text-base leading-8 text-[#657694]">
            {copy.description}
          </p>
        </div>

        <div className="grid gap-6 lg:grid-cols-[1fr_380px]">
          <div className="grid gap-4 md:grid-cols-2">
            {addOns.map((addOn) => {
              const state = selected[addOn.id];
              const isSelected = Boolean(state?.selected);
              const quantity = state?.quantity ?? 1;
              const features = addOnFeatures[productSlug][addOn.id] ?? [];

              return (
                <article
                  key={addOn.id}
                  className={`rounded-3xl  bg-white p-5 shadow-[0_14px_35px_rgba(31,48,94,0.08)] transition ${
                    isSelected
                      ? `${tone.border} ${tone.ring} ring-2 ring-offset-2 ring-offset-white`
                      : `border-slate-100`
                  }`}
                >
                  <div className="flex items-start justify-between gap-4">
                    <div>
                      <h2 className="text-lg font-extrabold text-[#111a35]">
                        {addOn.name[locale]}
                      </h2>
                      <p className="mt-2 text-sm leading-6 text-[#657694]">
                        {addOn.description[locale]}
                      </p>
                    </div>

                    <button
                      type="button"
                      onClick={() => toggleAddOn(addOn)}
                      className={`grid h-9 w-9 shrink-0 place-items-center rounded-full border text-sm font-black ${
                        isSelected
                          ? `${tone.button} border-transparent`
                          : "border-slate-200 bg-white text-slate-400"
                      }`}
                      aria-label={`Select ${addOn.name.en}`}
                    >
                      {isSelected ? (
                        <Check size={17} strokeWidth={3.5} />
                      ) : (
                        <Plus size={17}  />
                      )}
                    </button>
                  </div>

                  <div className="mt-5 flex flex-wrap items-center justify-between gap-3">
                    <div>
                      <p className={`text-2xl font-extrabold ${tone.accent}`}>
                        ₹ {formatPrice(addOn.price, locale)}
                      </p>
                      <p className="mt-1 text-xs font-bold text-[#657694]">
                        {addOn.billing === "yearly"
                          ? copy.yearly
                          : copy.oneTime}
                      </p>
                    </div>

                    <span
                      className={`rounded-full px-3 py-1 text-xs font-extrabold ${tone.pill}`}
                    >
                      {copy.gstIncluded}
                    </span>
                  </div>

                  {features.length ? (
                    <div className="mt-5 space-y-2.5 border-t border-slate-100 pt-4">
                      {features.map((feature) => (
                        <p
                          key={feature}
                          className="flex items-start gap-2 text-sm font-semibold leading-6 text-[#526079]"
                        >
                          <Check
                            size={15}
                            strokeWidth={3.2}
                            className={`mt-1 shrink-0 ${tone.accent}`}
                          />
                          <span>{feature}</span>
                        </p>
                      ))}
                    </div>
                  ) : null}

                  {addOn.quantityEnabled ? (
                    <div className="mt-5 flex items-center justify-between rounded-2xl bg-slate-50 px-4 py-3">
                      <span className="text-sm font-bold text-[#657694]">
                        {copy.quantity}
                      </span>

                      <div className="flex items-center gap-3">
                        <button
                          type="button"
                          onClick={() => updateQuantity(addOn.id, "dec")}
                          className="grid h-8 w-8 place-items-center rounded-full bg-white text-[#111a35] shadow-sm"
                          aria-label="Decrease quantity"
                        >
                          <Minus size={15} />
                        </button>

                        <span className="w-6 text-center text-sm font-extrabold text-[#111a35]">
                          {quantity}
                        </span>

                        <button
                          type="button"
                          onClick={() => updateQuantity(addOn.id, "inc")}
                          className="grid h-8 w-8 place-items-center rounded-full bg-white text-[#111a35] shadow-sm"
                          aria-label="Increase quantity"
                        >
                          <Plus size={15} />
                        </button>
                      </div>
                    </div>
                  ) : null}
                </article>
              );
            })}
          </div>

          <aside className="h-fit rounded-[28px] border border-white bg-white p-6 shadow-[0_18px_45px_rgba(31,48,94,0.12)] lg:sticky lg:top-24">
            <h2 className="text-xl font-extrabold text-[#111a35]">
              {copy.eyebrow} Summary
            </h2>

            <div className="mt-5 space-y-3">
              {summary.selectedItems.length ? (
                summary.selectedItems.map((item) => (
                  <div
                    key={item.id}
                    className="flex items-start justify-between gap-4 rounded-2xl bg-slate-50 p-3"
                  >
                    <div>
                      <p className="text-sm font-extrabold text-[#111a35]">
                        {item.name[locale]}
                      </p>
                      <p className="text-xs font-bold text-[#657694]">
                        Qty: {item.quantity}
                      </p>
                    </div>

                    <p className="text-sm font-extrabold text-[#111a35]">
                      ₹ {formatPrice(item.price * item.quantity, locale)}
                    </p>
                  </div>
                ))
              ) : (
                <p className="rounded-2xl bg-slate-50 p-4 text-sm font-semibold text-[#657694]">
                  {copy.noAddOns}
                </p>
              )}
            </div>

            <div className="mt-6 border-t border-slate-100 pt-5">
              <div className="flex justify-between text-sm font-bold text-[#657694]">
                <span>Yearly Total</span>
                <span>₹ {formatPrice(summary.yearlyTotal, locale)}</span>
              </div>

              <div className="mt-3 flex justify-between text-sm font-bold text-[#657694]">
                <span>One-time Total</span>
                <span>₹ {formatPrice(summary.oneTimeTotal, locale)}</span>
              </div>

              <p
                className={`mt-4 rounded-2xl px-4 py-3 text-center text-sm font-extrabold ${tone.pill}`}
              >
                {copy.gstIncluded}
              </p>

              <Link
                href={registerHref}
                className={`mt-5 flex h-12 items-center justify-center rounded-2xl text-sm font-extrabold ${tone.button}`}
              >
                {copy.getStarted}
              </Link>
            </div>
          </aside>
        </div>
      </section>
    </main>
  );
}
