"use client";

import { useState } from "react";
import { useTranslation } from "@turbostarter/i18n";
import { cn } from "@turbostarter/ui";
import { buttonVariants } from "@turbostarter/ui-web/button";

import type { BusinessData } from "./wizard";

interface StepPaymentProps {
  business: BusinessData;
  email: string;
  onBack: () => void;
}

export const StepPayment = ({ business, email, onBack }: StepPaymentProps) => {
  const { t } = useTranslation("marketing");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const handlePay = async () => {
    setLoading(true);
    setError("");

    try {
      const locale = window.location.pathname.split("/")[1] || "en";

      const res = await fetch("/api/blueprint/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email,
          businessName: business.name,
          placeId: business.place_id,
          locale,
        }),
      });

      if (!res.ok) {
        const data = (await res.json().catch(() => ({}))) as Record<string, string>;
        setError(data.error || "Payment failed");
        return;
      }

      const data = (await res.json()) as { url: string };
      if (data.url) {
        window.location.href = data.url;
      }
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex w-full max-w-lg flex-col items-center gap-6">
      <div className="text-center">
        <h2 className="text-foreground text-2xl font-semibold tracking-tight sm:text-3xl">
          {t("wizard.payment.title")}
        </h2>
        <p className="text-muted-foreground mt-2 text-sm">
          {t("wizard.payment.description")}
        </p>
      </div>

      {/* Order summary card */}
      <div className="bg-background w-full rounded-xl border p-6">
        <h3 className="text-foreground mb-4 text-sm font-semibold">
          {t("wizard.payment.orderSummary")}
        </h3>

        <div className="flex items-start justify-between">
          <div>
            <p className="text-foreground font-medium">
              {t("wizard.payment.product")}
            </p>
            <p className="text-muted-foreground text-sm">
              {t("wizard.payment.for", { business: business.name })}
            </p>
          </div>
          <div className="text-right">
            <span className="text-muted-foreground mr-2 text-sm line-through">
              {t("wizard.payment.originalPrice")}
            </span>
            <span className="text-foreground text-xl font-bold">
              {t("wizard.payment.launchPrice")}
            </span>
          </div>
        </div>

        <div className="my-4">
          <span className="inline-flex items-center gap-1.5 rounded-full bg-amber-500/10 px-3 py-1 text-xs font-medium text-amber-600">
            {t("wizard.payment.launchBadge")}
          </span>
        </div>

        <div className="border-t pt-4">
          <div className="flex items-center justify-between">
            <span className="text-foreground font-semibold">
              {t("wizard.payment.total")}
            </span>
            <span className="text-foreground text-2xl font-bold">
              {t("wizard.payment.launchPrice")}
            </span>
          </div>
        </div>
      </div>

      {error && <p className="text-sm text-red-500">{error}</p>}

      <div className="flex w-full flex-col gap-3">
        <button
          type="button"
          onClick={handlePay}
          disabled={loading}
          className={cn(
            buttonVariants({ size: "lg" }),
            "w-full",
            loading && "opacity-60",
          )}
        >
          {loading ? (
            <span className="flex items-center gap-2">
              <span className="size-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
              {t("wizard.payment.payButton")}
            </span>
          ) : (
            t("wizard.payment.payButton")
          )}
        </button>

        <div className="text-muted-foreground flex flex-col items-center gap-1 text-xs">
          <span className="flex items-center gap-1">
            <svg
              className="size-3.5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M16.5 10.5V6.75a4.5 4.5 0 1 0-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H6.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z"
              />
            </svg>
            {t("wizard.payment.securePayment")}
          </span>
          <span>{t("wizard.payment.guarantee")}</span>
        </div>

        <button
          type="button"
          onClick={onBack}
          className="text-muted-foreground hover:text-foreground text-center text-sm transition-colors"
        >
          ← Back
        </button>
      </div>
    </div>
  );
};
