import { useState } from "react";
import {
  createEmployee,
  getEmployees,
  getEmployeeById,
  updateEmployee,
  deleteEmployee,
  toggleEmployeeStatus,
  getDepartmentsForDropdown,
  getRolesForDropdown,
  getSalarySettingsForDropdown,
  getEmployeesForDropdown,
  type EmployeeFilters,
  type CreateEmployeeData,
  type UpdateEmployeeData,
  type EmployeeListResponse,
  type EmployeeResponse,
  type DeleteEmployeeResponse,
  type DepartmentListResponse,
  type RoleListResponse,
  type SalarySettingListResponse,
} from "../../services/employeeService";
import { getSettings, type SettingsResponse } from "../../services/settingsService";
import { handleToastError, customizeToast } from "../../utils";

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

  // Create Employee
  const createEmployeeAsync = async (data: CreateEmployeeData | FormData) => {
    try {
      setLoading(true);
      const response = await createEmployee(data);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Employee created successfully", "success");
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Employee created successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to create employee";
        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 Employees
  const getEmployeesAsync = async (filters?: EmployeeFilters) => {
    try {
      setLoading(true);
      const response = await getEmployees(filters);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Employees fetched successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to fetch employees";
        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 Employee by ID
  const getEmployeeByIdAsync = async (id: string) => {
    try {
      setLoading(true);
      const response = await getEmployeeById(id);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Employee fetched successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to fetch employee";
        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 Employee
  const updateEmployeeAsync = async (data: UpdateEmployeeData | FormData) => {
    try {
      setLoading(true);
      const response = await updateEmployee(data);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Employee updated successfully", "success");
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Employee updated successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to update employee";
        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 Employee
  const deleteEmployeeAsync = async (id: string) => {
    try {
      setLoading(true);
      const response = await deleteEmployee(id);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Employee deleted successfully", "success");
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Employee deleted successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to delete employee";
        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 Employee Status
  const toggleEmployeeStatusAsync = async (id: string) => {
    try {
      setLoading(true);
      const response = await toggleEmployeeStatus(id);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Employee status updated successfully", "success");
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Employee status updated successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to update employee 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);
    }
  };

  // Get Departments for dropdown
  const getDepartmentsAsync = async () => {
    try {
      const response = await getDepartmentsForDropdown();

      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Departments fetched successfully",
        };
      } else {
        const errorMessage =
          response.data?.message || "Failed to fetch departments";
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error.toString();
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    }
  };

  // Get Roles for dropdown
  const getRolesAsync = async (remove_admin: boolean = false) => {
    try {
      const response = await getRolesForDropdown(remove_admin ? "true" : undefined);

      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Roles fetched successfully",
        };
      } else {
        const errorMessage =
          response.data?.message || "Failed to fetch roles";
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error.toString();
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    }
  };

  // Get Salary Settings for dropdown
  const getSalarySettingsAsync = async () => {
    try {
      const response = await getSalarySettingsForDropdown();

      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Salary settings fetched successfully",
        };
      } else {
        const errorMessage =
          response.data?.message || "Failed to fetch salary settings";
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error.toString();
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    }
  };

  // Get Settings
  const getSettingsAsync = async () => {
    try {
      const response = await getSettings();

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

  // Get Employees for dropdown
  const getEmployeesForDropdownAsync = async () => {
    try {
      const response = await getEmployeesForDropdown();

      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Employees fetched successfully",
        };
      } else {
        const errorMessage =
          response.data?.message || "Failed to fetch employees";
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error.toString();
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    }
  };

  return {
    loading,
    createEmployee: createEmployeeAsync,
    getEmployees: getEmployeesAsync,
    getEmployeeById: getEmployeeByIdAsync,
    updateEmployee: updateEmployeeAsync,
    deleteEmployee: deleteEmployeeAsync,
    toggleEmployeeStatus: toggleEmployeeStatusAsync,
    getDepartments: getDepartmentsAsync,
    getRoles: getRolesAsync,
    getSalarySettings: getSalarySettingsAsync,
    getSettings: getSettingsAsync,
    getEmployeesForDropdown: getEmployeesForDropdownAsync,
  };
}

export default useEmployeeService;
