"use client";

import type { VehicleStatsOverview } from "../../../lib/api";

const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));

const formatDateTime = (value?: string | null) => {
  if (!value) {
    return "Brak daty";
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return "Brak daty";
  }

  return new Intl.DateTimeFormat("pl-PL", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  }).format(date);
};

const formatDayLabel = (value?: string | null) => {
  if (!value) {
    return "Brak dnia";
  }

  const date = new Date(`${value}T00:00:00`);
  if (Number.isNaN(date.getTime())) {
    return value;
  }

  return new Intl.DateTimeFormat("pl-PL", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  }).format(date);
};

const formatMonthLabel = (value?: string | null) => {
  if (!value) {
    return "Bieżący miesiąc";
  }

  const date = new Date(`${value}T00:00:00`);
  if (Number.isNaN(date.getTime())) {
    return "Bieżący miesiąc";
  }

  return new Intl.DateTimeFormat("pl-PL", {
    month: "long",
    year: "numeric",
  }).format(date);
};

const formatYearLabel = (value?: string | null) => {
  if (!value) {
    return "Bieżący rok";
  }

  const date = new Date(`${value}T00:00:00`);
  if (Number.isNaN(date.getTime())) {
    return "Bieżący rok";
  }

  return new Intl.DateTimeFormat("pl-PL", {
    year: "numeric",
  }).format(date);
};

const formatStatsValue = (value?: number | null, unit?: "km/h" | "km") => {
  if (value == null || Number.isNaN(value) || !Number.isFinite(value)) {
    return unit ? `0 ${unit}` : "0";
  }

  const rounded = unit === "km" ? Math.round(value) : Math.ceil(value);
  return unit ? `${rounded} ${unit}` : String(rounded);
};

function StatsSpeedGauge({ speed }: { speed?: number | null }) {
  const maxSpeed = 180;
  const safeSpeed = clamp(Number.isFinite(speed ?? NaN) ? Number(speed) : 0, 0, maxSpeed);
  const ratio = safeSpeed / maxSpeed;
  const needleAngle = -120 + ratio * 240;

  return (
    <div className="relative h-[88px] w-[170px] overflow-hidden">
      <svg viewBox="0 0 200 110" className="h-full w-full" aria-hidden="true">
        <defs>
          <linearGradient id="stats-speed-arc" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0%" stopColor="#58ff7d" />
            <stop offset="48%" stopColor="#fff15a" />
            <stop offset="78%" stopColor="#ff9d2f" />
            <stop offset="100%" stopColor="#ff4d4d" />
          </linearGradient>
          <filter id="stats-speed-glow" x="-30%" y="-30%" width="160%" height="160%">
            <feGaussianBlur stdDeviation="2.5" result="blur" />
            <feMerge>
              <feMergeNode in="blur" />
              <feMergeNode in="SourceGraphic" />
            </feMerge>
          </filter>
        </defs>

        <path
          d="M22 98 A78 78 0 0 1 178 98"
          fill="none"
          stroke="url(#stats-speed-arc)"
          strokeWidth="17"
          strokeLinecap="round"
          filter="url(#stats-speed-glow)"
        />
        <path
          d="M22 98 A78 78 0 0 1 178 98"
          fill="none"
          stroke="rgba(255,255,255,0.08)"
          strokeWidth="5"
          strokeLinecap="round"
        />

        {Array.from({ length: 13 }, (_, index) => {
          const tickAngle = (-120 + index * 20) * (Math.PI / 180);
          const outerRadius = 78;
          const innerRadius = index % 3 === 0 ? 52 : 60;
          const x1 = 100 + Math.cos(tickAngle) * outerRadius;
          const y1 = 98 + Math.sin(tickAngle) * outerRadius;
          const x2 = 100 + Math.cos(tickAngle) * innerRadius;
          const y2 = 98 + Math.sin(tickAngle) * innerRadius;
          return (
            <line
              key={index}
              x1={x1}
              y1={y1}
              x2={x2}
              y2={y2}
              stroke="rgba(255,255,255,0.7)"
              strokeWidth={index % 3 === 0 ? 2.5 : 1.5}
              strokeLinecap="round"
            />
          );
        })}

        <g
          style={{
            transformBox: "fill-box",
            transformOrigin: "100px 98px",
            transform: `rotate(${needleAngle}deg)`,
            transition: "transform 700ms cubic-bezier(0.22, 1, 0.36, 1)",
          }}
        >
          <line
            x1="100"
            y1="98"
            x2="160"
            y2="98"
            stroke="#ff4d6d"
            strokeWidth="6"
            strokeLinecap="round"
          />
          <line
            x1="100"
            y1="98"
            x2="73"
            y2="98"
            stroke="rgba(255,77,109,0.65)"
            strokeWidth="4"
            strokeLinecap="round"
          />
        </g>

        <circle cx="100" cy="98" r="10" fill="#ff4d6d" />
        <circle cx="100" cy="98" r="4" fill="#ffd4dc" />
      </svg>
    </div>
  );
}

