import { useState } from "react";
import {
  createVendor,
  getVendors,
  getVendorById,
  updateVendor,
  deleteVendor,
  getVendorTypes,
  createVendorType,
  getProjectsForDropdown,
  type VendorFilters,
  type CreateVendorData,
  type UpdateVendorData,
  type CreateVendorTypeData,
  type VendorListResponse,
  type VendorResponse,
  type DeleteVendorResponse,
  type VendorTypesResponse,
  type ProjectsResponse,
  type VendorTypeResponse,
} from "../../services/vendorService";
import { handleToastError, customizeToast } from "../../utils";

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

  // Create Vendor
  const createVendorAsync = async (data: CreateVendorData) => {
    try {
      setLoading(true);
      const response = await createVendor(data);

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

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

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

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

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        customizeToast("Vendor deleted successfully", "success");
        return {
          success: true,
          data: response.data,
          message:
            response.data?.message || "Vendor deleted successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to delete vendor";
        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 Vendor Types
  const getVendorTypesAsync = async () => {
    try {
      const response = await getVendorTypes();

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

  // Create Vendor Type (Inline)
  const createVendorTypeAsync = async (data: CreateVendorTypeData) => {
    try {
      const response = await createVendorType(data);

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

  // Get Projects for dropdown
  const getProjectsForDropdownAsync = async () => {
    try {
      const response = await getProjectsForDropdown();

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

  return {
    loading,
    createVendor: createVendorAsync,
    getVendors: getVendorsAsync,
    getVendorById: getVendorByIdAsync,
    updateVendor: updateVendorAsync,
    deleteVendor: deleteVendorAsync,
    getVendorTypes: getVendorTypesAsync,
    createVendorType: createVendorTypeAsync,
    getProjectsForDropdown: getProjectsForDropdownAsync,
  };
}

export default useVendorService;
