"use client";

import { useEffect, useState } from "react";
import { ArrowLeft, Share2, MapPin, ShoppingCart, X } from "lucide-react";
import OctagonSeatMap from "@/components/OctagonSeatMap";
import { useCartStore } from "@/store/cartStore";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { getTournamentSeatsApi, type SeatResponse } from "@/api/client";

// ─── Mocked event banner data (real events API is out of scope here) ──────────

const MOCK_EVENT = {
  title: "Чемпионат по ММА",
  venue: "ВТБ Арена, Москва",
  imageSrc: "https://images.unsplash.com/photo-1549719386-74dfcbf7dbed?w=400&q=80",
};

// ─── Legend item ──────────────────────────────────────────────────────────────

function LegendDot({ color, label }: { color: string; label: string }) {
  return (
    <div className="flex items-center gap-1.5">
      <span className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: color }} />
      <span className="text-[11px] text-[#8E8E93]">{label}</span>
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function SeatsPage({ params }: { params: { id: string } }) {
  const router = useRouter();
  const { seats: cartSeats, removeSeat, totalPrice } = useCartStore();

  // Seat data from the API (null = loading, [] = empty/error, array = ready)
  const [apiSeats, setApiSeats] = useState<SeatResponse[] | null>(null);

  useEffect(() => {
    let cancelled = false;

    getTournamentSeatsApi(params.id)
      .then((data) => {
        if (!cancelled) setApiSeats(data);
      })
      .catch(() => {
        if (!cancelled) setApiSeats([]); // Show empty state on error
      });

    return () => { cancelled = true; };
  }, [params.id]);

  const total = totalPrice();
  const count = cartSeats.length;
  const firstSeat = cartSeats[0];

  return (
    <div className="flex justify-center min-h-screen bg-[#121212]">
      <div className="relative w-full max-w-[390px] flex flex-col min-h-screen bg-[#121212]">

        {/* ── Header ── */}
        <div className="flex items-center justify-between px-5 pt-12 pb-3">
          <button
            aria-label="Назад"
            onClick={() => router.back()}
            className="w-9 h-9 flex items-center justify-center rounded-full bg-[#1C1C1E] text-white"
          >
            <ArrowLeft size={18} strokeWidth={2.5} />
          </button>
          <h1 className="text-[17px] font-semibold text-white">Выбор мест</h1>
          <button
            aria-label="Поделиться"
            className="w-9 h-9 flex items-center justify-center rounded-full bg-[#1C1C1E] text-white"
          >
            <Share2 size={17} strokeWidth={2} />
          </button>
        </div>

        {/* ── Event banner ── */}
        <div className="flex items-center gap-3 px-5 py-3 mx-4 mb-3 bg-[#1C1C1E] rounded-2xl">
          <div className="relative w-11 h-11 rounded-xl overflow-hidden flex-shrink-0">
            <Image
              src={MOCK_EVENT.imageSrc}
              alt={MOCK_EVENT.title}
              fill
              className="object-cover"
              sizes="44px"
            />
          </div>
          <div className="min-w-0">
            <p className="text-[14px] font-semibold text-white leading-tight">{MOCK_EVENT.title}</p>
            <div className="flex items-center gap-1 mt-0.5">
              <MapPin size={10} className="text-[#8E8E93]" />
              <span className="text-[11px] text-[#8E8E93] truncate">{MOCK_EVENT.venue}</span>
            </div>
          </div>
        </div>

        {/* ── Seat map (real data, loading, or empty state) ── */}
        <div className="flex-1 flex flex-col px-1">
          <OctagonSeatMap apiSeats={apiSeats} />
        </div>

        {/* ── Legend (only when seats are loaded) ── */}
        {apiSeats !== null && apiSeats.length > 0 && (
          <div className="px-5 pb-2">
            <div className="grid grid-cols-2 gap-x-6 gap-y-2">
              <LegendDot color="#0891B2" label="Свободно" />
              <LegendDot color="#2D3748" label="Занято" />
              <LegendDot color="#E32636" label="Выбрано" />
              <LegendDot color="#D97706" label="Удержано" />
              <LegendDot color="#8B5CF6" label="VIP" />
              <LegendDot color="#0891B2" label="Стандарт" />
            </div>
          </div>
        )}

        {/* ── Selected seats chips ── */}
        {count > 0 && (
          <div className="px-5 pb-2">
            <div className="flex gap-2 flex-wrap">
              {cartSeats.map((s) => (
                <div
                  key={s.seatId}
                  className="flex items-center gap-1.5 bg-[#1C1C1E] border border-[#2C2C2E] rounded-full px-3 py-1"
                >
                  <span className="text-[11px] text-white">
                    {s.sector} · Р{s.row} М{s.number}
                  </span>
                  <button
                    onClick={() => removeSeat(s.seatId)}
                    className="text-[#8E8E93] hover:text-white"
                    aria-label={`Убрать место ${s.number}`}
                  >
                    <X size={11} strokeWidth={2.5} />
                  </button>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ── Bottom bar ── */}
        <div className="sticky bottom-0 left-0 right-0 bg-[#1C1C1E] border-t border-[#2C2C2E] px-5 pt-3 pb-8">
          {count > 0 ? (
            <>
              <div className="flex items-start justify-between mb-3">
                <div>
                  <p className="text-[12px] text-[#8E8E93] mb-0.5">Выбранные места:</p>
                  <p className="text-[14px] font-semibold text-white leading-snug">
                    {firstSeat
                      ? `${firstSeat.sector}, Ряд ${firstSeat.row}, Место ${firstSeat.number}`
                      : "—"}
                    {count > 1 && (
                      <span className="text-[#8E8E93] font-normal"> +{count - 1}</span>
                    )}
                  </p>
                </div>
                <div className="text-right">
                  <p className="text-[12px] text-[#8E8E93] mb-0.5">Количество мест:</p>
                  <p className="text-[14px] font-semibold text-white">{count}</p>
                </div>
              </div>

              <div className="flex items-center justify-between">
                <div>
                  <p className="text-[12px] text-[#8E8E93]">Итого к оплате:</p>
                  <p className="text-[22px] font-bold text-white leading-tight">
                    {total.toLocaleString("ru-RU")} ₽
                  </p>
                </div>
                <button
                  onClick={() => router.push("/checkout")}
                  className="bg-[#E32636] hover:bg-[#C41E2A] active:scale-95 transition-all text-white text-[15px] font-semibold px-6 py-3.5 rounded-2xl"
                >
                  Перейти к оплате
                </button>
              </div>
            </>
          ) : (
            <div className="flex items-center justify-center gap-2 py-1">
              <ShoppingCart size={16} className="text-[#8E8E93]" />
              <p className="text-[13px] text-[#8E8E93]">Выберите места на схеме</p>
            </div>
          )}
        </div>

      </div>
    </div>
  );
}
