import { useMutation } from '@tanstack/react-query';

import { toast } from '@/components/toast/Toast';
import { useApiClient } from '@/lib/apiClient';
import { CreatorLabel } from '@/utils/constants';

export function useCreatorLabel({
  setCurrentCreatorLabel,
}: {
  setCurrentCreatorLabel: (label: CreatorLabel | undefined) => void;
}) {
  const apiClient = useApiClient();

  const setCreatorLabelMutation = useMutation({
    mutationFn: async ({
      creator_user_uuid,
      label,
    }: {
      creator_user_uuid: string;
      label: CreatorLabel;
    }) => {
      const response = await apiClient.POST('/api/video/hooks/creator_label', {
        body: { creator_user_uuid, label },
      });

      const { data, error } = response;
      if (error || !data) {
        throw new Error(
          `Failed to set creator label: ${error || 'No data returned'}`
        );
      }
      return data;
    },
    onSuccess: (_response, { label }) => {
      setCurrentCreatorLabel(label);
      const labelName =
        label === CreatorLabel.CHAMPION ? 'Champion' : 'Ambassador';
      toast({
        title: `${labelName} Label Added`,
        description: `This creator has been successfully labeled as a ${labelName}.`,
        status: 'success',
        position: 'bottom',
        duration: 5000,
        isClosable: true,
      });
    },
    onError: (_err, { label }) => {
      const labelName =
        label === CreatorLabel.CHAMPION ? 'Champion' : 'Ambassador';
      toast({
        title: `Failed to Add ${labelName} Label`,
        description: `There was an error adding the ${labelName} label to the account.`,
        status: 'error',
        position: 'bottom',
        duration: 5000,
        isClosable: true,
      });
    },
  });

  const removeCreatorLabelMutation = useMutation({
    mutationFn: async ({
      creator_user_uuid,
    }: {
      creator_user_uuid: string;
    }) => {
      const response = await apiClient.POST(
        '/api/video/hooks/remove_creator_label',
        {
          body: { creator_user_uuid },
        }
      );

      const { data, error } = response;
      if (error || !data) {
        throw new Error(
          `Failed to remove creator label: ${error || 'No data returned'}`
        );
      }
      return data;
    },
    onSuccess: () => {
      setCurrentCreatorLabel(undefined);
      toast({
        title: 'Label removed',
        description: "This creator's label has been removed.",
        status: 'success',
        position: 'bottom',
        duration: 5000,
        isClosable: true,
      });
    },
    onError: () => {
      toast({
        title: 'Failed to Remove Hook Creator Label',
        description: 'There was an error removing the label from the account.',
        status: 'error',
        position: 'bottom',
        duration: 5000,
        isClosable: true,
      });
    },
  });

  return {
    setCreatorLabelMutation,
    removeCreatorLabelMutation,
  };
}
