import { useState } from "react";
import {
  createClient,
  getClients,
  getClientById,
  updateClient,
  deleteClient,
  toggleClientStatus,
  type ClientFilters,
  type CreateClientData,
  type UpdateClientData,
  type ClientListResponse,
  type ClientResponse,
  type DeleteClientResponse,
} from "../../services/clientService";
import { handleToastError, customizeToast } from "../../utils";

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

  // Create Client
  const createClientAsync = async (data: CreateClientData) => {
    try {
      setLoading(true);
      const response = await createClient(data);

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

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

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

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

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

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Client status updated successfully", "success");
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Client status updated successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to update client 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,
    createClient: createClientAsync,
    getClients: getClientsAsync,
    getClientById: getClientByIdAsync,
    updateClient: updateClientAsync,
    deleteClient: deleteClientAsync,
    toggleClientStatus: toggleClientStatusAsync,
  };
}

export default useClientService;
