import { useEffect, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { useLocation, useParams } from "react-router-dom";

import LetterViewer from "../common/letterViewer";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { fetchRecordContentByRecordId } from "@/record-management/services/api/userRecordService";
import { DelegatePositionDto } from "@/record-management/dto/delegation/delegationDto";
import { useLocalizedName } from "@/shared/common/localizedName";
import { CommentCard } from "@/record-management/common/WorkflowCommentHistory";

const DelegationLetterView = () => {
  const { id } = useParams<{ id: string }>();
  const location = useLocation();
  const { t } = useTranslation();
  const localizeName = useLocalizedName();

  const { handleError } = useErrorHandler(t);
  const routeState = location.state as {
    delegation?: DelegatePositionDto;
    delegationType?: "delegator" | "delegatee";
  } | null;

  const delegation = routeState?.delegation;
  const terminationReason = delegation?.terminationReason ?? null;

  const { data, error } = useQuery({
    queryKey: ["delegation-latest-outgoing-history", id],
    queryFn: () => fetchRecordContentByRecordId(id!),
    enabled: Boolean(id),

    staleTime: 0,
    refetchOnMount: true,
    refetchOnWindowFocus: true,
    refetchOnReconnect: true,
  });

  const previousErrorRef = useRef<unknown>(null);
  useEffect(() => {
    if (error && error !== previousErrorRef.current) {
      previousErrorRef.current = error;
      handleError(error);
    }
  }, [error, handleError]);

  const latestOutgoingHistory = data?.outgoingHistories?.[0];
  const delegationActionRowData = delegation
    ? {
        ...delegation,
        delegationType: routeState?.delegationType,
        comment: latestOutgoingHistory?.comment,
        createdAt: latestOutgoingHistory?.createdAt,
        employeePosition: latestOutgoingHistory?.employeePosition,
        assigner:
          localizeName(
            latestOutgoingHistory?.employeePosition?.employee?.name as
              | { en: string; am: string }
              | undefined,
          ) || "",
      }
    : undefined;

  const terminatedEmployeeName =
    (delegation?.terminationReason?.terminatorEmployeePosition?.employee
      ?.name &&
      (localizeName(
        delegation.terminationReason.terminatorEmployeePosition.employee.name,
      ) ||
        delegation.terminationReason.terminatorEmployeePosition.employee.name
          .en ||
        delegation.terminationReason.terminatorEmployeePosition.employee.name
          .am)) ||
    t("common.unknownUser", "Unknown user");

  const terminationBanner = terminationReason ? (
    <div className="max-w-8xl mx-none px-6 pt-6">
      <h3 className="text-sm font-semibold text-gray-900 dark:text-white mb-2">
        {t("delegation.terminationDetail", "Termination Detail")}
      </h3>
      <CommentCard
        createdAt={terminationReason.terminatedAt}
        comment={terminationReason.comment}
        assignerName={terminatedEmployeeName}
        variant="secondary"
      />
    </div>
  ) : null;

  return (
    <>
      {terminationBanner}
      <LetterViewer
        backurl="/record-management/delegation"
        type="delegation"
        shouldFetchInstance={false}
        actions="DelegationRecordActions"
        actionRowData={delegationActionRowData}
      />
    </>
  );
};

export default DelegationLetterView;
