"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import {
  ChevronDown,
  Crown,
  Dice5,
  Gift,
  Home,
  LifeBuoy,
  Menu,
  Search,
  Settings,
  TicketCheck,
  Trophy,
  UserRound,
  X
} from "lucide-react";
import { Brand } from "@/components/brand";
import { BetSlip, useBetSlip } from "@/components/bet-slip";
import { SportGlyph } from "@/components/sport-glyph";
import { cn } from "@/lib/utils";

const authenticatedMenuLinks = [
  { href: "/", label: "Accueil", icon: Home },
  { href: "/sports", label: "Paris sportifs", icon: Trophy },
  { href: "/casino", label: "Casino", icon: Dice5 },
  { href: "/bets", label: "Mes Paris", icon: TicketCheck },
  { href: "/profile", label: "Mon profil", icon: UserRound },
  { href: "/vip", label: "VIP & Bonus", icon: Crown },
  { href: "/promotions", label: "Promotions", icon: Gift },
  { href: "/settings", label: "Paramètres", icon: Settings },
  { href: "/help", label: "Besoin d'aide ?", icon: LifeBuoy }
];

const guestMenuLinks = [
  { href: "/", label: "Accueil", icon: Home },
  { href: "/sports", label: "Paris sportifs", icon: Trophy },
  { href: "/casino", label: "Casino", icon: Dice5 },
  { href: "/promotions", label: "Promotions", icon: Gift },
  { href: "/help", label: "Besoin d'aide ?", icon: LifeBuoy }
];

const popularSports = [
  { href: "/sports/football", slug: "football", label: "Football", iconClass: "text-emerald-400", bgClass: "bg-emerald-400/10" },
  { href: "/sports/tennis", slug: "tennis", label: "Tennis", iconClass: "text-lime-300", bgClass: "bg-lime-300/10" },
  { href: "/sports/basketball", slug: "basketball", label: "Basketball", iconClass: "text-orange-300", bgClass: "bg-orange-300/10" },
  { href: "/sports/rugby", slug: "rugby", label: "Rugby", iconClass: "text-slate-200", bgClass: "bg-slate-200/10" },
  { href: "/sports/american-football", slug: "american-football", label: "Football Américain", iconClass: "text-cyan-300", bgClass: "bg-cyan-300/10" },
  { href: "/sports/hockey", slug: "hockey", label: "Hockey sur glace", iconClass: "text-felt", bgClass: "bg-felt/10" },
  { href: "/sports/volleyball", slug: "volleyball", label: "Volleyball", iconClass: "text-green-300", bgClass: "bg-green-300/10" },
  { href: "/sports/handball", slug: "handball", label: "Handball", iconClass: "text-zinc-300", bgClass: "bg-zinc-300/10" },
  { href: "/sports/table-tennis", slug: "table-tennis", label: "Tennis de table", iconClass: "text-lime-400", bgClass: "bg-lime-400/10" },
  { href: "/sports/mma", slug: "mma", label: "MMA", iconClass: "text-felt", bgClass: "bg-felt/10" }
];

type SearchEvent = {
  id: string;
  homeName: string;
  awayName: string;
  startsAt: string;
  isLive: boolean;
  sport: { slug: string; name: string };
  competition: { name: string; country: string };
};

type SearchSport = {
  id: string;
  slug: string;
  name: string;
};