function StatsRankingList({
  title,
  items,
  labelFormatter,
  onSelectVehicle,
}: {
  title: string;
  items: VehicleStatsOverview["topDistances"];
  labelFormatter: (value?: string | null) => string;
  onSelectVehicle: (vehicleId: string) => void;
}) {
  return (
    <div className="rounded-[0.8rem] border border-white/10 bg-black/10 px-3 py-3">
      <div className="text-[10px] font-semibold uppercase tracking-[0.24em] text-slate-400">{title}</div>
      <div className="mt-3 space-y-2">
        {items?.length ? items.map((item, index) => (
          <button
            key={`${title}-${item.vehicleId}-${index}`}
            type="button"
            onClick={() => onSelectVehicle(item.vehicleId)}
            className="flex w-full items-start justify-between rounded-[0.65rem] border border-white/6 bg-white/[0.03] px-2.5 py-2 text-left transition hover:border-mint/25 hover:bg-white/[0.05]"
          >
            <div className="min-w-0">
              <div className="truncate text-sm font-semibold text-white">{item.vehicleName}</div>
              <div className="text-[11px] leading-tight text-slate-400">{labelFormatter(item.recordedDay)}</div>
            </div>
            <div className="mb-2 ml-3 shrink-0 self-start text-sm font-bold leading-none text-mint">{formatStatsValue(item.value, "km")}</div>
          </button>
        )) : (
          <div className="text-sm text-slate-500">Brak danych</div>
        )}
      </div>
    </div>
  );
}

type StatsPanelProps = {
  isOpen: boolean;
  error: string | null;
  overview: VehicleStatsOverview | null;
  onClose: () => void;
  onSelectVehicle: (vehicleId: string) => void;
};

