import {
  type Action,
  type IResourceItem,
  useParsed,
  useTranslate,
  generateDefaultDocumentTitle,
  useUserFriendlyName,
} from "@refinedev/core";
import React, { useLayoutEffect } from "react";
import { useLocation } from "react-router";

type Props = {
  handler?: (options: {
    resource?: IResourceItem;
    action?: Action;
    params?: Record<string, string | undefined>;
    pathname?: string;
    autoGeneratedTitle: string;
  }) => string;
};

export function DocumentTitleHandler({ handler }: Props) {
  const location = useLocation();
  const { action, id, params, pathname, resource } = useParsed();
  const translate = useTranslate();
  const getUserFriendlyName = useUserFriendlyName();

  const identifier = resource?.identifier ?? resource?.name;
  const preferredLabel = resource?.meta?.label;
  const resourceName =
    preferredLabel ??
    getUserFriendlyName(identifier, action === "list" ? "plural" : "singular");
  const populatedLabel = translate(
    `${resource?.name}.${resource?.name}`,
    resourceName,
  );

  useLayoutEffect(() => {
    const autoGeneratedTitle = generateDefaultDocumentTitle(
      translate,
      resource!,
      action,
      `${id}`,
      resourceName,
      getUserFriendlyName,
    );
    if (handler) {
      document.title = handler({
        action,
        resource: {
          ...(resource! ?? {}),
          meta: {
            ...resource?.meta,
            label: populatedLabel,
          },
        },
        params,
        pathname,
        autoGeneratedTitle,
      });
    } else {
      document.title = autoGeneratedTitle;
    }
  }, [location]);

  return <></>;
}
