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

import Head from "next/head";

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

export const DocumentTitleHandler = ({ handler }: Props) => {
  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,
  );

  const autoGeneratedTitle = generateDefaultDocumentTitle(
    translate,
    resource,
    action,
    `${id}`,
    resourceName,
  );

  return (
    <Head>
      <title>
        {handler?.({
          resource: {
            ...(resource! ?? {}),
            meta: {
              ...resource?.meta,
              label: populatedLabel,
            },
          },
          params,
          action,
          autoGeneratedTitle,
          pathname,
        }) ?? autoGeneratedTitle}
      </title>
    </Head>
  );
};
