import { useRef, useState } from "react";
import { YearsData } from "@/dummyData/data";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { DialogMode } from "../types/experience.types";
import { AwardForm, AwardsMapType } from "@/type/profileType";
import {
  addAward,
  editAward,
  deleteAward,
} from "@/lib/services/profile.service";
import showCustomToast from "@/components/common/toaster/CustomToast";
import {
  mapItemToAwardFormValues,
  mapFormToAwardBody,
} from "../utils/award.utils";

export function useAwardSection() {
  const queryClient = useQueryClient();

  // ─── Dialog state ─────────────────────────────────────────────────────────
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [defaultValues, setDefaultValues] = useState<AwardForm[] | undefined>(
    undefined,
  );

  // ─── Refs ─────────────────────────────────────────────────────────────────
  const modeRef = useRef<DialogMode>("add");
  const editingIdRef = useRef<string | undefined>(undefined);

  // ─── Mutation ─────────────────────────────────────────────────────────────
  const { mutate, isPending } = useMutation<
    { message: string },
    AxiosError<{ message: string }>,
    AwardForm
  >({
    mutationFn: (body) =>
      modeRef.current === "edit" && editingIdRef.current
        ? editAward(editingIdRef.current, body)
        : addAward(body),
    onMutate: async (newBody) => {
      await queryClient.cancelQueries({ queryKey: ["profile"] });
      const previousProfile = queryClient.getQueryData(["profile"]);

      queryClient.setQueryData(["profile"], (old: any) => {
        if (!old) return old;
        const awards = [...(old.data.awards || [])];

        if (modeRef.current === "edit" && editingIdRef.current) {
          const index = awards.findIndex(
            (a: any) => a.uuid === editingIdRef.current,
          );
          if (index !== -1) {
            awards[index] = { ...awards[index], ...newBody };
          }
        } else {
          // Add optimistic item
          awards.unshift({
            ...newBody,
            uuid: "temp-" + Date.now(),
          });
        }

        return {
          ...old,
          data: { ...old.data, awards },
        };
      });

      return { previousProfile };
    },
    onSuccess: (data) => {
      showCustomToast({ type: "success", message: data.message });
      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 { mutate: deleteMutate } = useMutation({
    mutationFn: deleteAward,
    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,
            awards: (old.data.awards || []).filter(
              (award: any) => award.uuid !== uuid,
            ),
          },
        };
      });
      return { previousProfile };
    },
    onSuccess: () => {
      showCustomToast({ type: "success", message: "Award deleted" });
    },
    onError: (err, uuid, context: any) => {
      queryClient.setQueryData(["profile"], context.previousProfile);
      showCustomToast({ type: "error", message: "Failed to delete award" });
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ["profile"] });
    },
  });

  // ─── Handlers ─────────────────────────────────────────────────────────────
  const openAddDialog = () => {
    modeRef.current = "add";
    editingIdRef.current = undefined;
    setDefaultValues(undefined);
    setIsDialogOpen(true);
  };

  const openEditDialog = (item: any) => {

    modeRef.current = "edit";
    editingIdRef.current = item.id || item.uuid;
    setDefaultValues([mapItemToAwardFormValues(item)]);
    setIsDialogOpen(true);
  };

  const closeDialog = () => {
    setIsDialogOpen(false);
    setDefaultValues(undefined);
  };

  const handleSubmit = (data: { awards: AwardForm[] }) => {
    console.log("-----------------+++++++++++++--------", data);

    const body = mapFormToAwardBody(data.awards[0], editingIdRef.current);
    mutate(body);
  };

  return {
    isDialogOpen,
    defaultValues,
    isPending,
    isEditing: modeRef.current === "edit",
    openAddDialog,
    openEditDialog,
    closeDialog,
    handleSubmit,
    deleteAward: deleteMutate,
    yearsOptions: YearsData,
  };
}
