import { useUser } from '@clerk/nextjs';
import { useMutation, useQuery } from '@tanstack/react-query';

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

export type VoxPersonaSource =
  | 'random_lyrics'
  | 'happy_birthday'
  | 'random_song'
  | 'library_song';

export type CreateVoxPersonaParams = {
  user_id: string;
  clip_id: string;
  name: string;
  description?: string;
  source: VoxPersonaSource;
  genres: string;
  language: string;
  is_public: boolean;
};

export function useCreateVoxPersona() {
  const apiClient = useApiClient();
  const { user } = useUser();

  return useMutation({
    mutationFn: async (params: Omit<CreateVoxPersonaParams, 'user_id'>) => {
      if (!user?.id) {
        throw new Error('User not authenticated');
      }

      const { data, response } = await apiClient.POST(
        '/api/persona/vox/create/',
        {
          body: { ...params, user_id: user.id } as any,
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );

      if (!response.ok) {
        const errorMsg = (data as any)?.detail
          ? typeof (data as any).detail === 'string'
            ? (data as any).detail
            : JSON.stringify((data as any).detail)
          : 'Failed to create vox persona.';
        throw new Error(errorMsg);
      }

      return { ...data, is_owned: true };
    },
    onSuccess: () => {
      toast({
        title: 'Success',
        description: 'Vox persona created successfully.',
        status: 'info',
        duration: 5000,
        isClosable: true,
      });
    },
    onError: (error: Error) => {
      toast({
        title: 'Error',
        description:
          error.message || 'An error occurred while creating the vox persona.',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
      console.error('Error creating vox persona:', error);
    },
  });
}

export function usePersonaById(personaId: string | null) {
  const apiClient = useApiClient();

  return useQuery({
    queryKey: ['persona', personaId],
    queryFn: async () => {
      if (!personaId) {
        return null;
      }

      const { data, response } = await apiClient.GET(
        '/api/persona/get-persona/{persona_id}/',
        {
          params: {
            path: {
              persona_id: personaId,
            },
          },
        }
      );

      if (!response.ok) {
        throw new Error('Failed to fetch persona');
      }

      return {
        ...(data || {}),
        upvote_count: data?.upvote_count || 0,
        is_loved: data?.is_loved || false,
      };
    },
    enabled: !!personaId,
  });
}