export function MobileDock({
  isAuthenticated,
  onLogout
}: {
  isAuthenticated: boolean;
  onLogout?: () => void;
}) {
  const pathname = usePathname();
  const { selections } = useBetSlip();
  const [open, setOpen] = useState(false);
  const [sportsOpen, setSportsOpen] = useState(false);
  const [couponOpen, setCouponOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [matchSearch, setMatchSearch] = useState("");
  const [events, setEvents] = useState<SearchEvent[]>([]);
  const [searchSports, setSearchSports] = useState<SearchSport[]>([]);
  const isSportsPage = pathname === "/sports" || pathname?.startsWith("/sports/") || pathname?.startsWith("/events/");
  const isCasinoPage = pathname === "/casino" || pathname?.startsWith("/casino/");
  const primaryDockItem = isSportsPage
    ? { href: "/casino", label: "Casino", icon: Dice5 }
    : { href: "/sports", label: isCasinoPage ? "Sports" : "Sports", icon: Trophy };
  const couponDockItem = { href: "#coupon", label: "Coupon", icon: TicketCheck, opensCoupon: true };
  const searchDockItem = { href: "#search", label: "Chercher", icon: Search, opensSearch: true };
  const vipDockItem = { href: "/vip", label: "VIP", icon: Crown };
  const promotionsDockItem = { href: "/promotions", label: "Promos", icon: Gift };
  const visibleDock = isAuthenticated
    ? [primaryDockItem, couponDockItem, searchDockItem, vipDockItem]
    : isSportsPage
      ? [primaryDockItem, couponDockItem, searchDockItem, promotionsDockItem]
      : [primaryDockItem, searchDockItem, promotionsDockItem];
  const dockColumnClass = visibleDock.length + 1 >= 5 ? "grid-cols-5" : "grid-cols-4";
  const visibleMenuLinks = isAuthenticated ? authenticatedMenuLinks : guestMenuLinks;
  const query = matchSearch.trim().toLowerCase();
  const matchResults = useMemo(
    () =>
      query
        ? events
            .filter((event) =>
              [event.homeName, event.awayName, event.competition.name, event.competition.country, event.sport.name]
                .join(" ")
                .toLowerCase()
                .includes(query)
            )
            .slice(0, 6)
        : [],
    [events, query]
  );

  useEffect(() => {
    if (!searchOpen || (events.length && searchSports.length)) return;
    let cancelled = false;

    async function loadEvents() {
      try {
        const response = await fetch("/api/sports/events", { cache: "no-store" });
        const payload = await response.json();
        if (!cancelled && payload.ok) {
          setEvents(payload.data.events ?? []);
          setSearchSports(payload.data.sports ?? []);
        }
      } catch {
        if (!cancelled) {
          setEvents([]);
          setSearchSports([]);
        }
      }
    }

    void loadEvents();
    return () => {
      cancelled = true;
    };
  }, [events.length, searchOpen, searchSports.length]);

  function closeSports() {
    setSportsOpen(false);
    setMatchSearch("");
  }

  function closeCoupon() {
    setCouponOpen(false);
  }

  function closeSearch() {
    setSearchOpen(false);
    setMatchSearch("");
  }

  function submitSportSearch(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const target = matchResults[0];
    window.location.href = target ? `/events/${target.id}` : "/sports";
  }

  return (
    <>
      {sportsOpen ? (
        <div className="fixed inset-x-0 top-0 z-[58] bottom-[calc(4.65rem+env(safe-area-inset-bottom))] bg-black/58 lg:hidden" onClick={closeSports}>
          <aside
            className="h-full w-[82vw] max-w-[430px] overflow-y-auto border-r border-white/10 bg-[#070c16] shadow-[18px_0_48px_rgba(0,0,0,.54)]"
            onClick={(event) => event.stopPropagation()}
          >
            <div className="border-b border-white/10 px-4 pb-4 pt-4">
              <Brand />
              <form onSubmit={submitSportSearch} className="mt-4 flex h-12 items-center gap-2 rounded-xl border border-white/10 bg-white/[0.045] p-1.5">
                <Search className="ml-2 h-4 w-4 shrink-0 text-slate-500" />
                <input
                  value={matchSearch}
                  onChange={(event) => setMatchSearch(event.target.value)}
                  placeholder="Rechercher un match..."
                  className="h-full min-w-0 flex-1 border-0 bg-transparent p-0 text-sm font-semibold text-white placeholder:text-slate-500 focus:ring-0"
                />
                <button className="grid h-9 w-9 shrink-0 place-items-center rounded-xl bg-felt text-white shadow-[0_10px_22px_rgba(15,191,143,.28)]" aria-label="Rechercher">
                  <Search className="h-5 w-5" />
                </button>
              </form>
            </div>

            <nav className="pb-6">
              <Link href="/" onClick={closeSports} className="flex h-11 items-center gap-3 border-l-4 border-felt bg-felt/10 px-4 text-sm font-bold text-white">
                <span className="grid h-6 w-6 place-items-center text-felt">
                  <Home className="h-5 w-5" />
                </span>
                Accueil
              </Link>
              {query ? (
                <div className="border-t border-white/10 px-4 py-4">
                  <div className="text-[11px] font-black uppercase tracking-[0.08em] text-slate-500">Matchs</div>
                  <div className="mt-2 space-y-1.5">
                    {matchResults.length ? (
                      matchResults.map((event) => (
                        <Link
                          key={event.id}
                          href={`/events/${event.id}`}
                          onClick={closeSports}
                          className="flex min-h-12 items-center gap-2.5 rounded-lg bg-white/[0.035] px-2.5 py-2 text-xs font-semibold text-slate-300"
                        >
                          <span className="grid h-7 w-7 shrink-0 place-items-center rounded-lg bg-felt/10">
                            <SportGlyph slug={event.sport.slug} label={event.sport.name} className="h-4 w-4 text-felt" />
                          </span>
                          <span className="min-w-0 flex-1">
                            <span className="block truncate text-[13px] font-bold text-white">{event.homeName} - {event.awayName}</span>
                            <span className="block truncate text-[11px] text-slate-500">{event.competition.name} · {formatMatchTime(event.startsAt, event.isLive)}</span>
                          </span>
                        </Link>
                      ))
                    ) : (
                      <div className="rounded-lg border border-white/10 bg-white/[0.025] px-3 py-2 text-xs font-semibold text-slate-500">
                        Aucun match trouvé.
                      </div>
                    )}
                  </div>
                </div>
              ) : null}

              <div className="px-4 pt-4 text-[11px] font-black uppercase tracking-[0.08em] text-slate-500">Populaire</div>
              <div className="mt-2 space-y-1 px-4">
                {popularSports.map((sport) => (
                  <Link
                    key={sport.href}
                    href={sport.href}
                    onClick={closeSports}
                    className="flex h-10 items-center gap-3 rounded-lg text-sm font-semibold text-slate-300 transition hover:bg-white/[0.045] hover:text-white"
                  >
                    <span className={cn("grid h-[30px] w-[30px] place-items-center rounded-lg", sport.bgClass)}>
                      <SportGlyph slug={sport.slug} label={sport.label} className={cn("h-[22px] w-[22px]", sport.iconClass)} />
                    </span>
                    <span className="truncate">{sport.label}</span>
                  </Link>
                ))}
              </div>
            </nav>
          </aside>
        </div>
      ) : null}

      {couponOpen ? (
        isAuthenticated ? (
          <BetSlip compact open={couponOpen} isAuthenticated onClose={closeCoupon} />
        ) : (
          <GuestCouponPrompt onClose={closeCoupon} />
        )
      ) : null}
      {searchOpen ? (
        <SearchPanel
          query={matchSearch}
          events={matchResults}
          sports={searchSports}
          onQueryChange={setMatchSearch}
          onClose={closeSearch}
        />
      ) : null}

      {open ? (
        <div className="fixed inset-0 z-50 bg-black/55 lg:hidden" onClick={() => setOpen(false)}>
          <aside
            className="ml-auto flex h-full w-[78vw] max-w-[330px] flex-col border-l border-white/10 bg-ink-950 p-3 shadow-panel"
            onClick={(event) => event.stopPropagation()}
          >
            <div className="flex items-center justify-between">
              <div className="flex gap-2">
                <button className="rounded-lg bg-white/[0.06] px-3 py-2 text-xs font-black text-white">🇫🇷 FR</button>
                <button className="rounded-lg bg-white/[0.06] px-3 py-2 text-xs font-black text-white">€ EUR</button>
              </div>
              <button onClick={() => setOpen(false)} className="grid h-9 w-9 place-items-center rounded-full bg-white/[0.06] text-slate-300" aria-label="Fermer le menu">
                <X className="h-4 w-4" />
              </button>
            </div>

            {isAuthenticated ? (
              <div className="mt-3">
                <button
                  onClick={() => {
                    setOpen(false);
                    onLogout?.();
                  }}
                  className="grid h-9 w-full place-items-center rounded-lg border border-white/10 bg-white/[0.06] text-xs font-extrabold text-white"
                >
                  Déconnexion
                </button>
              </div>
            ) : (
              <div className="mt-3 grid grid-cols-2 gap-2 rounded-lg border border-felt/15 bg-felt/10 p-2">
                <Link href="/login" className="grid h-9 place-items-center rounded-lg bg-white/[0.08] text-xs font-extrabold text-white" onClick={() => setOpen(false)}>
                  Se connecter
                </Link>
                <Link href="/register" className="grid h-9 place-items-center rounded-lg bg-felt text-xs font-extrabold text-ink-950" onClick={() => setOpen(false)}>
                  S'inscrire
                </Link>
              </div>
            )}

            <label className="mt-3 flex h-10 items-center gap-2 rounded-lg border border-white/10 bg-white/[0.04] px-3 text-slate-400">
              <Search className="h-4 w-4" />
              <input placeholder="Rechercher équipe, ligue..." className="h-full min-w-0 flex-1 border-0 bg-transparent p-0 text-sm text-white placeholder:text-slate-500 focus:ring-0" />
            </label>

            <nav className="mt-3 space-y-1.5">
              {visibleMenuLinks.map((item) => (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={() => setOpen(false)}
                  className="flex h-10 items-center justify-between rounded-lg bg-white/[0.04] px-2.5 text-xs font-bold text-slate-200"
                >
                  <span className="flex items-center gap-2.5">
                    <span className="grid h-7 w-7 place-items-center rounded-lg bg-white/[0.06] text-slate-300">
                      <item.icon className="h-4 w-4" />
                    </span>
                    {item.label}
                  </span>
                  <span className="text-slate-600">›</span>
                </Link>
              ))}
            </nav>
          </aside>
        </div>
      ) : null}

      <nav className={cn("fixed inset-x-0 bottom-0 z-50 grid border-t border-white/10 bg-ink-950/95 px-1.5 pb-[max(0.5rem,env(safe-area-inset-bottom))] pt-2 backdrop-blur lg:hidden", dockColumnClass)}>
        {visibleDock.map((item) =>
          "opensSports" in item && item.opensSports ? (
            <button
              key={item.href}
              onClick={() => {
                setOpen(false);
                setCouponOpen(false);
                setSportsOpen((value) => !value);
              }}
              className={cn(
                "relative flex min-w-0 flex-col items-center gap-1 rounded-lg px-1 py-1 text-[10px] font-semibold",
                sportsOpen ? "text-felt" : "text-slate-300"
              )}
            >
              {sportsOpen ? <span className="absolute -top-2 h-0.5 w-10 rounded-full bg-felt shadow-[0_0_18px_rgba(15,191,143,.7)]" /> : null}
              <item.icon className="h-5 w-5" />
              <span className="max-w-full truncate">{item.label}</span>
            </button>
          ) : "opensCoupon" in item && item.opensCoupon ? (
            <button
              key={item.href}
              onClick={() => {
                setOpen(false);
                closeSports();
                closeSearch();
                setCouponOpen((value) => !value);
              }}
              className={cn(
                "relative flex min-w-0 flex-col items-center gap-1 rounded-lg px-1 py-1 text-[10px] font-semibold",
                couponOpen ? "text-felt" : "text-slate-300"
              )}
            >
              {couponOpen ? <span className="absolute -top-2 h-0.5 w-10 rounded-full bg-felt shadow-[0_0_18px_rgba(15,191,143,.7)]" /> : null}
              <span className="relative">
                <item.icon className="h-5 w-5" />
                {selections.length > 0 ? (
                  <span className="absolute -right-2 -top-2 grid h-5 min-w-5 place-items-center rounded-full bg-felt px-1 text-[10px] font-black text-ink-950 ring-2 ring-ink-950">
                    {selections.length}
                  </span>
                ) : null}
              </span>
              <span className="max-w-full truncate">{item.label}</span>
            </button>
          ) : "opensSearch" in item && item.opensSearch ? (
            <button
              key={item.href}
              onClick={() => {
                setOpen(false);
                closeSports();
                closeCoupon();
                setSearchOpen((value) => !value);
              }}
              className={cn(
                "relative flex min-w-0 flex-col items-center gap-1 rounded-lg px-1 py-1 text-[10px] font-semibold",
                searchOpen ? "text-felt" : "text-slate-300"
              )}
            >
              {searchOpen ? <span className="absolute -top-2 h-0.5 w-10 rounded-full bg-felt shadow-[0_0_18px_rgba(15,191,143,.7)]" /> : null}
              <item.icon className="h-5 w-5" />
              <span className="max-w-full truncate">{item.label}</span>
            </button>
          ) : (
            <Link
              href={item.href}
              key={item.href}
              className={cn("flex min-w-0 flex-col items-center gap-1 rounded-lg px-1 py-1 text-[10px] font-semibold text-slate-300")}
              onClick={() => {
                closeSports();
                closeCoupon();
                closeSearch();
              }}
            >
              <item.icon className="h-5 w-5" />
              <span className="max-w-full truncate">{item.label}</span>
            </Link>
          )
        )}
        <button
          onClick={() => {
            closeSports();
            closeCoupon();
            closeSearch();
            setOpen(true);
          }}
          className="flex min-w-0 flex-col items-center gap-1 rounded-lg px-1 py-1 text-[10px] font-semibold text-slate-300"
        >
          <Menu className="h-5 w-5" />
          <span>Menu</span>
        </button>
      </nav>
    </>
  );
}

function GuestCouponPrompt({ onClose }: { onClose: () => void }) {
  return (
    <section className="fixed inset-x-0 bottom-[calc(4.65rem+env(safe-area-inset-bottom))] z-[49] border-t border-white/10 bg-[#090e17] p-3 shadow-panel lg:hidden">
      <div className="rounded-lg border border-white/10 bg-[#121821] p-3">
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <div className="flex items-center gap-2 text-sm font-black text-white">
              <TicketCheck className="h-4 w-4 text-felt" />
              Coupon
            </div>
            <p className="mt-1 text-xs font-semibold leading-5 text-slate-400">
              Connectez-vous pour placer un pari. Les cotes restent consultables sans compte.
            </p>
          </div>
          <button onClick={onClose} className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-white/[0.06] text-slate-300" aria-label="Fermer le coupon">
            <X className="h-4 w-4" />
          </button>
        </div>
        <div className="mt-3 grid grid-cols-2 gap-2">
          <Link href="/login" onClick={onClose} className="grid h-10 place-items-center rounded-lg border border-white/10 bg-white/[0.06] text-xs font-black text-white">
            Connexion
          </Link>
          <Link href="/register" onClick={onClose} className="grid h-10 place-items-center rounded-lg bg-felt text-xs font-black text-ink-950">
            Inscription
          </Link>
        </div>
      </div>
    </section>
  );
}

function SearchPanel({
  query,
  events,
  sports,
  onQueryChange,
  onClose
}: {
  query: string;
  events: SearchEvent[];
  sports: SearchSport[];
  onQueryChange: (value: string) => void;
  onClose: () => void;
}) {
  const groupedSports = groupSportsByLetter(sports.length ? sports : popularSports.map((sport, index) => ({ id: `${index}`, slug: sport.slug, name: sport.label })));
  const hasQuery = query.trim().length > 0;

  return (
    <section className="fixed inset-x-0 top-0 bottom-[calc(4.65rem+env(safe-area-inset-bottom))] z-[49] overflow-y-auto border-b border-white/10 bg-[#050607] text-white shadow-panel lg:hidden">
      <div className="border-b border-white/10 px-4 py-4">
        <div className="flex items-center gap-2">
          <form
            onSubmit={(event) => {
              event.preventDefault();
              if (events[0]) window.location.href = `/events/${events[0].id}`;
            }}
            className="flex h-12 min-w-0 flex-1 items-center overflow-hidden rounded-lg border border-felt/70 bg-[#10131a] shadow-[0_0_18px_rgba(15,191,143,.08)]"
          >
            <button type="button" className="flex h-full shrink-0 items-center gap-2 border-r border-white/10 bg-white/[0.06] px-3 text-sm font-semibold text-white">
              Sports
              <ChevronDown className="h-4 w-4" />
            </button>
            <input
              value={query}
              onChange={(event) => onQueryChange(event.target.value)}
              placeholder="Rechercher des matchs..."
              className="h-full min-w-0 flex-1 border-0 bg-transparent px-3 text-sm font-semibold text-white placeholder:text-slate-500 focus:ring-0"
              autoFocus
            />
          </form>
          <button onClick={onClose} className="grid h-11 w-11 shrink-0 place-items-center rounded-full text-slate-200 hover:bg-white/[0.07]" aria-label="Fermer la recherche">
            <X className="h-6 w-6" />
          </button>
        </div>

        <div className="-mx-1 mt-4 overflow-x-auto px-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
          <div className="flex gap-2">
            <Link href="/sports" onClick={onClose} className="flex h-10 shrink-0 items-center gap-2 rounded-lg border border-felt/60 bg-felt/10 px-3 text-sm font-extrabold text-felt">
              <span className="grid h-5 w-5 grid-cols-2 gap-0.5" aria-hidden="true">
                <span className="rounded-sm border border-current" />
                <span className="rounded-sm border border-current" />
                <span className="rounded-sm border border-current" />
                <span className="rounded-sm border border-current" />
              </span>
              Tous les sports
            </Link>
            <Link href="/sports" onClick={onClose} className="grid h-10 shrink-0 place-items-center rounded-lg bg-white/[0.08] px-4 text-sm font-bold text-white">
              À venir
            </Link>
          </div>
        </div>
      </div>

      <div className="px-4 py-5">
        {hasQuery ? (
          <div className="space-y-2">
            <h2 className="px-0.5 text-sm font-extrabold text-white">Matchs</h2>
            {events.length ? (
              events.map((event) => (
                <Link key={event.id} href={`/events/${event.id}`} onClick={onClose} className="flex min-h-14 items-center gap-3 rounded-lg border border-white/10 bg-[#11141a] px-3 py-2.5">
                  <span className="grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-felt/10 text-felt">
                    <SportGlyph slug={event.sport.slug} label={event.sport.name} className="h-5 w-5" />
                  </span>
                  <span className="min-w-0 flex-1">
                    <span className="block truncate text-sm font-bold text-white">{event.homeName} - {event.awayName}</span>
                    <span className="mt-0.5 block truncate text-xs font-semibold text-slate-500">
                      {event.competition.name} · {formatMatchTime(event.startsAt, event.isLive)}
                    </span>
                  </span>
                </Link>
              ))
            ) : (
              <div className="rounded-lg border border-white/10 bg-[#11141a] p-4 text-sm font-semibold text-slate-500">Aucun match trouvé.</div>
            )}
          </div>
        ) : (
          <div className="space-y-6">
            {groupedSports.map((group) => (
              <section key={group.letter} className="space-y-2">
                <h2 className="px-0.5 text-sm font-extrabold text-white">{group.letter}</h2>
                <div className="overflow-hidden rounded-lg border border-white/10 bg-[#11141a]">
                  {group.items.map((sport, index) => (
                    <Link
                      key={sport.slug}
                      href={`/sports/${sport.slug}`}
                      onClick={onClose}
                      className={cn(
                        "flex h-14 items-center gap-3 px-4 text-sm font-semibold text-white transition hover:bg-white/[0.045]",
                        index > 0 && "border-t border-white/10"
                      )}
                    >
                      <SportGlyph slug={sport.slug} label={sport.name} className="h-6 w-6 text-felt" />
                      {sport.name}
                    </Link>
                  ))}
                </div>
              </section>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

function formatMatchTime(value: string, isLive: boolean) {
  if (isLive) return "Live";
  return new Intl.DateTimeFormat("fr-FR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(value));
}

function groupSportsByLetter(sports: SearchSport[]) {
  const groups = new Map<string, SearchSport[]>();

  for (const sport of [...sports].sort((left, right) => left.name.localeCompare(right.name))) {
    const letter = sport.name.trim().charAt(0).toUpperCase() || "#";
    const current = groups.get(letter);
    if (current) {
      current.push(sport);
    } else {
      groups.set(letter, [sport]);
    }
  }

  return Array.from(groups.entries()).map(([letter, items]) => ({ letter, items }));
}
