'use client';

import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useRouter } from 'next/navigation';
import {
    LayoutGrid,
    ShoppingBag,
    LogOut
} from 'lucide-react';
import {
    DEFAULT_LOCALE,
    getStoredLocale,
    LOCALE_CHANGE_EVENT,
    type LocaleCode,
} from "@/i18n/localeSwitcher";
import staticCopy from "@/i18n/staticCopy.json";

const MAIN_NAV = [
    { icon: LayoutGrid, path: '/dashboard', labelKey: 'dashboard' },
    { icon: ShoppingBag, path: '/orders', labelKey: 'orders' },
];

export default function Sidebar() {
    const pathname = usePathname();
    const router = useRouter();
    const [profile, setProfile] = useState<Record<string, any> | null>(null);
    const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);

    useEffect(() => {
        const syncLocale = () => {
            setUiLocale(getStoredLocale());
        };

        syncLocale();
        window.addEventListener("storage", syncLocale);
        window.addEventListener(LOCALE_CHANGE_EVENT, syncLocale);
        return () => {
            window.removeEventListener("storage", syncLocale);
            window.removeEventListener(LOCALE_CHANGE_EVENT, syncLocale);
        };
    }, [pathname]);

    const mainNav = useMemo(
        () =>
            MAIN_NAV.map((item) => ({
                ...item,
                label: staticCopy.sidebar[uiLocale][item.labelKey as "dashboard" | "orders"],
            })),
        [uiLocale]
    );

    useEffect(() => {
        let active = true;

        const loadProfile = async () => {
            try {
                const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
                if (!base) return;

                const headers: Record<string, string> = {
                    "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
                };

                const raw = typeof window !== "undefined" ? localStorage.getItem("currentUser") : null;
                const user = raw ? JSON.parse(raw) : null;
                const token = String(user?.token ?? user?.access_token ?? "").trim();
                if (token) headers.Authorization = `Bearer ${token}`;

                const res = await fetch(`${base}/store/customers/profile`, {
                    method: "GET",
                    headers,
                    credentials: "include",
                    cache: "no-store",
                });
                if (!res.ok || !active) return;

                const data = await res.json().catch(() => null);
                if (!active || !data) return;
                setProfile(data);
            } catch {
            }
        };

        void loadProfile();
        return () => {
            active = false;
        };
    }, []);

    const profileAvatarSrc = useMemo(() => {
        const directAvatar =
            String(
                profile?.avatar_url ??
                profile?.avatar ??
                profile?.profile_image ??
                profile?.image_url ??
                ""
            ).trim();
        if (directAvatar) return directAvatar;

        const name = String(
            `${profile?.first_name || ""} ${profile?.last_name || ""}`.trim() ||
            profile?.company_business_name ||
            "User"
        ).trim();
        return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=053F31&color=ffffff&size=256`;
    }, [profile]);

    const handleLogout = () => {
        localStorage.removeItem("currentUser");
        router.push("/login");
    };

    const NavItem = ({ item, isBottom = false }: { item: any, isBottom?: boolean }) => {
        const isActive = pathname === item.path || pathname?.startsWith(item.path);

        return (
            <Link
                href={item.path}
                className="relative group flex items-center justify-center w-full"
                title={item.label}
            >
                <div
                    className={`
                    w-[50px] h-[50px] rounded-full flex items-center justify-center transition-all duration-300
                        ${isActive
                            ? 'bg-[#053F31] text-white shadow-lg shadow-[#053F31]/30 ' 
                            : 'text-[#053F31] hover:bg-[#DAE6DC]/50' 
                        }
          `}
                >
                    <item.icon
                        size={16}
                        strokeWidth={isActive ? 2.5 : 2}
                        className="transition-transform duration-300"
                    />
                </div>

                <span className="absolute left-[70px] bg-[#053F31] text-white text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 pointer-events-none">
                    {item.label}
                </span>
            </Link>
        );
    };

    return (
        <>
            <aside className="hidden md:flex flex-col w-[60px] bg-[#F7FAF8] rounded-full shadow-xl border border-[#053F31]/5 gap-7 py-4 justify-between">
                <div className="flex flex-col gap-2 w-full items-center">
                    {mainNav.map((item) => (
                        <NavItem key={item.path} item={item} />
                    ))}
                </div>

                <div className="flex flex-col gap-2 w-full items-center mt-auto">
                    <button
                        onClick={handleLogout}
                        className="w-[50px] h-[50px] flex items-center justify-center text-[#053F31] hover:bg-red-50 hover:text-red-600 rounded-full transition-all"
                        title={staticCopy.sidebar[uiLocale].logout}
                        aria-label={staticCopy.sidebar[uiLocale].logout}
                    >
                        <LogOut size={16} strokeWidth={2} />
                    </button>
                    <Link
                        href="/profile"
                        className="mt-2 relative group cursor-pointer"
                        title={staticCopy.sidebar[uiLocale].profile}
                        aria-label={staticCopy.sidebar[uiLocale].profile}
                    >
                        <div className="w-[50px] h-[50px] rounded-full p-[2px] border-2 border-[#053F31]/20 group-hover:border-[#053F31] transition-colors overflow-hidden">
                            <img
                                src={profileAvatarSrc}
                                alt="User"
                                className="w-full h-full object-cover rounded-full"
                            />
                        </div>

                        <div className="absolute bottom-0 right-0 w-3.5 h-3.5 bg-green-500 border-2 border-white rounded-full"></div>
                    </Link>

                </div>
            </aside>

            <nav className="flex md:hidden fixed bottom-6 left-1/2 -translate-x-1/2 z-50 bg-white rounded-full shadow-2xl border border-gray-100 p-1 items-center gap-1">
                {mainNav.map((item) => {
                    const isActive = pathname === item.path || pathname?.startsWith(item.path);
                    return (
                        <Link
                            key={item.path}
                            href={item.path}
                            className={`
                                flex items-center gap-2 px-6 py-3 rounded-full transition-all duration-300
                                ${isActive
                                    ? 'bg-[#053F31] text-white shadow-md'
                                    : 'text-gray-500 hover:bg-gray-50'
                                }
                            `}
                        >
                            <item.icon size={20} strokeWidth={isActive ? 2.5 : 2} />
                            <span className={`text-sm font-medium ${isActive ? 'block' : 'hidden'}`}>
                                {item.label}
                            </span>
                        </Link>
                    );
                })}
            </nav>
        </>
    );
}