import { useRef, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import {
  addProfileLanguage,
  updateProfileLanguage,
  deleteProfileLanguage,
} from "@/lib/services/profile.service";
import showCustomToast from "@/components/common/toaster/CustomToast";

interface UseLanguageSectionReturn {
  isDialogOpen: boolean;
  isPending: boolean;
  openDialog: () => void;
  isEditingToggle: () => void;
  isEdit: boolean;
  closeDialog: () => void;
  handleSubmit: (data: any) => void;
  deleteLanguage: (uuid: string) => void;
}

export function useLanguageSection(): UseLanguageSectionReturn {
  const queryClient = useQueryClient();
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  const [isEdit, setIsEdit] = useState(false);

  const isEditingToggle = () => {
    setIsEdit((prev) => !prev); // ✅ always works off the latest value
    console.log(isEdit);
  };

  // ─── Add/Update Mutation ───────────────────────────────────────────────────
  const { mutate, isPending } = useMutation<
    { message: string },
    AxiosError<{ message: string }>,
    { language_uuid: string; proficiency: string }
  >({
    mutationFn: addProfileLanguage,
    onMutate: async (newLang) => {
      await queryClient.cancelQueries({ queryKey: ["profile-languages"] });
      const previousLangs = queryClient.getQueryData(["profile-languages"]);

      queryClient.setQueryData(["profile-languages"], (old: any) => {
        if (!old) return old;
        return {
          ...old,
          data: [
            ...old.data.filter(
              (l: any) => l.language_uuid !== newLang.language_uuid,
            ),
            {
              uuid: "temp-" + Date.now(),
              language_uuid: newLang.language_uuid,
              language_name: "Loading...",
              proficiency: newLang.proficiency,
            },
          ],
        };
      });

      return { previousLangs };
    },
    onSuccess: (data) => {
      showCustomToast({ type: "success", message: data.message });
      closeDialog();
    },
    onError: (error, _, context: any) => {
      queryClient.setQueryData(["profile-languages"], context.previousLangs);
      showCustomToast({
        type: "error",
        message: error.response?.data?.message ?? "Something went wrong",
      });
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ["profile-languages"] });
    },
  });

  // ─── Delete Mutation ───────────────────────────────────────────────────────
  const { mutate: deleteMutate } = useMutation({
    mutationFn: deleteProfileLanguage,
    onMutate: async (uuid) => {
      await queryClient.cancelQueries({ queryKey: ["profile-languages"] });
      const previousLangs = queryClient.getQueryData(["profile-languages"]);

      queryClient.setQueryData(["profile-languages"], (old: any) => {
        if (!old) return old;
        return {
          ...old,
          data: old.data.filter((l: any) => l.uuid !== uuid),
        };
      });

      return { previousLangs };
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ["profile-languages"] });
    },
  });

  const openDialog = () => setIsDialogOpen(true);
  const closeDialog = () => setIsDialogOpen(false);

  const handleSubmit = (data: any) => {
    const langData = data.languageSkills?.[0];

    const selectedLanguageId = langData?.languageSkillName?.id;

    const proficiency = langData?.proficiency?.id || 0;
    console.log("__________f__________");

    if (!selectedLanguageId) return;
    console.log("__________l__________");

    const previousLangs = queryClient.getQueryData([
      "profile-languages",
    ]) as any;

    const currentLangs = previousLangs?.data || [];

    const alreadyExists = currentLangs.some(
      (lang: any) =>
        lang.language_uuid === selectedLanguageId ||
        lang.uuid === selectedLanguageId,
    );

    if (!alreadyExists) {
      mutate({
        language_uuid: selectedLanguageId,
        proficiency: proficiency.toString(),
      });
    }
  };

  return {
    isDialogOpen,
    isPending,
    openDialog,
    isEditingToggle,
    isEdit,
    closeDialog,
    handleSubmit,
    deleteLanguage: (uuid: string) => deleteMutate(uuid),
  };
}
