import { useEffect, useMemo, useState } from 'react';
import { type FieldValues, type UseFormReturn } from 'react-hook-form';
import { useQuery } from 'react-query';

import { type AxiosResponse } from 'axios';

import { useAuth } from 'src/contexts/JWTContext';
import useFormatDate from 'src/hooks/useFormatDate';
import { profileKeys } from 'src/pages/dashboard/profile/queries';
import {
  dynamicFieldsResponse,
  getPeopleList,
  getProfileById,
} from 'src/services/users';
import { type Question, type Step } from 'src/types/forms';
import { type User } from 'src/types/user';
import { getQuestionName } from 'src/utils/form';
import { getFullName } from 'src/utils/userUtils';

import { ID_NUMBER, SPECIAL_FORM_V2 } from './constants';
import { EdemsaSpecialFields } from './types';
import { isEdemsaSpecialForm, iterateQuestions } from './utils';

type Props = {
  formTitle: string;
  currentStepIdx: number;
  step: Step;
  form: UseFormReturn<FieldValues>;
};

const useEdemsaVLookupForm = ({
  formTitle,
  currentStepIdx,
  step,
  form,
}: Props) => {
  const [employeeId, setEmployeeId] = useState('');
  const [shouldFetch, setShouldFetch] = useState(false);
  const { instance } = useAuth();
  const { formatDate } = useFormatDate();

  const isSpecialForm = isEdemsaSpecialForm(instance!.id, formTitle);

  const { data: peopleListData, isLoading: isLoadingPeopleList } = useQuery(
    ['employeeProfile', employeeId],
    () => getPeopleList(employeeId, 1),
    {
      select: response => response.data,
      enabled: shouldFetch && !!employeeId && isSpecialForm,
    },
  );

  const userId = peopleListData?.items?.[0]?.id || null;
  const noUserFound = peopleListData !== undefined && !peopleListData?.count;

  const { data: userData, isLoading: isLoadingUserData } = useQuery(
    ['userProfile', userId],
    () => getProfileById(userId!),
    {
      enabled: !!userId && isSpecialForm,
    },
  );

  const { data: profileFields, isLoading: isLoadingProfileFields } = useQuery(
    profileKeys.profileFields(instance!.id),
    () => dynamicFieldsResponse(instance!.id),
    {
      select: response => {
        return [
          ...Object.entries(response.data).map(([key, v]) => ({
            id: key,
            name: v.name,
          })),
        ];
      },
      enabled: isSpecialForm,
    },
  );

  useEffect(() => {
    iterateQuestions(step, (config: Question, index: number) => {
      if (config.description === ID_NUMBER) {
        const fieldName = `${currentStepIdx}-${index}-${getQuestionName(config)}-${step.id}`;
        const idNumberValue = form.watch(fieldName);
        if (idNumberValue) {
          setEmployeeId(idNumberValue);
          setShouldFetch(true);
        }
      }
      return 0;
    });
  }, [currentStepIdx]);

  const getUserProfileData = (
    data: { id: string; name: string }[] | undefined,
    userInfo: AxiosResponse<User, any> | undefined,
  ) => {
    if (!data) return null;

    return data.map((elem: { id: string; name: string }) => ({
      id: elem.id,
      name: elem.name,
      value: userInfo?.data?.profileData?.[elem.id as any] || null,
    }));
  };

  const profileData = useMemo(
    () => getUserProfileData(profileFields, userData),
    [profileFields, userData],
  );

  const getProfileDataValue = (
    data: { id: string; name: string; value: unknown }[],
    name: string,
  ) => {
    const profileDataResult = data?.find(elem => elem.name === name);
    return profileDataResult ? (profileDataResult.value as string) : null;
  };

  const userProfileDataObj = useMemo(() => {
    if (!profileData || !isSpecialForm || !userData) return [];
    return [
      {
        name: EdemsaSpecialFields.MANAGEMENT,
        value: getProfileDataValue(profileData, EdemsaSpecialFields.MANAGEMENT),
        allowed: true,
      },
      {
        name: EdemsaSpecialFields.SUB_MANAGEMENT,
        value: getProfileDataValue(
          profileData,
          EdemsaSpecialFields.SUB_MANAGEMENT,
        ),
        allowed: true,
      },
      {
        name: EdemsaSpecialFields.ORGANIZATIONAL_UNIT,
        value: getProfileDataValue(
          profileData,
          EdemsaSpecialFields.ORGANIZATIONAL_UNIT,
        ),
        allowed: true,
      },
      {
        name: EdemsaSpecialFields.POSITION,
        value: getProfileDataValue(profileData, EdemsaSpecialFields.POSITION),
        allowed: true,
      },
      {
        name: EdemsaSpecialFields.FUNCTIONAL_LEVEL,
        value: getProfileDataValue(
          profileData,
          EdemsaSpecialFields.FUNCTIONAL_LEVEL,
        ),
        allowed: formTitle !== SPECIAL_FORM_V2, // Only for ROTACIÓN DE PERSONAL
      },
      {
        name: EdemsaSpecialFields.WORKPLACE,
        value: getProfileDataValue(profileData, EdemsaSpecialFields.WORKPLACE),
        allowed: true,
      },
      {
        name: EdemsaSpecialFields.AGREEMENT,
        value: getProfileDataValue(profileData, EdemsaSpecialFields.AGREEMENT),
        allowed: true,
      },
      {
        name: EdemsaSpecialFields.COST_CENTER,
        value: getProfileDataValue(
          profileData,
          EdemsaSpecialFields.COST_CENTER,
        )?.toString(),
        allowed: true,
      },
      {
        name: EdemsaSpecialFields.FULL_NAME,
        value: getFullName(userData?.data),
        allowed: true,
      },
      {
        name: EdemsaSpecialFields.ISSUE_DATE,
        value: formatDate(new Date()),
        allowed: true,
      },
    ];
  }, [profileData, formTitle, userData, formatDate]);

  const handleSearchEmployeeData = (name: string) => {
    const newValue = form.watch(name);
    setEmployeeId(newValue);
    setShouldFetch(true);
  };

  const isLoading =
    isLoadingPeopleList || isLoadingUserData || isLoadingProfileFields;

  return {
    userProfileDataObj,
    noUserFound,
    isLoading,
    isSpecialForm,
    handleSearchEmployeeData,
    setEmployeeId,
  };
};

export default useEdemsaVLookupForm;
