"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ArrowLeft, Download, CheckCircle2, Wallet } from "lucide-react";
import { QRCodeSVG } from "qrcode.react";
import type { AxiosError } from "axios";
import { getMyTicketsApi, type TicketResponse } from "@/api/client";

// ─── Constants ────────────────────────────────────────────────────────────────

/** Strip the internal MinIO origin so the URL becomes a relative path.
 *  e.g. "http://minio:9000/tickets-media/file.pdf" → "/tickets-media/file.pdf" */
const MINIO_INTERNAL = "http://minio:9000";

const RU_MONTHS = [
  "Января", "Февраля", "Марта", "Апреля", "Мая", "Июня",
  "Июля", "Августа", "Сентября", "Октября", "Ноября", "Декабря",
];

function formatDate(iso: string): string {
  const d = new Date(iso);
  const hh = String(d.getHours()).padStart(2, "0");
  const mm = String(d.getMinutes()).padStart(2, "0");
  return `${d.getDate()} ${RU_MONTHS[d.getMonth()]}, ${hh}:${mm}`;
}

function resolvePdfUrl(url: string): string {
  return url.replace(MINIO_INTERNAL, "");
}

// ─── Perforated ticket card ───────────────────────────────────────────────────

function TicketCard({ ticket }: { ticket: TicketResponse }) {
  const { seat } = ticket;
  const { tournament } = seat;

  return (
    // Outer wrapper for the notch overlay trick
    <div className="relative mx-4">

      {/* Top semicircle notch — same colour as page bg to "cut" the card */}
      <div className="absolute -top-3.5 left-1/2 -translate-x-1/2 w-7 h-7 rounded-full bg-[#121212] z-10" />

      {/* Card body */}
      <div className="bg-[#1C1C1E] rounded-3xl overflow-hidden">

        {/* ── Upper half: QR code ── */}
        <div className="flex flex-col items-center px-8 pt-10 pb-6">
          <div className="bg-white rounded-2xl p-4 shadow-2xl">
            <QRCodeSVG
              value={`TICKET-ID-${ticket.id}`}
              size={180}
              bgColor="#FFFFFF"
              fgColor="#000000"
              level="H"
            />
          </div>

          <h2 className="mt-5 text-[18px] font-bold text-white text-center leading-tight">
            {tournament.title}
          </h2>
          <p className="mt-1 text-[13px] text-[#8E8E93] text-center">
            {formatDate(tournament.event_date)}
            <span className="mx-2 text-[#3A3A3C]">|</span>
            ВТБ Арена
          </p>
        </div>

        {/* ── Dashed perforation line with side notches ── */}
        <div className="relative flex items-center px-0">
          {/* Left notch */}
          <div className="w-5 h-5 rounded-full bg-[#121212] flex-shrink-0 -ml-2.5 z-10" />
          {/* Dashed line */}
          <div className="flex-1 border-t-2 border-dashed border-[#2C2C2E]" />
          {/* Right notch */}
          <div className="w-5 h-5 rounded-full bg-[#121212] flex-shrink-0 -mr-2.5 z-10" />
        </div>

        {/* ── Lower half: seat details for steward ── */}
        <div className="px-6 pt-5 pb-8">
          <div className="grid grid-cols-3 gap-2 text-center">
            <div className="flex flex-col gap-1">
              <p className="text-[11px] text-[#8E8E93] uppercase tracking-wider">Сектор</p>
              <p className="text-[24px] font-extrabold text-white leading-none">{seat.sector}</p>
            </div>
            <div className="flex flex-col gap-1">
              <p className="text-[11px] text-[#8E8E93] uppercase tracking-wider">Ряд</p>
              <p className="text-[24px] font-extrabold text-white leading-none">{seat.row}</p>
            </div>
            <div className="flex flex-col gap-1">
              <p className="text-[11px] text-[#8E8E93] uppercase tracking-wider">Место</p>
              <p className="text-[24px] font-extrabold text-white leading-none">{seat.number}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Bottom semicircle notch */}
      <div className="absolute -bottom-3.5 left-1/2 -translate-x-1/2 w-7 h-7 rounded-full bg-[#121212] z-10" />
    </div>
  );
}

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

