"use client";

import { useEffect, useState } from "react";
import { ClassesRequestForm } from "@/components/classes-request-form";
import type { BallboxStoreClassOffer } from "@/lib/classes-backend";
import { formatBallboxDateTime } from "@/lib/ballbox-datetime";
import { classesOfferDetailResponseSchema } from "@/lib/contracts/classes";

type ClassOfferDetailClientProps = {
  initialOffer: BallboxStoreClassOffer;
  initialSportclubId?: string | null;
  initialSelectedSlot?: {
    start: string;
    durationMinutes: number;
    priceMinor: number | null;
    currency: string | null;
    sportclubId: string | null;
    courtId: string | null;
    courtName: string | null;
  } | null;
};

function formatMoney(value: number | null, currency: string | null) {
  if (value === null || !currency) return "A confirmar";

  return new Intl.NumberFormat("es-AR", {
    style: "currency",
    currency,
    maximumFractionDigits: 0,
  }).format(value / 100);
}

export function ClassOfferDetailClient({ initialOffer, initialSportclubId = null, initialSelectedSlot = null }: ClassOfferDetailClientProps) {
  const needsAtcHydration = initialOffer.atcContext.status === "linked";
  const [offer, setOffer] = useState(initialOffer);
  const [loadingAtc, setLoadingAtc] = useState(needsAtcHydration);
  const initialSelectedSlotStart = initialSelectedSlot?.start ?? null;
  const initialSelectedSlotDurationMinutes = initialSelectedSlot?.durationMinutes ?? null;
  const initialSelectedSlotCourtId = initialSelectedSlot?.courtId ?? null;

  useEffect(() => {
    if (!needsAtcHydration) {
      return;
    }

    let active = true;

    void (async () => {
      try {
        const url = new URL(`/api/classes/offers/${initialOffer.id}`, window.location.origin);
        if (initialSportclubId) {
          url.searchParams.set("sportclubId", initialSportclubId);
        }
        if (initialSelectedSlotStart) {
          url.searchParams.set("slotStart", initialSelectedSlotStart);
        }
        if (initialSelectedSlotDurationMinutes) {
          url.searchParams.set("slotDurationMinutes", String(initialSelectedSlotDurationMinutes));
        }
        if (initialSelectedSlotCourtId) {
          url.searchParams.set("slotCourtId", initialSelectedSlotCourtId);
        }
        const response = await fetch(url.toString(), { cache: "no-store" });
        const payload = classesOfferDetailResponseSchema.parse(await response.json());
        if (!response.ok || !active) return;
        setOffer(payload.item);
      } catch {
      } finally {
        if (active) {
          setLoadingAtc(false);
        }
      }
    })();

    return () => {
      active = false;
    };
  }, [
    initialOffer.id,
    initialSelectedSlotCourtId,
    initialSelectedSlotDurationMinutes,
    initialSelectedSlotStart,
    initialSportclubId,
    needsAtcHydration,
  ]);

  return (
    <section className="mt-8 grid gap-6 lg:grid-cols-[1.05fr_0.95fr]">
      <ClassesRequestForm
        key={`${offer.id}:${offer.atcContext.slots.length}:${initialSelectedSlot?.start ?? "no-slot"}`}
        classOfferId={offer.id}
        slots={offer.atcContext.slots}
        loadingSlots={loadingAtc}
        initialSelectedSlot={initialSelectedSlot}
      />

      <aside className="rounded-[1.75rem] border border-white/10 bg-[linear-gradient(180deg,#141813,#0c0f0b)] p-6 text-white shadow-[0_24px_60px_-35px_rgba(0,0,0,0.6)]">
        <p className="text-xs uppercase tracking-[0.22em] text-[#c4d600]">Contexto ATC</p>
        <h2 className="mt-2 text-2xl font-semibold">Public-read availability</h2>
        <div className="mt-5 space-y-4 text-sm text-white/80">
          <p>
            <span className="text-white/45">Club:</span> {offer.atcContext.clubName ?? (loadingAtc ? "Buscando..." : "No disponible")}
          </p>
          <p>
            <span className="text-white/45">Cancha:</span> {offer.atcContext.courtName ?? (loadingAtc ? "Buscando..." : "No disponible")}
          </p>
          <p>
            <span className="text-white/45">Ubicacion:</span> {offer.atcContext.locationName ?? (loadingAtc ? "Buscando..." : "No disponible")}
          </p>
          <p>
            <span className="text-white/45">Opciones visibles:</span> {loadingAtc ? "..." : offer.atcContext.slots.length}
          </p>
        </div>

        {loadingAtc ? (
          <p className="mt-5 rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white/75">
            Consultando ATC en segundo plano para no bloquear la carga inicial.
          </p>
        ) : null}

        {offer.atcContext.slots.length > 0 ? (
          <div className="mt-5 rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white/75">
            <p className="font-medium text-white">Horarios detectados</p>
            <ul className="mt-3 space-y-2">
              {offer.atcContext.slots.slice(0, 3).map((slot) => (
                <li key={`${slot.courtId ?? "court"}-${slot.start}`} className="flex flex-wrap items-center justify-between gap-2">
                  <span>{formatBallboxDateTime(slot.start)}</span>
                  <span className="text-white/55">{formatMoney(slot.priceMinor, slot.currency)}</span>
                </li>
              ))}
            </ul>
          </div>
        ) : null}

        {offer.atcContext.note && !loadingAtc ? (
          <p className="mt-5 rounded-2xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white/75">{offer.atcContext.note}</p>
        ) : null}
      </aside>
    </section>
  );
}
