"use client";

import { useRef, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import {
  DialogMode,
  ProjectFormValues,
  MappedProject,
  ProjectBody,
} from "../types/project.types";
import {
  AddProject,
  editProject,
  deleteProject,
} from "@/lib/services/profile.service";
import showCustomToast from "@/components/common/toaster/CustomToast";
import {
  mapFormToProjectBody,
  mapItemToProjectFormValues,
} from "../utils/project.utils";

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

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

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

  // ─── Add / Edit Mutation ──────────────────────────────────────────────────
  const { mutate, isPending } = useMutation({
    mutationFn: (body: ProjectBody) =>
      modeRef.current === "edit" && editingUuidRef.current
        ? editProject(editingUuidRef.current, body)
        : AddProject(body),
    onMutate: async (newBody) => {
      await queryClient.cancelQueries({ queryKey: ["profile"] });
      const previousProfile = queryClient.getQueryData(["profile"]);

      queryClient.setQueryData(["profile"], (old: any) => {
        if (!old) return old;
        const current = old.data.project ?? old.data.projects ?? [];
        const projects = [...current];

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

        return {
          ...old,
          data: { ...old.data, project: projects, projects: projects },
        };
      });

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

  // ─── Delete Mutation ──────────────────────────────────────────────────────
  const { mutate: deleteMutate } = useMutation({
    mutationFn: deleteProject,
    onMutate: async (uuid) => {
      await queryClient.cancelQueries({ queryKey: ["profile"] });
      const previousProfile = queryClient.getQueryData(["profile"]);
      queryClient.setQueryData(["profile"], (old: any) => {
        if (!old) return old;
        const current = old.data.project ?? old.data.projects ?? [];
        const filtered = current.filter((p: any) => p.uuid !== uuid);
        return {
          ...old,
          data: { ...old.data, project: filtered, projects: filtered },
        };
      });
      return { previousProfile };
    },
    onSuccess: () => {
      showCustomToast({ type: "success", message: "Project deleted" });
    },
    onError: (err, uuid, context: any) => {
      queryClient.setQueryData(["profile"], context.previousProfile);
      showCustomToast({ type: "error", message: "Failed to delete project" });
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ["profile"] });
    },
  });

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

  const openEditDialog = (item: MappedProject) => {
    console.log("EDIT+>>>>>>>>>>>>");

    modeRef.current = "edit";
    editingUuidRef.current = item.uuid;

    setDefaultValues([mapItemToProjectFormValues(item)]);
    setIsDialogOpen(true);
  };

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

  const handleSubmit = (data: { projects: ProjectFormValues[] }) => {
    const body = mapFormToProjectBody(data.projects[0]);
    console.log("======modeRef", data);

    mutate(body);
  };

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