import {
  getCCIncoming,
  getCCIncomingParent,
  PaginationParams,
} from "@/record-management/services/api/incomingRecordService";
import { MeDto } from "@/shared/dto/user/meDto";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { useUserDetail } from "./useUserDetail";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

// Define the DTO for CC records
export interface MetadataLang {
  am: string;
  en: string;
}

export interface Metadata {
  deliveredBy: MetadataLang;
  organizationName: MetadataLang;
}

export interface ContentItem {
  id: string;
  subject: string;
}

export interface Initiator {
  id: string;
  employee: {
    id: string;
    name: {
      am: string;
      en: string;
    };
  };
  position: {
    createdAt: string;
    updatedAt: string;
    id: string;
    name: {
      am: string;
      en: string;
    };
    key: string;
    rank: 1;
    parentPositionId: string;
    unitId: string;
    organizationId: string;
    projectId: null;
    positionTypeId: string;
  };
  unit: {
    id: string;
    name: {
      am: string;
      en: string;
    };
    organization: {
      id: string;
      name: {
        am: string;
        en: string;
      };
    };
  };
}

export interface Record {
  isUrgent: any;
  amharicDispatchedDate: string;
  letterName: string;
  referenceNumber: string;
  id: string;
  letterNumber: string;
  metadata: Metadata;
  dispatchedDate: string; // or Date if you parse it
  initiationType: string;
  recordTypeKey: string;
  content: ContentItem[];
  initiator: Initiator | null;
}

export interface AssigneePositionName {
  am: string;
  en: string;
}

export interface AssigneePosition {
  id: string;
  name: AssigneePositionName;
}

export interface CCIncomingRecordDto {
  hasSeen: string;
  createdAt: string; // or Date if parsed
  id?: string;
  status?: string;
  latestRemarkAt?: string | null;
  childAssignments?: {
    latestRemarkAt?: string | null;
  }[];
  isRead?: boolean;
  comment?: string | null;
  record: Record;
  assigneePosition?: AssigneePosition;
  amharicCreatedAt: string;
  amharicDispatchedDate: string;
  pageNo?: number;
  isLocked?: boolean;
  isDelegation?: boolean;
  // Other optional fields as needed
}

export interface MemoDto {
  id: string;
  createdAt: string;
  referenceNumber: string | null;
  dispatchedDate: string | null;
  amharicDispatchedDate: string | null;
  amharicCreatedAt: string;
  initiationType: string;
  recordTypeKey: string;
  content: MemoContentDto[];
  initiator: InitiatorDto;
  initiatedAs?: string;
  pageNo?: number;
  status: string;
  isLocked?: boolean;
  isDelegation?: boolean;
}

export interface MemoContentDto {
  id: string;
  subject: string;
  ccs: CCDto[];
}

export interface CCDto {
  id?: string;
  hasSeen?: boolean;
  status?: string;
  seenAt?: string | null;
  seenByEmployeePosition?: unknown | null;
  positionId?: string;
  unitId?: string;
  type?: "internal" | "external";
  isForYourReference?: boolean;
  value?: string;
  label?: string;
  employeePositionId?: string | null;
}

export interface InitiatorDto {
  id: string;
  employee: EmployeeDto;
  position: PositionDto;
}

export interface EmployeeDto {
  id: string;
  name: NameDto;
}

export interface NameDto {
  am: string;
  en: string;
}

export interface PositionDto {
  id: string;
  createdAt: string;
  updatedAt: string;
  name: NameDto;
  key: string;
  rank: number;
  parentPositionId: string | null;
  unitId: string;
  organizationId: string;
  projectId: string | null;
  positionTypeId: string;
}

export const useCCIncomingRecords = (params?: PaginationParams) => {
  const { userDetails } = useAuthUser();
  const { permissionKeys } = useUserDetail(userDetails as MeDto);
  const RO = permissionKeys.includes("can:dispatchRecords");
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  // Use React Query for data fetching with caching

  const {
    data, // Default to mock data for now
    isLoading,
    isError,
    error: ccError,
    refetch,
  } = useQuery({
    queryKey: ["incoming-cc", params],
    staleTime: 1000 * 60 * 5, // Cache data for 5 minutes
    queryFn: () => getCCIncoming(params),
    enabled: Boolean(!RO),
  });
  const {
    data: dataParent,
    isLoading: isLoadingParent,
    isError: isErrorParent,
    error: ccParentError,
    refetch: refetchParent,
  } = useQuery({
    queryKey: ["incoming-cc-parent", params],
    staleTime: 1000 * 60 * 5, // Cache data for 5 minutes
    queryFn: () => getCCIncomingParent(params),
    enabled: Boolean(params?.fetchParent),
  });

  // Surface list-fetch failures via the centralized error handler.
  const listFetchError = ccError || ccParentError;
  const prevListErrorRef = useRef<unknown>(null);
  useEffect(() => {
    if (listFetchError && listFetchError !== prevListErrorRef.current) {
      prevListErrorRef.current = listFetchError;
      handleError(listFetchError);
    }
  }, [listFetchError, handleError]);

  const ccRecords = data?.items ?? [];
  const ccCount = data?.count ?? 0;

  return {
    ccCount,
    ccRecords,
    fetchAttachments: data,
    isLoading,
    isError,
    refetch,
    ...(params?.fetchParent
      ? {
          ccParent: dataParent?.items ?? [],
          ccParentCount: dataParent?.count ?? 0,
          refetchParent,
          isErrorParent,
          isLoadingParent,
        }
      : {}),
  };
};