export default function TicketDetailPage({
  params,
}: {
  params: { id: string };
}) {
  const router   = useRouter();
  const targetId = Number(params.id);

  const [ticket, setTicket]   = useState<TicketResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [walletToast, setWalletToast] = useState(false);

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

    async function load() {
      try {
        const all = await getMyTicketsApi();
        if (cancelled) return;
        const found = all.find((t) => t.id === targetId) ?? null;
        if (found) {
          setTicket(found);
        } else {
          setNotFound(true);
        }
      } catch (err) {
        if (cancelled) return;
        const axiosErr = err as AxiosError;
        if (axiosErr.response?.status === 401) {
          router.push("/");
          return;
        }
        setNotFound(true);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    void load();
    return () => { cancelled = true; };
  }, [router, targetId]);

  function handleWalletClick() {
    setWalletToast(true);
    setTimeout(() => setWalletToast(false), 2500);
  }

  function handleDownloadPdf() {
    if (!ticket?.pdf_url) return;
    const url = resolvePdfUrl(ticket.pdf_url);
    window.open(url, "_blank", "noopener,noreferrer");
  }

  // ── Loading state ──
  if (loading) {
    return (
      <div className="flex justify-center min-h-screen bg-[#121212]">
        <div className="w-full max-w-[390px] flex flex-col">
          <div className="flex items-center gap-3 px-5 pt-12 pb-4">
            <div className="w-9 h-9 rounded-full bg-[#1C1C1E] animate-pulse" />
            <div className="h-6 w-24 rounded-lg bg-[#1C1C1E] animate-pulse" />
          </div>
          <div className="mx-4 mt-4 rounded-3xl bg-[#1C1C1E] h-[460px] animate-pulse" />
        </div>
      </div>
    );
  }

  // ── Not found state ──
  if (notFound || !ticket) {
    return (
      <div className="flex justify-center min-h-screen bg-[#121212]">
        <div className="w-full max-w-[390px] flex flex-col items-center justify-center gap-4 px-5">
          <p className="text-[#8E8E93] text-center">Билет не найден.</p>
          <button
            onClick={() => router.push("/tickets")}
            className="text-[#E32636] font-semibold"
          >
            ← К списку билетов
          </button>
        </div>
      </div>
    );
  }

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

        {/* ── Header ── */}
        <div className="flex items-center gap-3 px-5 pt-12 pb-5">
          <button
            onClick={() => router.back()}
            aria-label="Назад"
            className="w-9 h-9 flex items-center justify-center rounded-full bg-[#1C1C1E] text-white flex-shrink-0"
          >
            <ArrowLeft size={18} strokeWidth={2.5} />
          </button>
          <h1 className="text-[22px] font-bold text-white">Билет</h1>
        </div>

        {/* ── Wallet toast ── */}
        <div
          className={`fixed top-14 left-1/2 -translate-x-1/2 z-50 transition-all duration-300 pointer-events-none ${
            walletToast ? "opacity-100 translate-y-0" : "opacity-0 -translate-y-1"
          }`}
          aria-live="polite"
        >
          <div className="flex items-center gap-2 bg-[#1C1C1E] border border-[#2C2C2E] text-white text-[13px] font-medium px-5 py-2.5 rounded-full shadow-xl whitespace-nowrap">
            <Wallet size={14} className="text-[#8E8E93]" />
            Функция в разработке
          </div>
        </div>

        {/* ── Ticket card with perforated design ── */}
        <TicketCard ticket={ticket} />

        {/* ── Validity badge ── */}
        <div className="flex justify-center mt-7">
          <div className="flex items-center gap-2 bg-[#1C1C1E] border border-[#2C2C2E] rounded-full px-5 py-2">
            <CheckCircle2 size={15} className="text-[#16A34A]" strokeWidth={2.5} />
            <span className="text-[13px] font-medium text-white">Билет действителен</span>
          </div>
        </div>

        {/* ── Action buttons ── */}
        <div className="px-5 mt-5 space-y-3">
          {/* Wallet */}
          <button
            onClick={handleWalletClick}
            className="w-full flex items-center justify-center gap-2 bg-[#E32636] hover:bg-[#C41E2A] active:scale-95 transition-all text-white text-[16px] font-semibold py-4 rounded-2xl"
          >
            <Wallet size={18} strokeWidth={2} />
            Добавить в Wallet
          </button>

          {/* Download PDF */}
          <button
            onClick={handleDownloadPdf}
            disabled={!ticket.pdf_url}
            className="w-full flex items-center justify-center gap-2 bg-[#1C1C1E] hover:bg-[#2C2C2E] disabled:opacity-40 disabled:cursor-not-allowed active:scale-95 transition-all text-white text-[16px] font-semibold py-4 rounded-2xl border border-[#2C2C2E]"
          >
            <Download size={18} strokeWidth={2} />
            Скачать
          </button>
        </div>

      </div>
    </div>
  );
}
