"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { SlidersHorizontal, CalendarDays, Ticket, User } from "lucide-react";
import type { AxiosError } from "axios";
import { getMyTicketsApi, type TicketResponse } from "@/api/client";

// ─── Date formatter ───────────────────────────────────────────────────────────

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

// ─── Skeleton card ────────────────────────────────────────────────────────────

function SkeletonCard() {
  return (
    <div className="bg-[#1C1C1E] rounded-2xl p-3 animate-pulse">
      <div className="flex gap-3 mb-3">
        <div className="w-20 h-20 rounded-xl bg-[#2C2C2E] flex-shrink-0" />
        <div className="flex-1 space-y-2 pt-1">
          <div className="h-4 bg-[#2C2C2E] rounded w-3/4" />
          <div className="h-3 bg-[#2C2C2E] rounded w-1/2" />
          <div className="h-3 bg-[#2C2C2E] rounded w-2/3" />
        </div>
      </div>
      <div className="h-10 bg-[#2C2C2E] rounded-xl" />
    </div>
  );
}

// ─── Ticket card ──────────────────────────────────────────────────────────────

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

  const POSTER =
    "https://images.unsplash.com/photo-1549719386-74dfcbf7dbed?w=400&q=80";

  return (
    <div className="bg-[#1C1C1E] rounded-2xl overflow-hidden">
      <div className="flex gap-3 p-3">
        {/* Event poster */}
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={POSTER}
          alt={tournament.title}
          className="w-20 h-20 rounded-xl object-cover flex-shrink-0"
        />

        {/* Info */}
        <div className="flex-1 min-w-0 flex flex-col justify-between py-0.5">
          <p className="text-[15px] font-bold text-white leading-snug line-clamp-2">
            {tournament.title}
          </p>
          <p className="text-[12px] text-[#8E8E93] mt-1">
            {formatDate(tournament.event_date)}
          </p>
          <p className="text-[12px] text-[#8E8E93]">
            Сектор:{" "}
            <span className="text-white font-medium">{seat.sector}</span>
            , Ряд:{" "}
            <span className="text-white font-medium">{seat.row}</span>
            , Место:{" "}
            <span className="text-white font-medium">{seat.number}</span>
          </p>
        </div>
      </div>

      {/* CTA — Link обеспечивает prefetch и семантику навигации */}
      <div className="px-3 pb-3">
        <Link
          href={`/tickets/${ticket.id}`}
          className="block w-full bg-[#E32636] hover:bg-[#C41E2A] active:scale-95 transition-all text-white text-[15px] font-semibold py-3 rounded-xl text-center"
        >
          Открыть билет
        </Link>
      </div>
    </div>
  );
}

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

type Tab = "active" | "history";

const NAV_ITEMS = [
  { label: "События",    icon: CalendarDays, href: "/" },
  { label: "Мои билеты", icon: Ticket,       href: "/tickets" },
  { label: "Профиль",    icon: User,         href: "/profile" },
] as const;

export default function TicketsPage() {
  const router = useRouter();

  const [tickets, setTickets]   = useState<TicketResponse[]>([]);
  const [loading, setLoading]   = useState(true);
  const [error, setError]       = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<Tab>("active");

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

    async function load() {
      try {
        const data = await getMyTicketsApi();
        if (!cancelled) setTickets(data);
      } catch (err) {
        if (cancelled) return;
        const axiosErr = err as AxiosError;
        if (axiosErr.response?.status === 401) {
          router.push("/");
          return;
        }
        setError("Не удалось загрузить билеты. Попробуйте позже.");
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

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

  // For now "active" shows PAID/SCANNED, "history" shows REFUNDED — all come
  // from the same /tickets/me endpoint which already filters by PAID
  const displayed =
    activeTab === "active"
      ? tickets.filter((t) => t.status === "PAID" || t.status === "SCANNED")
      : tickets.filter((t) => t.status === "REFUNDED");

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

        {/* ── Header ── */}
        <div className="flex items-center justify-between px-5 pt-12 pb-4">
          <h1 className="text-[32px] font-bold text-white leading-tight">
            Мои билеты
          </h1>
          <button
            aria-label="Фильтры"
            className="w-9 h-9 flex items-center justify-center rounded-full bg-[#1C1C1E] text-white"
          >
            <SlidersHorizontal size={17} strokeWidth={2} />
          </button>
        </div>

        {/* ── Tabs ── */}
        <div className="mx-5 mb-4 flex bg-[#1C1C1E] rounded-full p-1">
          {(["active", "history"] as Tab[]).map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`flex-1 py-2 text-[14px] font-semibold rounded-full transition-colors ${
                activeTab === tab
                  ? "bg-white text-[#121212]"
                  : "text-[#8E8E93]"
              }`}
            >
              {tab === "active" ? "Активные" : "История"}
            </button>
          ))}
        </div>

        {/* ── Content ── */}
        <div className="flex-1 overflow-y-auto px-4 pb-24 space-y-3">
          {loading ? (
            <>
              <SkeletonCard />
              <SkeletonCard />
              <SkeletonCard />
            </>
          ) : error ? (
            <div className="flex flex-col items-center justify-center py-16 gap-3">
              <p className="text-[#8E8E93] text-center text-[14px]">{error}</p>
              <button
                onClick={() => { setLoading(true); setError(null); }}
                className="text-[#E32636] text-[14px] font-semibold"
              >
                Повторить
              </button>
            </div>
          ) : displayed.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 gap-3">
              <Ticket size={44} className="text-[#2C2C2E]" />
              <p className="text-[#8E8E93] text-[14px] text-center">
                {activeTab === "active" ? "Нет активных билетов" : "История пуста"}
              </p>
            </div>
          ) : (
            displayed.map((ticket) => (
              <TicketCard key={ticket.id} ticket={ticket} />
            ))
          )}
        </div>

        {/* ── Bottom navigation ── */}
        <nav className="fixed bottom-0 left-1/2 -translate-x-1/2 w-full max-w-[390px] bg-[#1C1C1E] border-t border-[#2C2C2E]">
          <div className="flex">
            {NAV_ITEMS.map(({ label, icon: Icon, href }) => {
              const isActive = href === "/tickets";
              return (
                <Link
                  key={label}
                  href={href}
                  className={`flex-1 flex flex-col items-center gap-1 py-3 text-[10px] font-medium transition-colors ${
                    isActive ? "text-white" : "text-[#8E8E93]"
                  }`}
                >
                  <Icon size={22} strokeWidth={isActive ? 2.5 : 1.8} />
                  {label}
                </Link>
              );
            })}
          </div>
        </nav>

      </div>
    </div>
  );
}
