import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import { QUERY_KEYS } from "@/utils/query-key";
import {
  assignTicket,
  createTicketDepartment,
  createTicketStatus,
  createTicketSubject,
  deleteTicketDepartment,
  deleteTicketStatus,
  deleteTicketSubject,
  getTicket,
  getTicketDepartments,
  getTicketStatuses,
  getTickets,
  getTicketSubjects,
  replyToTicket,
  updateTicketDepartment,
  updateTicketStatus,
  updateTicketStatusConfig,
  updateTicketSubject,
} from "./_requests";
import {
  TicketAssignRequest,
  TicketDepartmentPayload,
  TicketFilters,
  TicketReplyRequest,
  TicketStatusPayload,
  TicketStatusUpdateRequest,
  TicketSubjectPayload,
} from "./_models";

export const useTickets = (filters?: TicketFilters) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_TICKETS, filters],
    queryFn: () => getTickets(filters),
  });
};

export const useTicket = (id?: string) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_TICKET, id],
    queryFn: () => getTicket(id || ""),
    enabled: !!id,
  });
};

export const useTicketDepartments = (options?: { activeOnly?: boolean }) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_TICKET_DEPARTMENTS, options?.activeOnly],
    queryFn: () => getTicketDepartments({ activeOnly: options?.activeOnly }),
  });
};

export const useTicketStatuses = (options?: { activeOnly?: boolean }) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_TICKET_STATUSES, options?.activeOnly],
    queryFn: () => getTicketStatuses({ activeOnly: options?.activeOnly }),
  });
};

export const useTicketSubjects = (options?: {
  activeOnly?: boolean;
  departmentId?: number;
}) => {
  return useQuery({
    queryKey: [
      QUERY_KEYS.GET_TICKET_SUBJECTS,
      options?.activeOnly,
      options?.departmentId,
    ],
    queryFn: () =>
      getTicketSubjects({
        activeOnly: options?.activeOnly,
        departmentId: options?.departmentId,
      }),
  });
};

export const useReplyTicket = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      ticketId,
      payload,
    }: {
      ticketId: string;
      payload: TicketReplyRequest;
    }) => replyToTicket(ticketId, payload),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET, variables.ticketId],
      });
      toast.success("پیام با موفقیت ارسال شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در ارسال پیام");
    },
  });
};

export const useUpdateTicketStatusMutation = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      ticketId,
      payload,
    }: {
      ticketId: string;
      payload: TicketStatusUpdateRequest;
    }) => updateTicketStatus(ticketId, payload),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET, variables.ticketId],
      });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKETS],
      });
      toast.success("وضعیت تیکت با موفقیت به‌روزرسانی شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در به‌روزرسانی وضعیت تیکت");
    },
  });
};

export const useAssignTicket = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      ticketId,
      payload,
    }: {
      ticketId: string;
      payload: TicketAssignRequest;
    }) => assignTicket(ticketId, payload),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET, variables.ticketId],
      });
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKETS],
      });
      toast.success("تیکت با موفقیت اختصاص داده شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در اختصاص تیکت");
    },
  });
};

export const useCreateTicketDepartment = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (payload: TicketDepartmentPayload) =>
      createTicketDepartment(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET_DEPARTMENTS],
      });
      toast.success("دپارتمان جدید اضافه شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در ایجاد دپارتمان");
    },
  });
};

export const useUpdateTicketDepartmentMutation = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      id,
      payload,
    }: {
      id: string | number;
      payload: TicketDepartmentPayload;
    }) => updateTicketDepartment(id, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET_DEPARTMENTS],
      });
      toast.success("دپارتمان به‌روزرسانی شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در به‌روزرسانی دپارتمان");
    },
  });
};

export const useDeleteTicketDepartmentMutation = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string | number) => deleteTicketDepartment(id),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET_DEPARTMENTS],
      });
      toast.success("دپارتمان حذف شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در حذف دپارتمان");
    },
  });
};

export const useCreateTicketStatus = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (payload: TicketStatusPayload) =>
      createTicketStatus(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET_STATUSES],
      });
      toast.success("وضعیت جدید اضافه شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در ایجاد وضعیت");
    },
  });
};

export const useUpdateTicketStatusConfigMutation = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      id,
      payload,
    }: {
      id: string | number;
      payload: TicketStatusPayload;
    }) => updateTicketStatusConfig(id, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET_STATUSES],
      });
      toast.success("وضعیت به‌روزرسانی شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در به‌روزرسانی وضعیت");
    },
  });
};

export const useDeleteTicketStatusMutation = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string | number) => deleteTicketStatus(id),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET_STATUSES],
      });
      toast.success("وضعیت حذف شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در حذف وضعیت");
    },
  });
};

export const useCreateTicketSubject = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (payload: TicketSubjectPayload) =>
      createTicketSubject(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET_SUBJECTS],
      });
      toast.success("موضوع جدید اضافه شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در ایجاد موضوع");
    },
  });
};

export const useUpdateTicketSubjectMutation = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      id,
      payload,
    }: {
      id: string | number;
      payload: TicketSubjectPayload;
    }) => updateTicketSubject(id, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET_SUBJECTS],
      });
      toast.success("موضوع به‌روزرسانی شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در به‌روزرسانی موضوع");
    },
  });
};

export const useDeleteTicketSubjectMutation = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string | number) => deleteTicketSubject(id),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_TICKET_SUBJECTS],
      });
      toast.success("موضوع حذف شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در حذف موضوع");
    },
  });
};


