"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import type { BallboxStoreClassOffer } from "@/lib/classes-backend";
import { formatBallboxDateTime } from "@/lib/ballbox-datetime";
import { classesOffersResponseSchema } from "@/lib/contracts/classes";

type ClassesOffersPageClientProps = {
  initialOffers: BallboxStoreClassOffer[];
};

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);
}

function AtcStatus({ offer, loading }: { offer: BallboxStoreClassOffer; loading: boolean }) {
  if (loading && offer.atcContext.status === "linked") {
    return (
      <p className="text-sm text-white/75">
        Buscando disponibilidad publica de ATC...
      </p>
    );
  }

  return (
    <p className="text-sm text-white/75">
      {offer.atcContext.status === "available"
        ? `${offer.atcContext.clubName ?? "Club ATC"}${offer.atcContext.courtName ? ` - ${offer.atcContext.courtName}` : ""}`
        : offer.atcContext.note ?? "Sin contexto ATC en este offer."}
    </p>
  );
}

export function ClassesOffersPageClient({ initialOffers }: ClassesOffersPageClientProps) {
  const needsAtcHydration = initialOffers.some((offer) => offer.atcContext.status === "linked");
  const [offers, setOffers] = useState(initialOffers);
  const [loadingAtc, setLoadingAtc] = useState(needsAtcHydration);

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

    let active = true;

    void (async () => {
      try {
        const response = await fetch("/api/classes/offers", { cache: "force-cache" });
        const payload = classesOffersResponseSchema.parse(await response.json());
        if (!response.ok || !active) return;
        setOffers(payload.items);
      } catch {
      } finally {
        if (active) {
          setLoadingAtc(false);
        }
      }
    })();

    return () => {
      active = false;
    };
  }, [needsAtcHydration]);

  return (
    <section className="mt-8 grid gap-5">
      {offers.map((offer) => (
        <article key={offer.id} className="rounded-[1.75rem] border border-white/10 bg-[#101510]/90 p-6 shadow-[0_22px_60px_-40px_rgba(0,0,0,0.55)]">
          <div className="flex flex-col gap-5 lg:flex-row lg:items-start lg:justify-between">
            <div className="space-y-3">
              <div className="flex flex-wrap items-center gap-2 text-xs uppercase tracking-[0.18em] text-white/45">
                <span>{offer.venue.clubName ?? "ATC no disponible"}</span>
                <span className="rounded-full border border-[#c4d600]/25 bg-[#c4d600]/12 px-3 py-1 text-[#c4d600]">{offer.coach.name}</span>
              </div>
              <div>
                <h2 className="text-2xl font-semibold text-white">{offer.title}</h2>
                <p className="mt-2 max-w-2xl text-sm leading-6 text-white/65">{offer.description ?? "Clase Ballbox con request local."}</p>
              </div>
              <div className="grid gap-2 text-sm text-white/80 sm:grid-cols-2">
                <p>{formatBallboxDateTime(offer.startsAt)}</p>
                <p>{offer.venue.name}</p>
                <p>{offer.durationMinutes ? `${offer.durationMinutes} min` : "Duracion a confirmar"}</p>
                <p>{formatMoney(offer.priceMinor, offer.currency)}</p>
              </div>
            </div>

            <div className="flex min-w-[250px] flex-col gap-4 rounded-[1.5rem] border border-white/10 bg-[linear-gradient(180deg,#141813,#0c0f0b)] p-5 text-white">
              <div>
                <p className="text-xs uppercase tracking-[0.18em] text-[#c4d600]">ATC publico</p>
                <div className="mt-2">
                  <AtcStatus offer={offer} loading={loadingAtc} />
                </div>
              </div>
              <Button asChild className="h-11 rounded-xl text-sm font-medium">
                <Link href={`/classes/${offer.id}`}>Ver detalle y solicitar</Link>
              </Button>
            </div>
          </div>
        </article>
      ))}
    </section>
  );
}
