import React, { createContext, useContext, ReactNode } from 'react';
import {
  Breadcrumbs,
  BreadcrumbsList,
  BreadcrumbsListItem,
  BreadcrumbsProps,
} from '@digigov/ui/navigation/Breadcrumbs';
import {
  useBreadcrumbs,
  UseBreadcrumbsReturn,
  BreadcrumbItem,
} from '@digigov/ui/navigation/Breadcrumbs/hooks';

export interface BreadcrumbsListAutoProps extends BreadcrumbsProps {}
export interface BreadcrumbsAutoProps extends BreadcrumbsProps {
  items: BreadcrumbItem[];
  initialUrlRoute?: string;
  children: ReactNode;
}
export const BreadcrumbsContext = createContext<UseBreadcrumbsReturn | null>(
  null
);

export const BreadcrumbsAuto = ({
  items,
  initialUrlRoute,
  children,
}: BreadcrumbsAutoProps) => {
  const breadcrumbs = useBreadcrumbs(items, initialUrlRoute);

  return (
    <BreadcrumbsContext.Provider value={breadcrumbs}>
      {children}
    </BreadcrumbsContext.Provider>
  );
};

export const useBreadcrumbsContext = (): UseBreadcrumbsReturn => {
  const context = useContext(BreadcrumbsContext);
  if (!context) {
    throw new Error(
      'BreadcrumbsContext must be used within an BreadcrumbsProvider'
    );
  }
  return context;
};

export const BreadcrumbsListAuto = React.forwardRef<
  HTMLDivElement,
  BreadcrumbsListAutoProps
>(function BreadcrumbsListAuto(props, ref) {
  const { breadcrumbs, setActiveItem } = useBreadcrumbsContext();
  return (
    <Breadcrumbs ref={ref} {...props}>
      <BreadcrumbsList>
        {breadcrumbs.map((breadcrumb, index) => (
          <BreadcrumbsListItem
            key={index}
            href={breadcrumbs.length - 1 === index ? '' : breadcrumb.href}
            onClick={() => setActiveItem(breadcrumb)}
            ariaCurrent={breadcrumbs.length - 1 === index ? 'page' : undefined}
          >
            {breadcrumb.title}
          </BreadcrumbsListItem>
        ))}
      </BreadcrumbsList>
    </Breadcrumbs>
  );
});
