import { QueryKey, useMutation } from "@tanstack/react-query";
import { queryClient, toast } from "@xtablo/shared";
import { supabase } from "../lib/supabase";
import { useUser } from "../providers/UserStoreProvider";
import { useAuthedApi } from "./auth";

/**
 * Hook to update user profile using Supabase client
 * Updates both the profiles table and user metadata
 */
export function useUpdateProfile() {
  const user = useUser();

  const { mutate, isPending } = useMutation({
    mutationFn: async ({ firstName, lastName }: { firstName: string; lastName: string }) => {
      // Build the name from first_name and last_name if provided
      const fullName = [firstName, lastName].filter(Boolean).join(" ");

      const { error } = await supabase
        .from("profiles")
        .update({
          first_name: firstName,
          last_name: lastName,
          name: fullName,
        })
        .eq("id", user.id);

      if (error) {
        throw new Error(error.message);
      }
      return {};
    },
    onSuccess: () => {
      toast.add({
        title: "Profil mis à jour avec succès",
        description: "Vos informations ont été mises à jour avec succès",
        type: "success",
        position: "top-center",
      });
      queryClient.invalidateQueries({ queryKey: ["user"] as QueryKey });
    },
    onError: () => {
      toast.add({
        title: "Erreur",
        description: "Une erreur est survenue lors de la mise à jour de votre profil",
        type: "error",
        position: "top-center",
      });
    },
  });
  return { mutate, isPending };
}

type FileUploadRequest = {
  content: string; // base64 encoded file content
  contentType: string; // MIME type (e.g., "image/jpeg")
  filename: string; // Original filename
};

export const useUploadAvatar = () => {
  const api = useAuthedApi();
  const { mutate, isPending } = useMutation({
    mutationFn: async ({ file }: { file: File | null }) => {
      if (!file) {
        throw new Error("No file selected");
      }

      // Read file as base64 using FileReader
      const base64Content = await new Promise<string>((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = () => {
          if (typeof reader.result === "string") {
            // Remove data URL prefix (e.g., "data:image/jpeg;base64,")
            const base64 = reader.result.split(",")[1];
            resolve(base64);
          } else {
            reject(new Error("Failed to read file"));
          }
        };

        reader.onerror = () => {
          reject(new Error("Error reading file"));
        };

        reader.readAsDataURL(file);
      });

      // Prepare upload request
      const uploadRequest: FileUploadRequest = {
        content: base64Content,
        contentType: file.type || "image/jpeg",
        filename: file.name,
      };

      // Upload to backend
      const response = await api.post("/api/v1/users/profile/avatar", uploadRequest);

      if (response.status !== 200) {
        throw new Error("Failed to upload avatar");
      }

      return response.data;
    },
    onSuccess: () => {
      toast.add({
        title: "Avatar mis à jour",
        description: "Votre photo de profil a été mise à jour avec succès",
        type: "success",
        position: "top-center",
      });
      // Refresh user data
      queryClient.invalidateQueries({ queryKey: ["user"] });
    },
    onError: (error: Error) => {
      toast.add({
        title: "Erreur",
        description: error.message || "Une erreur est survenue lors de l'upload",
        type: "error",
        position: "top-center",
      });
    },
  });
  return { mutate, isPending };
};

export const useRemoveAvatar = () => {
  const api = useAuthedApi();
  const { mutateAsync, isPending } = useMutation({
    mutationFn: async () => {
      await api.delete("/api/v1/users/profile/avatar");
    },
    onSuccess: () => {
      toast.add({
        title: "Avatar supprimé",
        description: "Votre photo de profil a été supprimée avec succès",
        type: "success",
        position: "top-center",
      });
      queryClient.invalidateQueries({ queryKey: ["user"] });
    },
  });
  return { mutateAsync, isPending };
};
