"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
import { CheckCircle2, DollarSign, LoaderCircle } from "lucide-react";
import { getReadableTextColor } from "@/lib/color-contrast";

type ConfirmationState = {
  loading: boolean;
  error: string | null;
  approvedOrderId: string | null;
  paymentStatus: string | null;
};

export default function CatalogCheckoutConfirmationClient({
  slug,
  storeName,
  logoUrl,
  primaryColor,
  headerColor,
  orderId,
  orderNumber,
}: {
  slug: string;
  storeName: string;
  logoUrl?: string | null;
  primaryColor: string;
  headerColor: string;
  orderId: string;
  orderNumber?: string;
}) {
  const [state, setState] = useState<ConfirmationState>({
    loading: true,
    error: null,
    approvedOrderId: null,
    paymentStatus: null,
  });

  useEffect(() => {
    let active = true;

    async function loadStatus() {
      try {
        const response = await fetch(
          `/api/catalog/payment/status?slug=${encodeURIComponent(slug)}&orderId=${encodeURIComponent(orderId)}`,
          { cache: "no-store" }
        );
        const payload = (await response.json().catch(() => null)) as
          | {
              error?: string;
              order?: { approved_order_id?: string | null; payment_status?: string | null };
              payment?: { status?: string | null };
            }
          | null;

        if (!response.ok) {
          throw new Error(payload?.error || "Nao foi possivel confirmar a compra.");
        }

        if (!active) return;

        const paymentStatus = payload?.payment?.status || payload?.order?.payment_status || null;
        setState({
          loading: false,
          error: null,
          approvedOrderId: payload?.order?.approved_order_id || null,
          paymentStatus,
        });
      } catch (error) {
        if (!active) return;
        setState({
          loading: false,
          error: error instanceof Error ? error.message : "Nao foi possivel confirmar a compra.",
          approvedOrderId: null,
          paymentStatus: null,
        });
      }
    }

    void loadStatus();
    const interval = window.setInterval(() => {
      void loadStatus();
    }, 2500);

    return () => {
      active = false;
      window.clearInterval(interval);
    };
  }, [orderId, slug]);

  const isReady = Boolean(state.approvedOrderId);

  return (
    <div className="min-h-[calc(100vh-120px)] bg-white px-4 py-10 sm:px-6">
      <div className="mx-auto max-w-[620px]">
        <div className="overflow-hidden border border-slate-200 bg-white">
          <div
            className="flex min-h-[108px] w-full items-center justify-center px-6 py-6 sm:min-h-[120px] sm:px-10"
            style={{ backgroundColor: headerColor || primaryColor }}
          >
            {logoUrl ? (
              <Image
                src={logoUrl}
                alt={storeName}
                width={220}
                height={84}
                className="h-16 w-auto max-w-[260px] object-contain sm:h-[72px]"
                unoptimized
              />
            ) : (
              <div className="text-2xl font-semibold tracking-[-0.05em] text-white">{storeName}</div>
            )}
          </div>

          <div className="px-6 py-8 sm:px-10 sm:py-12">
          <div className="flex flex-col items-center text-center">
            <div
              className="flex h-24 w-24 items-center justify-center rounded-full border-4"
              style={{
                borderColor: isReady ? "#bbf7d0" : `${primaryColor}22`,
                backgroundColor: isReady ? "#ecfdf3" : `${primaryColor}10`,
                color: isReady ? "#16a34a" : primaryColor,
              }}
            >
              {isReady ? (
                <div className="relative flex h-14 w-14 items-center justify-center">
                  <DollarSign className="h-14 w-14 stroke-[2.2]" />
                  <CheckCircle2 className="absolute -right-1 -top-1 h-6 w-6 rounded-full bg-white text-emerald-600" />
                </div>
              ) : (
                <LoaderCircle className="h-10 w-10 animate-spin" />
              )}
            </div>

            <div className="mt-5 text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">
              Confirmacao da compra
            </div>
            <h1 className="mt-3 text-3xl font-semibold tracking-[-0.05em] text-slate-950">
              {isReady ? "Compra confirmada" : "Finalizando seu pedido"}
            </h1>
            <p className="mt-3 max-w-[420px] text-sm leading-6 text-slate-500">
              {state.error
                ? state.error
                : isReady
                  ? `Seu pagamento foi confirmado${orderNumber ? ` no pedido #${orderNumber}` : ""}.`
                  : "Estamos concluindo a confirmacao e preparando o acesso ao seu pedido no portal do cliente."}
            </p>

            {state.paymentStatus && !state.error ? (
              <div className="mt-4 text-xs font-medium text-slate-500">
                Status do pagamento: {state.paymentStatus === "approved" ? "aprovado" : state.paymentStatus}
              </div>
            ) : null}

            <div className="mt-8 flex w-full flex-col items-center gap-4">
              {isReady ? (
                <Link
                  href={`/${slug}/cliente/pedido/${state.approvedOrderId}`}
                  className="inline-flex min-h-12 w-full items-center justify-center px-6 text-sm font-semibold text-white transition hover:opacity-95"
                  style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                >
                  Acessar pedido
                </Link>
              ) : (
                <div className="inline-flex min-h-12 w-full items-center justify-center border border-slate-200 bg-slate-50 px-6 text-sm font-semibold text-slate-600">
                  Aguarde um instante...
                </div>
              )}

              <Link href={`/${slug}`} className="text-sm font-medium text-slate-500 transition hover:text-slate-900">
                Voltar pra Loja
              </Link>
            </div>
          </div>
          </div>
        </div>
      </div>
    </div>
  );
}
