"use client";

import { useRef } from "react";
import { Layers, Filter, ChevronDown, Info, Map as MapIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { BASEMAPS, HEADER_THEMES } from "@/lib/constants";
import { useClickOutside } from "@/hooks/useClickOutside";

interface MapHeaderProps {
  basemapId: string;
  setBasemapId: (id: string) => void;
  day: number;
  hour: number;
  /** When set, show calendar date in header (e.g. "27 Aug 06:00") */
  dateLabel?: string | null;
  activeN: number;
  beachedN: number;
  filtersOpen: boolean;
  setFiltersOpen: (v: boolean) => void;
  infoOpen: boolean;
  setInfoOpen: (v: boolean) => void;
  showTrails: boolean;
  setShowTrails: (v: boolean) => void;
  showActiveParticles: boolean;
  setShowActiveParticles: (v: boolean) => void;
  showBeachedParticles: boolean;
  setShowBeachedParticles: (v: boolean) => void;
}

export function MapHeader({
  basemapId,
  setBasemapId,
  day,
  hour,
  dateLabel = null,
  activeN,
  beachedN,
  filtersOpen,
  setFiltersOpen,
  infoOpen,
  setInfoOpen,
  showTrails,
  setShowTrails,
  showActiveParticles,
  setShowActiveParticles,
  showBeachedParticles,
  setShowBeachedParticles,
}: MapHeaderProps) {
  const filtersRef = useRef<HTMLDivElement>(null);
  const infoRef = useRef<HTMLDivElement>(null);
  useClickOutside(filtersRef, filtersOpen, () => setFiltersOpen(false));
  useClickOutside(infoRef, infoOpen, () => setInfoOpen(false));

  const theme = HEADER_THEMES[basemapId] ?? HEADER_THEMES.dark;

  return (
    <header
      className={`absolute left-0 right-0 top-0 z-10 flex items-center justify-between gap-6 px-5 py-3 shadow-xl backdrop-blur-xl border-b ${theme.bg} ${theme.border} ${theme.text}`}
    >
      <div className="flex items-center gap-6 min-w-0">
        <div className="flex items-center gap-3 shrink-0">
          <div
            className={`flex size-9 items-center justify-center rounded-lg ring-1 ${theme.accentMuted} ${theme.accent}`}
          >
            <Layers className="size-5" />
          </div>
          <div>
            <h1
              className={`text-base font-bold tracking-tight leading-tight ${theme.text}`}
            >
              Lagrangian trajectories · UPC
            </h1>
            <p className={`text-[11px] font-medium ${theme.subtitle}`}>
              Catalan coast · 72 h
            </p>
          </div>
        </div>
        <div className="hidden sm:block h-8 w-px bg-slate-600/80 shrink-0" />
        <div className="flex items-center gap-4 shrink-0">
          <div
            className={`flex items-center gap-2 rounded-lg px-3 py-1.5 border ${theme.card}`}
          >
            <span
              className={`text-[11px] uppercase tracking-wider font-medium ${theme.subtitle}`}
            >
              Time
            </span>
            <span
              className={`text-sm font-semibold tabular-nums ${theme.text}`}
            >
              {dateLabel ?? `Day ${day} · ${hour.toString().padStart(2, "0")}:00`}
            </span>
          </div>
          <div className="flex items-center gap-2">
            <div className="flex items-center gap-1.5 rounded-md bg-teal-500/10 px-2.5 py-1 border border-teal-500/20">
              <span className="size-2 rounded-full bg-teal-400 shrink-0" />
              <span className="text-sm font-semibold text-teal-300 tabular-nums">
                {activeN.toLocaleString()}
              </span>
              <span className={`text-[11px] ${theme.subtitle}`}>active</span>
            </div>
            <div className="flex items-center gap-1.5 rounded-md bg-red-500/10 px-2.5 py-1 border border-red-500/20">
              <span className="size-2 rounded-full bg-red-500 shrink-0" />
              <span className="text-sm font-semibold text-red-400 tabular-nums">
                {beachedN.toLocaleString()}
              </span>
              <span className={`text-[11px] ${theme.subtitle}`}>beached</span>
            </div>
          </div>
        </div>
      </div>
      <div className="flex items-center gap-2 shrink-0" ref={filtersRef}>
        <div className="relative" ref={infoRef}>
          <Button
            variant="ghost"
            size="sm"
            className={`gap-2 rounded-lg px-3.5 py-2.5 text-sm font-medium transition-all ${
              infoOpen
                ? "bg-teal-500/15 text-teal-300 border border-teal-500/40"
                : `border ${theme.card} hover:opacity-90 ${theme.text}`
            }`}
            onClick={(e) => {
              e.stopPropagation();
              setInfoOpen(!infoOpen);
            }}
            aria-label="About this project"
            aria-expanded={infoOpen}
          >
            <Info className="size-4" />
            Info
          </Button>
          {infoOpen && (
            <div className="absolute right-0 top-full z-50 mt-2 w-96 max-w-[calc(100vw-2rem)] rounded-2xl border border-slate-600/80 bg-slate-800/98 shadow-2xl overflow-hidden">
              <div className="p-4 space-y-3 text-sm">
                <h3 className="font-semibold text-white">
                  Lagrangian trajectory viewer · UPC
                </h3>
                <p className="text-slate-400">
                  This viewer shows a{" "}
                  <strong className="text-slate-300">
                    Lagrangian particle simulation
                  </strong>{" "}
                  of the NW Mediterranean: particles are released from the
                  Catalan coast and advected by a synthetic current field for 72
                  hours.
                </p>
                <p className="text-slate-400">
                  The approach is consistent with{" "}
                  <a
                    href="https://oceanparcels.org/"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-teal-400 hover:underline"
                  >
                    Ocean Parcels
                  </a>
                  : passive drifters are integrated in time; particles that hit
                  the coast are marked as beached.
                </p>
                <p className="text-xs text-slate-500">
                  Universitat Politècnica de Catalunya (UPC)
                </p>
              </div>
            </div>
          )}
        </div>
        <div className="relative">
          <Button
            variant="ghost"
            size="sm"
            className={`gap-2 rounded-lg px-4 py-2.5 text-sm font-medium transition-all ${
              filtersOpen
                ? "bg-teal-500/15 text-teal-300 border border-teal-500/40 shadow-sm"
                : `border hover:border-slate-500 ${theme.text} ${theme.card} hover:opacity-90`
            }`}
            onClick={(e) => {
              e.stopPropagation();
              setFiltersOpen(!filtersOpen);
            }}
          >
            <Filter className="size-4" />
            Filters
            <ChevronDown
              className={`size-4 transition-transform ${filtersOpen ? "rotate-180" : ""}`}
            />
          </Button>
          {filtersOpen && (
            <div className="absolute right-0 top-full z-50 mt-2 w-80 rounded-2xl border border-slate-600/80 bg-slate-800/98 shadow-2xl overflow-hidden">
              <div className="bg-slate-700/50 px-4 py-3 border-b border-slate-600/80">
                <span className="flex items-center gap-2 text-sm font-semibold text-slate-200">
                  <Layers className="size-4 text-teal-400" />
                  Layers &amp; basemap
                </span>
                <p className="text-[11px] text-slate-500 mt-1">
                  Basemap i capes
                </p>
              </div>
              <div className="max-h-[70vh] overflow-y-auto p-4 space-y-5">
                <div className="space-y-3">
                  <p className="text-xs font-medium uppercase tracking-wider text-slate-400">
                    Basemap
                  </p>
                  <div className="grid grid-cols-2 gap-2.5">
                    {BASEMAPS.map((b) => {
                      const isImage =
                        b.thumb.startsWith("/") || b.thumb.startsWith("http");
                      const selected = basemapId === b.id;
                      return (
                        <button
                          key={b.id}
                          type="button"
                          onClick={() => setBasemapId(b.id)}
                          className={`flex flex-col overflow-hidden rounded-xl border-2 text-left transition-all ${
                            selected
                              ? "border-teal-400 ring-2 ring-teal-400/30 shadow-lg shadow-teal-500/10"
                              : "border-slate-600 hover:border-slate-500 bg-slate-700/40"
                          }`}
                        >
                          <div className="relative h-14 w-full shrink-0 overflow-hidden bg-slate-700">
                            {isImage ? (
                              <img
                                src={b.thumb}
                                alt={b.name}
                                className="h-full w-full object-cover"
                                onError={(e) => {
                                  e.currentTarget.style.display = "none";
                                }}
                              />
                            ) : (
                              <div
                                className="h-full w-full"
                                style={{ background: b.thumb }}
                              />
                            )}
                            <div className="absolute inset-0 flex items-center justify-center opacity-40">
                              <MapIcon className="size-6 text-slate-400" />
                            </div>
                            {selected && (
                              <div className="absolute inset-0 bg-teal-500/10 pointer-events-none" />
                            )}
                          </div>
                          <span
                            className={`px-2.5 py-1.5 text-xs font-medium ${selected ? "text-teal-300" : "text-slate-300"}`}
                          >
                            {b.name}
                          </span>
                        </button>
                      );
                    })}
                  </div>
                </div>
                <div className="space-y-3 pt-1 border-t border-slate-600/80">
                  <p className="text-xs font-medium uppercase tracking-wider text-slate-400">
                    Overlays
                  </p>
                  <div className="space-y-3 rounded-xl bg-slate-700/30 p-3">
                    <div className="flex items-center justify-between gap-3">
                      <div>
                        <Label
                          htmlFor="layer-trails"
                          className="text-sm text-slate-200 cursor-pointer"
                        >
                          Trajectories
                        </Label>
                        <p className="text-[11px] text-slate-500">
                          Particle paths over time
                        </p>
                      </div>
                      <Switch
                        id="layer-trails"
                        checked={showTrails}
                        onCheckedChange={setShowTrails}
                      />
                    </div>
                    <div className="flex items-center justify-between gap-3">
                      <div className="flex items-center gap-2 min-w-0">
                        <span className="size-2 rounded-full bg-teal-400 shrink-0" />
                        <div>
                          <Label
                            htmlFor="layer-active"
                            className="text-sm text-slate-200 cursor-pointer"
                          >
                            Active particles
                          </Label>
                          <p className="text-[11px] text-slate-500">
                            In water
                          </p>
                        </div>
                      </div>
                      <Switch
                        id="layer-active"
                        checked={showActiveParticles}
                        onCheckedChange={setShowActiveParticles}
                      />
                    </div>
                    <div className="flex items-center justify-between gap-3">
                      <div className="flex items-center gap-2 min-w-0">
                        <span className="size-2 rounded-full bg-red-500 shrink-0" />
                        <div>
                          <Label
                            htmlFor="layer-beached"
                            className="text-sm text-slate-200 cursor-pointer"
                          >
                            Beached particles
                          </Label>
                          <p className="text-[11px] text-slate-500">
                            On coast
                          </p>
                        </div>
                      </div>
                      <Switch
                        id="layer-beached"
                        checked={showBeachedParticles}
                        onCheckedChange={setShowBeachedParticles}
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
