'use client';

import { useEffect, useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";

interface NavLink {
    href: string;
    title: string;
    subLinks?: {
        href: string;
        title: string;
    }[];
}

interface DataNavProps extends React.HTMLAttributes<HTMLElement> {
    links: NavLink[];
}

export function DataNav({ className, links, ...props }: DataNavProps) {
    const router = useRouter();
    const pathname = usePathname();
    const [expandedGroup, setExpandedGroup] = useState<string | null>(null);

    const isPathMatch = (currentPath: string, href: string) => {
        if (!currentPath || !href) return false;
        return currentPath === href || currentPath.startsWith(`${href}/`);
    };

    useEffect(() => {
        // Find which group should be expanded based on current pathname
        let groupFound = false;
        const activePath = pathname || '';
        for (const link of links) {
            if (link.subLinks) {
                const isInGroup =
                    activePath === link.href
                    || link.subLinks.some((sub) => {
                        // A sub-link equal to the group root should only match exact route,
                        // otherwise sibling routes (e.g. /admin/sales/debit-notes) are incorrectly captured.
                        if (sub.href === link.href) {
                            return activePath === sub.href;
                        }
                        return isPathMatch(activePath, sub.href);
                    });
                if (isInGroup) {
                    setExpandedGroup(link.href);
                    groupFound = true;
                }
            }
        }
        if (!groupFound) {
            setExpandedGroup(null);
        }
    }, [pathname, links]);

    const activePath = pathname || '';
    
    // Find active value: prefer exact match, otherwise use group href
    const activeValue = links.find(link => activePath === link.href)?.href 
        || links.find(link => link.subLinks?.some(sub => activePath === sub.href))?.href
        || links[0]?.href 
        || '';

    const handleTabChange = (href: string) => {
        const link = links.find(l => l.href === href);
        if (link?.subLinks && link.subLinks.length > 0) {
            // If group has subLinks, navigate to first subLink
            setExpandedGroup(href);
            router.push(link.subLinks[0].href);
        } else {
            // Regular navigation
            setExpandedGroup(null);
            router.push(href);
        }
    };

    const activeSubValue = (() => {
        if (!expandedGroup) return activePath;
        const group = links.find((link) => link.href === expandedGroup);
        const subLinks = group?.subLinks || [];
        if (subLinks.some((sub) => sub.href === activePath)) return activePath;
        return subLinks[0]?.href || activePath;
    })();

    return (
        <div className={cn("w-full flex flex-col", className)} {...props}>
            <Tabs value={activeValue} onValueChange={handleTabChange} className="w-full">
            <div className="w-full overflow-hidden">
            <TabsList className="flex w-full flex-wrap justify-start h-auto bg-muted/40 p-1 gap-1">
                {links.map((link) => (
                        <TabsTrigger key={link.href} value={link.href} className="text-xs sm:text-sm h-auto whitespace-normal leading-tight">
                        {link.title}
                    </TabsTrigger>
                ))}
            </TabsList>
            </div>
            </Tabs>

            {/* Nested tabs for groups with subLinks */}
            {expandedGroup && links.find(l => l.href === expandedGroup)?.subLinks && (
                <Tabs 
                    value={activeSubValue} 
                    onValueChange={(href) => router.push(href)}
                    className="w-full mt-2"
                >
                    <div className="w-full overflow-hidden">
                    <TabsList className="flex w-full flex-wrap justify-start h-auto bg-muted p-1 gap-1">
                        {links.find(l => l.href === expandedGroup)?.subLinks?.map((subLink) => (
                            <TabsTrigger key={subLink.href} value={subLink.href} className="text-xs sm:text-sm h-auto whitespace-normal leading-tight">
                                {subLink.title}
                            </TabsTrigger>
                        ))}
                    </TabsList>
                    </div>
                </Tabs>
            )}
        </div>
    );
}
