import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  addProfileLink,
  updateProfileLink,
  deleteProfileLink,
} from "@/lib/services/profile.service";
import showCustomToast from "@/components/common/toaster/CustomToast";
import { ProfileLinksType } from "@/type/profileType";
import { getSocialMedia } from "@/lib/services/options.services/socialMedia.services";
import { APIResponseType } from "@/type/comonType";
import { SocialMediaPlatform } from "@/lib/options.type/socalMedia.type";
import { MapDataToDropdownOptions } from "@/lib/mapData/mapDataToDropdownOptions";

export const useLinksSection = () => {
  const queryClient = useQueryClient();
  const [activeDialog, setActiveDialog] = useState<
    "portfolio" | "socialMedia" | null
  >(null);
  const [selectedItem, setSelectedItem] = useState<any>(null);

  const { data: socialMediaList } = useQuery<
    APIResponseType<SocialMediaPlatform[]>
  >({
    queryKey: ["social_media_list"],
    queryFn: () => getSocialMedia(),
  });

  const filterSocialMediaOptions = MapDataToDropdownOptions(
    socialMediaList?.data,
  );

  const { mutate: addLink, isPending: isAdding } = useMutation({
    mutationFn: addProfileLink,
    onMutate: async (newLink) => {
      await queryClient.cancelQueries({ queryKey: ["profile"] });
      const previousProfile = queryClient.getQueryData(["profile"]);

      queryClient.setQueryData(["profile"], (old: any) => {
        if (!old) return old;
        return {
          ...old,
          data: {
            ...old.data,
            links: [
              ...(old.data.links || []),
              { ...newLink, uuid: "temp-id-" + Math.random() },
            ],
          },
        };
      });

      // Close dialog immediately for "instant" feel
      setActiveDialog(null);
      setSelectedItem(null);

      return { previousProfile };
    },
    onError: (err, newLink, context: any) => {
      queryClient.setQueryData(["profile"], context.previousProfile);
      showCustomToast({
        type: "error",
        message: "Failed to add link. Rolling back.",
      });
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ["profile"] });
    },
    onSuccess: () => {
      showCustomToast({ type: "success", message: "Link added successfully" });
    },
  });

  const { mutate: updateLink, isPending: isUpdating } = useMutation({
    mutationFn: updateProfileLink,
    onMutate: async (updatedLink) => {
      await queryClient.cancelQueries({ queryKey: ["profile"] });
      const previousProfile = queryClient.getQueryData(["profile"]);

      queryClient.setQueryData(["profile"], (old: any) => {
        if (!old) return old;
        return {
          ...old,
          data: {
            ...old.data,
            links: (old.data.links || []).map((link: any) =>
              link.uuid === updatedLink.uuid
                ? { ...link, ...updatedLink }
                : link,
            ),
          },
        };
      });

      setActiveDialog(null);
      setSelectedItem(null);

      return { previousProfile };
    },
    onError: (err, updatedLink, context: any) => {
      queryClient.setQueryData(["profile"], context.previousProfile);
      showCustomToast({
        type: "error",
        message: "Failed to update link. Rolling back.",
      });
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ["profile"] });
    },
    onSuccess: () => {
      showCustomToast({
        type: "success",
        message: "Link updated successfully",
      });
    },
  });

  const { mutate: deleteLink, isPending: isDeleting } = useMutation({
    mutationFn: deleteProfileLink,
    onMutate: async (uuid) => {
      await queryClient.cancelQueries({ queryKey: ["profile"] });
      const previousProfile = queryClient.getQueryData(["profile"]);

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

      return { previousProfile };
    },
    onError: (err, uuid, context: any) => {
      queryClient.setQueryData(["profile"], context.previousProfile);
      showCustomToast({
        type: "error",
        message: "Failed to delete link. Rolling back.",
      });
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ["profile"] });
    },
    onSuccess: () => {
      showCustomToast({
        type: "success",
        message: "Link deleted successfully",
      });
    },
  });

  const handleEdit = (item: any, type: "portfolio" | "socialMedia") => {

    setSelectedItem(item);
    setActiveDialog(type);
  };

  const handleSubmit = (data: any, type: "portfolio" | "socialMedia") => {
    const variant = type === "portfolio" ? "portfolioLinks" : "socialMedia";
    const linkData = data[variant][0];

    const cleanUrl = (url?: string) => {
      if (!url || url === "https://") return "";
      return url.replace(/^https?:\/\//, "");
    };

    const platformLabel =
      linkData.platform && typeof linkData.platform === "object"
        ? (linkData.platform.label ?? linkData.platform.value ?? "")
        : (linkData.platform ?? "");

    const platformUuid =
      linkData.platform && typeof linkData.platform === "object"
        ? (linkData.platform.uuid ?? linkData.platform.id ?? "")
        : (linkData.platform ?? "");

    const payload: ProfileLinksType = {
      uuid: selectedItem?.uuid,
      platform: platformLabel, // ✅ human-readable name so optimistic update shows label
      url: cleanUrl(linkData.url),
      social_media_platform_id: platformUuid, // ✅ UUID for the API FK
      is_portfolio: type === "portfolio" || linkData.is_portfolio,
    };

    if (selectedItem) {
      updateLink(payload);
    } else {
      addLink(payload);
    }
  };

  return {
    activeDialog,
    setActiveDialog,
    selectedItem,
    setSelectedItem,
    handleEdit,
    handleSubmit,
    deleteLink,
    filterSocialMediaOptions,
    isEditing: !!selectedItem,
    isLoading: isAdding || isUpdating || isDeleting,
  };
};
