import React from 'react'

import { cn } from "@/lib/utils"
import Link from 'next/link';

export interface BreadcrumbProps {
    className?: string,
    path: string
}

const Breadcrumb = async ({ className, path } : BreadcrumbProps) => {

    const progressivePath = await Promise.all(path.split('/').slice(1).map((_, index, array) => {
        const uri = `/${array.slice(0, index + 1).join('/')}`
        return fetch(uri).then(res => res.ok)
}))
    
    const CapitalPath = path.split('/').slice(1).map(currentPath => currentPath.charAt(0).toUpperCase() + currentPath.slice(1))

    console.log(progressivePath)
    console.log(CapitalPath)

    return (
        <div className={cn("flex items-center space-x-2 text-md bg-slate-300 w-fit px-2 py-1 rounded-md", className)}>
            {CapitalPath.map((path, index) => (
                    <>
                    {
                        progressivePath[index] === '#' ? 
                        <BreadcrumbItem key={index}>
                            <BreadCrumbLink className="text-md" href='#'>{path}</BreadCrumbLink>
                        </BreadcrumbItem>
                        :
                        <BreadcrumbItem key={index}>
                            <BreadCrumbLink className="text-md underline underline-offset-1" href='#'>{path}</BreadCrumbLink>
                        </BreadcrumbItem>
                    }
                    {
                        index < CapitalPath.length - 1 ? 
                        <BreadCrumbSeparator key={index}>
                            {">"}
                        </BreadCrumbSeparator> : null
                    }
                    </>
            ))}
        </div>
    )
}

const BreadcrumbItem = React.forwardRef<
    HTMLDivElement, 
    React.HTMLAttributes<HTMLDivElement>>
(({ className, ...props}, ref) => (
    <div
    ref={ref}
    className={cn("flex items-center space-x-2 text-md", className)}
    {...props}
    />
))
BreadcrumbItem.displayName = "BreadcrumbItem"
 
const BreadCrumbLink = React.forwardRef<
    React.ElementRef<typeof Link>,
    React.ComponentPropsWithoutRef<typeof Link>
>(({ className, href, ...props }, ref) => (
    <Link
    ref={ref}
    href={href}
    className={cn("text-md", className)}
    {...props}
    />
))
BreadCrumbLink.displayName = "BreadCrumbLink"

const BreadCrumbSeparator = React.forwardRef<
    HTMLDivElement,
    React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
    <div
    ref={ref}
    className={cn("text-md text-muted-foreground", className)}
    {...props}
    />
))
BreadCrumbSeparator.displayName = "BreadCrumbSeparator"


export default Breadcrumb