export function StatsPanel({ isOpen, error, overview, onClose, onSelectVehicle }: StatsPanelProps) {
  if (!isOpen) {
    return null;
  }

  return (
    <div className="pointer-events-none fixed inset-x-3 top-[5.5rem] bottom-3 z-[1700] md:left-auto md:right-[390px] md:top-4 md:bottom-4">
      <div className="neo-panel pointer-events-auto flex h-full w-full max-w-[430px] flex-col overflow-hidden rounded-[0.9rem] p-4 shadow-[0_0_0_1px_rgba(74,222,128,0.18),0_0_18px_rgba(74,222,128,0.1),0_20px_40px_rgba(2,8,23,0.42)]">
        <div className="flex items-start justify-between gap-3">
          <div>
            <div className="text-[11px] font-semibold uppercase tracking-[0.3em] text-mint">Stats</div>
            <div className="mt-1 text-[12px] text-slate-300">Rekordy floty i rankingi dnia, miesiąca oraz roku</div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/10 bg-white/5 text-slate-300 transition hover:text-white"
            aria-label="Zamknij statystyki"
            title="Zamknij statystyki"
          >
            <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        {error ? (
          <div className="mt-4 rounded-[0.7rem] border border-coral/40 bg-coral/10 px-3 py-2 text-sm text-coral">
            {error}
          </div>
        ) : null}

        <div className="mt-4 grid flex-1 gap-3 overflow-y-auto pr-1">
          <div className="rounded-[0.8rem] border border-mint/25 bg-white/[0.03] px-3 py-3">
            <div className="text-[10px] font-semibold uppercase tracking-[0.24em] text-slate-400">Wybrane auto</div>
            <div className="mt-2 flex items-start justify-between gap-3">
              <div className="min-w-0">
                <div className="text-lg font-semibold text-white">
                  {overview?.selectedVehicleStats?.vehicleName ?? "Brak"}
                </div>
                <div className="mt-1 text-xs text-slate-400">
                  Szacowany przebieg: {formatStatsValue(overview?.selectedVehicleStats?.estimatedCurrentOdometer, "km")}
                </div>
                <div className="mt-1 text-xs text-slate-400">
                  Najmocniejszy dzień: {overview?.selectedVehicleStats?.bestDay ? formatDayLabel(overview.selectedVehicleStats.bestDay) : "Brak dnia"}
                </div>
              </div>
              <div className="grid shrink-0 gap-2 text-right">
                <div>
                  <div className="text-[10px] uppercase tracking-[0.18em] text-slate-400">Miesiąc</div>
                  <div className="text-xl font-bold text-mint">{formatStatsValue(overview?.selectedVehicleStats?.currentMonthKm, "km")}</div>
                  <div className="text-[11px] text-slate-400">Pozycja: {overview?.selectedVehicleStats?.monthlyRank ?? "-"}</div>
                </div>
                <div>
                  <div className="text-[10px] uppercase tracking-[0.18em] text-slate-400">Rok</div>
                  <div className="text-xl font-bold text-mint">{formatStatsValue(overview?.selectedVehicleStats?.currentYearKm, "km")}</div>
                  <div className="text-[11px] text-slate-400">Pozycja: {overview?.selectedVehicleStats?.yearlyRank ?? "-"}</div>
                </div>
              </div>
            </div>
            <div className="mt-3">
              <div className="text-[11px] text-slate-400">Najlepszy dzień: <span className="font-semibold text-white">{formatStatsValue(overview?.selectedVehicleStats?.bestDayKm, "km")}</span></div>
            </div>
          </div>

          <div className="rounded-[0.8rem] border border-mint/25 bg-white/[0.03] px-3 py-3">
            <div className="text-[10px] font-semibold uppercase tracking-[0.24em] text-slate-400">Największy przebieg dnia</div>
            <div className="mt-2 flex items-end justify-between gap-3">
              <div>
                <div className="text-lg font-semibold text-white">
                  {overview?.topDistance?.vehicleName ?? "Brak"}
                </div>
                <div className="mt-1 text-xs text-slate-400">
                  {overview?.topDistance?.recordedDay ? formatDayLabel(overview.topDistance.recordedDay) : "Brak dnia"}
                </div>
              </div>
              <div className="text-right text-2xl font-bold text-mint">
                {formatStatsValue(overview?.topDistance?.value, "km")}
              </div>
            </div>
          </div>

          <div className="grid gap-3 lg:grid-cols-2">
            <div className="rounded-[0.8rem] border border-mint/25 bg-white/[0.03] px-3 py-3">
              <div className="text-[10px] font-semibold uppercase tracking-[0.24em] text-slate-400">Największy przebieg miesiąca</div>
              <div className="mt-2 flex items-end justify-between gap-3">
                <div>
                  <div className="text-lg font-semibold text-white">
                    {overview?.topMonthlyDistance?.vehicleName ?? "Brak"}
                  </div>
                  <div className="mt-1 text-xs text-slate-400">
                    {formatMonthLabel(overview?.topMonthlyDistance?.recordedDay)}
                  </div>
                </div>
                <div className="text-right text-2xl font-bold text-mint">
                  {formatStatsValue(overview?.topMonthlyDistance?.value, "km")}
                </div>
              </div>
            </div>

            <div className="rounded-[0.8rem] border border-mint/25 bg-white/[0.03] px-3 py-3">
              <div className="text-[10px] font-semibold uppercase tracking-[0.24em] text-slate-400">Największy przebieg roku</div>
              <div className="mt-2 flex items-end justify-between gap-3">
                <div>
                  <div className="text-lg font-semibold text-white">
                    {overview?.topYearlyDistance?.vehicleName ?? "Brak"}
                  </div>
                  <div className="mt-1 text-xs text-slate-400">
                    {formatYearLabel(overview?.topYearlyDistance?.recordedDay)}
                  </div>
                </div>
                <div className="text-right text-2xl font-bold text-mint">
                  {formatStatsValue(overview?.topYearlyDistance?.value, "km")}
                </div>
              </div>
            </div>
          </div>

          <div className="grid gap-3 lg:grid-cols-2">
            <StatsRankingList
              title="Top 5 przebiegów dnia"
              items={overview?.topDistances ?? []}
              labelFormatter={formatDayLabel}
              onSelectVehicle={onSelectVehicle}
            />
            <StatsRankingList
              title="Top 5 przebiegów miesiąca"
              items={overview?.topMonthlyDistances ?? []}
              labelFormatter={formatMonthLabel}
              onSelectVehicle={onSelectVehicle}
            />
          </div>

          <div className="grid gap-3 lg:grid-cols-2">
            <StatsRankingList
              title="Top 5 przebiegów roku"
              items={overview?.topYearlyDistances ?? []}
              labelFormatter={formatYearLabel}
              onSelectVehicle={onSelectVehicle}
            />
            <div className="rounded-[0.8rem] border border-white/10 bg-black/10 px-3 py-3">
              <div className="text-[10px] font-semibold uppercase tracking-[0.24em] text-slate-400">Obciążenie auta</div>
              <div className="mt-3 space-y-2 text-sm text-slate-300">
                <div>Miesiąc: <span className="font-semibold text-white">{overview?.selectedVehicleStats?.monthlyRank ? `#${overview.selectedVehicleStats.monthlyRank}` : "-"}</span></div>
                <div>Rok: <span className="font-semibold text-white">{overview?.selectedVehicleStats?.yearlyRank ? `#${overview.selectedVehicleStats.yearlyRank}` : "-"}</span></div>
                <div>To pozwala szybko ocenić, czy dane auto jest zajeżdżane częściej niż reszta floty.</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
