"use client";

import { FC, useEffect, useState } from "react";
import Link from "@/components/common/versioned-link";
import { Check, Compass, Flame, Home, Images, Plus, User } from "lucide-react";
import { usePathname } from "next/navigation";
import Sticky from "./sticky.component";
import { cn } from "@/lib/utils";
import { ApiEndpoint } from "@/lib/services/api.service";
import { useApi } from "@/lib/services/axios.service";
import { StreakResponseDto } from "@/lib/dto/practice.dto";
import { PRACTICE_LOGGED_EVENT } from "@/components/practice/practice-sheet.component";
import { faNumber } from "@/lib/helpers/format.helper";

const SIDE_ITEMS = {
  start: [
    { href: "/home", label: "خانه", icon: Home },
    { href: "/explore", label: "کاوش", icon: Compass },
  ],
  end: [
    { href: "/gallery", label: "گالری", icon: Images },
    { href: "/profile", label: "پروفایل", icon: User },
  ],
};

const normalize = (path: string) => path.replace(/\/$/, "");

// The last state seen, so a page change doesn't flash the button back to "not done" while it reloads.
const lastKnown = { practised: false, streak: 0 };

const Menu: FC = () => {
  const pathname = normalize(usePathname());
  const [practised, setPractised] = useState(lastKnown.practised);
  const [streak, setStreak] = useState(lastKnown.streak);
  const [, fetchStreak] = useApi<StreakResponseDto>({ url: ApiEndpoint("practice", "streak"), method: "GET", useCache: true, cacheTTL: 30000 });

  useEffect(() => {
    fetchStreak().then(
      (response) => {
        lastKnown.practised = !!response?.body?.data?.practised_today;
        lastKnown.streak = response?.body?.data?.current ?? 0;
        setPractised(lastKnown.practised);
        setStreak(lastKnown.streak);
      },
      () => { /* no answer: keep the last known state */ },
    );
  }, [fetchStreak, pathname]);

  useEffect(() => {
    const done = () => {
      lastKnown.practised = true;
      lastKnown.streak = Math.max(1, lastKnown.streak);
      setPractised(true);
      setStreak(lastKnown.streak);
    };
    window.addEventListener(PRACTICE_LOGGED_EVENT, done);
    return () => window.removeEventListener(PRACTICE_LOGGED_EVENT, done);
  }, []);

  const tab = (item: { href: string; label: string; icon: typeof Home }) => {
    const Icon = item.icon;
    const active = pathname === item.href || pathname.startsWith(`${item.href}/`);

    return (
      <Link
        key={item.href}
        href={item.href}
        aria-current={active ? "page" : undefined}
        className={cn(
          "flex flex-col items-center flex-1 min-h-12 justify-center text-micro",
          active ? "text-sienna font-bold" : "text-ink-soft font-semibold"
        )}
      >
        <span className={cn("px-3.5 py-1 rounded-full transition-colors", active && "bg-sienna-soft")}>
          <Icon className="h-[21px] w-[21px]" strokeWidth={active ? 2.1 : 1.7} />
        </span>
        <span className="mt-0.5">{item.label}</span>
      </Link>
    );
  };

  const practiceActive = pathname === "/practice";

  return (
    <Sticky>
      <nav
        aria-label="منوی اصلی"
        className="w-full bg-canvas border-t border-line flex items-end shrink-0 pt-1.5 pb-[max(6px,env(safe-area-inset-bottom))]"
      >
        {SIDE_ITEMS.start.map(tab)}

        <Link
          href={practised || practiceActive ? "/practice" : "/practice?log=1"}
          aria-current={practiceActive ? "page" : undefined}
          aria-label={practised ? `تمرین امروز ثبت شد، ${faNumber(streak)} روز پیاپی` : "ثبت تمرین امروز"}
          className="group relative flex flex-col items-center flex-1 text-micro"
        >
          <span className="relative -mt-[19px]">
            <span
              aria-hidden="true"
              className="absolute -inset-2 rounded-full bg-canvas border border-line"
              style={{ clipPath: "inset(-8px -8px 47% -8px)" }}
            />
            <span
              className={cn(
                "relative w-12 h-12 rounded-full grid place-items-center text-canvas shadow-raised transition-transform group-active:scale-95",
                practised ? "bg-gradient-to-br from-sage to-sage-ink" : "bg-gradient-to-br from-sienna to-ochre"
              )}
            >
              {practised ? (
                <Check className="w-6 h-6" strokeWidth={2.6} />
              ) : (
                <Plus className="w-6 h-6" strokeWidth={2.6} />
              )}
            </span>

            {streak > 0 && (
              <span className="absolute -top-1 -right-2 h-[18px] min-w-[18px] px-1 rounded-full bg-canvas text-sienna-dark text-micro font-extrabold flex items-center gap-0.5 shadow-card ring-1 ring-line tabular-nums leading-none">
                <Flame className="w-2.5 h-2.5 text-sienna" aria-hidden="true" />
                {faNumber(streak)}
              </span>
            )}
          </span>

          <span className={cn("mt-1", practised ? "text-sage-ink font-bold" : "text-sienna font-extrabold")}>
            {practised ? "انجام شد" : "تمرین"}
          </span>
        </Link>

        {SIDE_ITEMS.end.map(tab)}
      </nav>
    </Sticky>
  );
};

export default Menu;
