import { useState } from "react";
import {
  createDepartment,
  getDepartments,
  getDepartmentById,
  updateDepartment,
  deleteDepartment,
  toggleDepartmentStatus,
  type DepartmentFilters,
  type CreateDepartmentData,
  type UpdateDepartmentData,
  type DepartmentListResponse,
  type DepartmentResponse,
  type DeleteDepartmentResponse,
} from "../../services/departmentService";
import { handleToastError, customizeToast } from "../../utils";

function useDepartmentService() {
  const [loading, setLoading] = useState(false);

  // Create Department
  const createDepartmentAsync = async (data: CreateDepartmentData) => {
    try {
      setLoading(true);
      const response = await createDepartment(data);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Department created successfully", "success");
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Department created successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to create department";
        customizeToast(errorMessage, "danger");
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      customizeToast(errorMessage, "danger");
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  // Get Departments
  const getDepartmentsAsync = async (filters?: DepartmentFilters) => {
    try {
      setLoading(true);
      const response = await getDepartments(filters);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Departments fetched successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to fetch departments";
        customizeToast(errorMessage, "danger");
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      customizeToast(errorMessage, "danger");
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  // Get Department by ID
  const getDepartmentByIdAsync = async (id: string) => {
    try {
      setLoading(true);
      const response = await getDepartmentById(id);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Department fetched successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to fetch department";
        customizeToast(errorMessage, "danger");
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      customizeToast(errorMessage, "danger");
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  // Update Department
  const updateDepartmentAsync = async (data: UpdateDepartmentData) => {
    try {
      setLoading(true);
      const response = await updateDepartment(data);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Department updated successfully", "success");
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Department updated successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to update department";
        customizeToast(errorMessage, "danger");
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      customizeToast(errorMessage, "danger");
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  // Delete Department
  const deleteDepartmentAsync = async (id: string) => {
    try {
      setLoading(true);
      const response = await deleteDepartment(id);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Department deleted successfully", "success");
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Department deleted successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to delete department";
        customizeToast(errorMessage, "danger");
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      customizeToast(errorMessage, "danger");
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  // Toggle Department Status
  const toggleDepartmentStatusAsync = async (id: string) => {
    try {
      setLoading(true);
      const response = await toggleDepartmentStatus(id);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Department status updated successfully", "success");
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Department status updated successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to update department status";
        customizeToast(errorMessage, "danger");
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = error?.response?.data?.message || error.toString();
      customizeToast(errorMessage, "danger");
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    createDepartment: createDepartmentAsync,
    getDepartments: getDepartmentsAsync,
    getDepartmentById: getDepartmentByIdAsync,
    updateDepartment: updateDepartmentAsync,
    deleteDepartment: deleteDepartmentAsync,
    toggleDepartmentStatus: toggleDepartmentStatusAsync,
  };
}

export default useDepartmentService;
