import { useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { editProfile, getProfile } from "@/lib/services/profile.service";
import showCustomToast from "@/components/common/toaster/CustomToast";
import { DialogMode } from "../types/experience.types";
import { APIResponseType } from "@/type/comonType";
import { ProfileDataType } from "@/type/userType";
import { mapReferenceToUserDetails } from "../utils";
import {
  addReference,
  editReference,
  deleteReference,
  getHobbies,
  getPersonalValues,
} from "@/lib/services/other.servise";

// ─── Types ────────────────────────────────────────────────────────────────
export type OthersDialogKey =
  | "references"
  | "personalValues"
  | "interest"
  | "declaration"
  | "signature";

export type MappedReference = {
  id: string;
  label: string;
  [key: string]: any;
};

// ─── Dialog config for hobbies & personal values (mirrors SKILL_DIALOG_CONFIG) ─
export type OthersDropdownDialogKey = "personalValues" | "interest";

export interface OthersDialogConfig {
  title: string;
  variant: "personalValues" | "interest";
  formKey: "personalValues" | "interest";
  nameField: "personalValueName" | "interestName";
  profileKey: "personal_values" | "hobbies"; // key in profile response
  apiField: "personal_value_uuids" | "hobby_uuids"; // key for PUT /api/v1/profile
}

export const OTHERS_DIALOG_CONFIG: Record<
  OthersDropdownDialogKey,
  OthersDialogConfig
> = {
  personalValues: {
    title: "Personal Values",
    variant: "personalValues",
    formKey: "personalValues",
    nameField: "personalValueName",
    profileKey: "personal_values",
    apiField: "personal_value_uuids",
  },
  interest: {
    title: "Interest & Hobbies",
    variant: "interest",
    formKey: "interest",
    nameField: "interestName",
    profileKey: "hobbies",
    apiField: "hobby_uuids",
  },
};

export function useOthersSection() {
  const queryClient = useQueryClient();
  const [isPersinalValueEdit, setPersinalValueEdit] = useState(false);
  const [isHobbyEdit, setHobbyEdit] = useState(false);

  const isPersonalValueEditingToggle = () => {
    setPersinalValueEdit((prev) => !prev); // ✅ always works off the latest value
    console.log(isPersinalValueEdit);
  };
  const isHobbyEditingToggle = () => {
    setHobbyEdit((prev) => !prev); // ✅ always works off the latest value
    console.log(isHobbyEdit);
  };

  // ─── 1. QUERY ─────────────────────────────────────────────────────────────
  const { data: profileData, isLoading } = useQuery<
    APIResponseType<ProfileDataType>
  >({
    queryKey: ["profile"],
    queryFn: getProfile,
  });

  // options
  const hobbiesQuery = useQuery({
    queryKey: ["hobbies-list"],
    queryFn: getHobbies,
    staleTime: 10 * 60 * 1000,
  });
  const hobbbyOption = hobbiesQuery?.data?.data?.map((item: any) => ({
    id: item.uuid,
    uuid: item.uuid,
    label: item.name,
  }));
  const personalValuesQuery = useQuery({
    queryKey: ["personal-values-list"],
    queryFn: getPersonalValues,
    staleTime: 10 * 60 * 1000,
  });
  const personalValuesOption = personalValuesQuery?.data?.data?.map(
    (item: any) => ({
      id: item.uuid,
      uuid: item.uuid,
      label: item.name,
    }),
  );

  console.log("personalValuesOption---------------", personalValuesOption);

  // ─── 2. DIALOG STATE ──────────────────────────────────────────────────────
  const [activeDialog, setActiveDialog] = useState<OthersDialogKey | null>(
    null,
  );
  const [dialogKey, setDialogKey] = useState("");
  const [defaultValues, setDefaultValues] = useState<any>(undefined);
  const modeRef = useRef<DialogMode>("add");
  const editingIdRef = useRef<string | undefined>(undefined);
  const activeDialogRef = useRef<OthersDialogKey | null>(null);

  // ─── 3. MAPPED DISPLAY DATA ───────────────────────────────────────────────
  const mappedReferenceDetails = useMemo(() => {
    return mapReferenceToUserDetails(profileData?.data).reference || [];
  }, [profileData]);

  const mappedPersonalValues = useMemo(() => {
    return (
      profileData?.data?.personal_values?.map((item: any) => ({
        id: item.uuid ?? item.id,
        uuid: item.uuid ?? item.id,
        label: item.name ?? item.label,
      })) || []
    );
  }, [profileData]);

  const mappedHobbies = useMemo(() => {
    return (
      profileData?.data?.hobbies?.map((item: any) => ({
        id: item.uuid ?? item.id,
        uuid: item.uuid ?? item.id,
        label: item.name ?? item.label,
      })) || []
    );
  }, [profileData]);

  // ─── 4. MUTATIONS ─────────────────────────────────────────────────────────

  // Generic mutation for profile update (used by profileUpdate, hobbies, personal values)
  const { mutate: profileUpdate } = useMutation<
    APIResponseType<unknown>,
    AxiosError<{ message: string }>,
    Partial<ProfileDataType>
  >({
    mutationFn: editProfile as any,
    onMutate: async (newProfileData) => {
      await queryClient.cancelQueries({ queryKey: ["profile"] });
      const previousProfile = queryClient.getQueryData(["profile"]);

      queryClient.setQueryData(["profile"], (old: any) => {
        if (!old) return old;
        return {
          ...old,
          data: {
            ...old.data,
            about_me: newProfileData.about_me ?? old.data.about_me,
            declaration: newProfileData.declaration ?? old.data.declaration,
          },
        };
      });

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

  const referenceMutation = useMutation<
    { message: string },
    AxiosError<{ message: string }>,
    any
  >({
    mutationFn: (body: any) => {
      if (modeRef.current === "edit" && body.ReferenceUUID) {
        return editReference(body.ReferenceUUID, body.cleanPayload);
      }
      return addReference(body.cleanPayload);
    },
    onSuccess: (data) => {
      showCustomToast({ type: "success", message: data.message });
      queryClient.invalidateQueries({ queryKey: ["profile"] });
      closeDialog();
    },
    onError: (error) => {
      showCustomToast({
        type: "error",
        message: error.response?.data?.message ?? "Something went wrong",
      });
    },
  });

  const deleteReferenceMutation = useMutation<
    { message: string },
    AxiosError<{ message: string }>,
    string
  >({
    mutationFn: (uuid) => deleteReference(uuid),
    onSuccess: (data) => {
      showCustomToast({ type: "success", message: data.message });
      queryClient.invalidateQueries({ queryKey: ["profile"] });
    },
    onError: (error) => {
      showCustomToast({
        type: "error",
        message: error.response?.data?.message ?? "Something went wrong",
      });
    },
  });

  // ─── Hobbies mutation (same pattern as editSkills) ─────────────────────────
  const hobbiesMutation = useMutation<
    any,
    AxiosError<{ message: string }>,
    { uuids: string[]; items: any[] }
  >({
    mutationFn: (data) => editProfile({ hobby_uuids: data.uuids } as any),
    onMutate: async ({ uuids, items }) => {
      await queryClient.cancelQueries({ queryKey: ["profile"] });
      const previousProfile = queryClient.getQueryData(["profile"]);

      queryClient.setQueryData(["profile"], (old: any) => {
        if (!old) return old;
        const currentHobbies = (old.data.hobbies || []).filter((h: any) =>
          uuids.includes(h.uuid || h.id),
        );
        items.forEach((newItem) => {
          const itemUuid = newItem.uuid || newItem.id;
          if (!currentHobbies.find((s: any) => (s.uuid || s.id) === itemUuid)) {
            currentHobbies.push({
              id: newItem.id,
              uuid: itemUuid,
              name: newItem.name || newItem.label,
            });
          }
        });

        return {
          ...old,
          data: {
            ...old.data,
            hobbies: currentHobbies,
          },
        };
      });

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

  // ─── Personal Values mutation (same pattern as editSkills) ─────────────────
  const personalValuesMutation = useMutation<
    any,
    AxiosError<{ message: string }>,
    { uuids: string[]; items: any[] }
  >({
    mutationFn: (data) =>
      editProfile({ personal_value_uuids: data.uuids } as any),
    onMutate: async ({ uuids, items }) => {
      await queryClient.cancelQueries({ queryKey: ["profile"] });
      const previousProfile = queryClient.getQueryData(["profile"]);

      queryClient.setQueryData(["profile"], (old: any) => {
        if (!old) return old;
        const currentValues = (old.data.personal_values || []).filter(
          (v: any) => uuids.includes(v.uuid || v.id),
        );
        items.forEach((newItem) => {
          const itemUuid = newItem.uuid || newItem.id;
          if (!currentValues.find((s: any) => (s.uuid || s.id) === itemUuid)) {
            currentValues.push({
              id: newItem.id,
              uuid: itemUuid,
              name: newItem.name || newItem.label,
            });
          }
        });

        return {
          ...old,
          data: {
            ...old.data,
            personal_values: currentValues,
          },
        };
      });

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

  const declarationMutation = useMutation<
    { message: string },
    AxiosError<{ message: string }>,
    any
  >({
    mutationFn: (body) => {
      // TODO: replace with editDeclaration(body)
      return Promise.resolve({ message: "Declaration saved" });
    },
    onSuccess: (data) => {
      showCustomToast({
        type: "success",
        message: data.message || "Declaration saved",
      });
      queryClient.invalidateQueries({ queryKey: ["profile"] });
      closeDialog();
    },
    onError: (error) => {
      showCustomToast({
        type: "error",
        message: error.response?.data?.message ?? "Something went wrong",
      });
    },
  });

  const signatureMutation = useMutation<
    { message: string },
    AxiosError<{ message: string }>,
    any
  >({
    mutationFn: () => {
      return Promise.resolve({ message: "Signature updated" });
    },
    onSuccess: (data) => {
      showCustomToast({ type: "success", message: data.message });
      queryClient.invalidateQueries({ queryKey: ["profile"] });
      closeDialog();
    },
    onError: (error) => {
      showCustomToast({
        type: "error",
        message: error.response?.data?.message ?? "Something went wrong",
      });
    },
  });

  // ─── 5. MUTATION ROUTER ───────────────────────────────────────────────────
  const isPendingMap: Record<OthersDialogKey, boolean> = {
    references: referenceMutation.isPending,
    personalValues: personalValuesMutation.isPending,
    interest: hobbiesMutation.isPending,
    declaration: declarationMutation.isPending,
    signature: signatureMutation.isPending,
  };

  // ─── 6. OPTIONS MAP ───────────────────────────────────────────────────────
  const optionsMap: Record<string, any[]> = {
    personalValues: personalValuesOption ?? [],
    interest: hobbbyOption ?? [],
  };

  // ─── 7. HANDLERS ──────────────────────────────────────────────────────────
  const openAddDialog = (key: OthersDialogKey) => {
    modeRef.current = "add";
    activeDialogRef.current = key;
    editingIdRef.current = undefined;
    setDefaultValues(undefined); // blank form
    setActiveDialog(key);
    setDialogKey(`${key}-${Date.now()}`);
  };

  const openEditDialog = (key: OthersDialogKey, item: any) => {
    modeRef.current = "edit";
    activeDialogRef.current = key;
    editingIdRef.current = item.id;
    setDefaultValues(buildDefaultValues(key, item)); // pre-filled form
    setActiveDialog(key);
    setDialogKey(`${key}-${Date.now()}`);
  };

  const closeDialog = () => {
    setActiveDialog(null);
    setDefaultValues(undefined);
    editingIdRef.current = undefined;
    activeDialogRef.current = null;
  };

  // ─── 8. DEFAULT VALUES builder ────────────────────────────────────────────
  const buildDefaultValues = (key: OthersDialogKey, item?: any): any => {
    console.log("item------------", item);
    console.log("key", key);

    if (item) {
      return { [key]: [item] };
    }
    return undefined;
  };

  // ─── 9. SUBMIT HANDLER ───────────────────────────────────────────────────
  const handleSubmit = (data: any) => {
    console.log("DATA----++++------", data);
    const key = activeDialogRef.current;
    if (!key) return;

    // Handle hobbies and personal values (dropdown pattern like skills)
    if (key === "interest" || key === "personalValues") {
      const config = OTHERS_DIALOG_CONFIG[key as OthersDropdownDialogKey];
      const items = data[config.formKey];
      // if (!items || !items.length) return;
      console.log("items----++++------", items);

      const newItems = items
        .map((row: any) => row[config.nameField])
        .filter(Boolean);
      // if (!newItems.length) return;
      console.log("newItems", newItems);
      console.log("first item", newItems[0]);

      const newUuids = items.flatMap((row: any) => row[config.nameField] || []);
      // Get current saved UUIDs from profile
      const currentProfile = queryClient.getQueryData(["profile"]) as any;
      const currentItems = currentProfile?.data?.[config.profileKey] || [];
      let currentUuids = currentItems.map((s: any) => s.uuid || s.id);

      if (modeRef.current === "edit" && editingIdRef.current) {
        currentUuids = currentUuids.filter(
          (id: string) => id !== editingIdRef.current,
        );
      }

      // Combine current + new UUIDs (deduplicated)
      const combinedUuids = Array.from(new Set([...currentUuids, ...newUuids]));

      if (key === "interest") {
        hobbiesMutation.mutate({
          uuids: combinedUuids,
          items: newItems,
        });
      } else {
        personalValuesMutation.mutate({
          uuids: combinedUuids,
          items: newItems,
        });
      }
      return;
    }

    // Handle references (original form pattern)
    if (key === "references") {
      const payload = data[key]?.[0];
      if (!payload) return;

      // Remove id from body — it goes in the URL via editingIdRef
      const { uuid, id, ...cleanPayload } = payload;
      const ReferenceUUID = uuid || id || "";
      referenceMutation.mutate({ cleanPayload, ReferenceUUID });
      return;
    }
    // Handle declaration
    if (key === "declaration") {
      const payload = data[key]?.[0];
      if (!payload) return;
      declarationMutation.mutate(payload);
      return;
    }

    // Handle signature
    if (key === "signature") {
      const payload = data[key]?.[0];
      if (!payload) return;
      signatureMutation.mutate(payload);
      return;
    }
  };

  // ─── 10. DELETE HANDLERS (same pattern as skills) ─────────────────────────
  const handleDeleteHobby = (uuid: string) => {
    const currentProfile = queryClient.getQueryData(["profile"]) as any;
    const currentItems = currentProfile?.data?.hobbies || [];
    console.log("hobbies-currentItems----------------", currentItems);

    const remainingUuids = currentItems
      .map((s: any) => s.uuid || s.id)
      .filter((id: string) => id !== uuid);
    console.log("remainingUuids----------------------", remainingUuids);

    hobbiesMutation.mutate({ uuids: remainingUuids, items: [] });
  };
  const handleDeleteReference = (uuid: string) => {
    deleteReferenceMutation.mutate(uuid);
  };

  const handleDeletePersonalValue = (uuid: string) => {
    const currentProfile = queryClient.getQueryData(["profile"]) as any;
    const currentItems = currentProfile?.data?.personal_values || [];

    const remainingUuids = currentItems
      .filter((item: any) => (item.uuid || item.id) !== uuid)
      .map((item: any) => item.uuid || item.id);

    personalValuesMutation.mutate({
      uuids: remainingUuids,
      items: [],
    });
  };
  // Convenience: isPending for the currently open dialog
  const isPending = activeDialog ? isPendingMap[activeDialog] : false;

  return {
    // Data
    isPersinalValueEdit,
    isHobbyEditingToggle,
    isPersonalValueEditingToggle,
    isHobbyEdit,
    isLoading,
    isPending,
    activeDialog,
    dialogKey,
    defaultValues,
    isEditing: modeRef.current === "edit",
    mappedReferenceDetails,
    mappedPersonalValues,
    mappedHobbies,
    hobbiesOptions: hobbbyOption ?? [],
    personalValuesOptions: personalValuesOption ?? [],
    profilePersonalValues: mappedPersonalValues,
    profileHobbies: mappedHobbies,
    optionsMap,
    // Handlers
    openAddDialog,
    openEditDialog,
    closeDialog,
    handleSubmit,
    deleteHobby: handleDeleteHobby,
    deleteReference: handleDeleteReference,
    deletePersonalValue: handleDeletePersonalValue,
    handleDeclarationSave: (declaration: string) => {
      profileUpdate({ declaration } as any);
    },
    profileDeclaration: profileData?.data?.declaration || "",
  };
}
