import { useState } from "react";
import {
  createCompany,
  getCompanies,
  getCompanyById,
  updateCompany,
  deleteCompany,
  toggleCompanyStatus,
  type CompanyFilters,
  type CreateCompanyData,
  type UpdateCompanyData,
  type CompanyListResponse,
  type CompanyResponse,
  type DeleteCompanyResponse,
} from "../../services/companyService";
import { handleToastError, customizeToast } from "../../utils";

// Helper function to extract error message from various error response structures
const getErrorMessage = (error: any, defaultMessage: string): string => {
  if (!error) return defaultMessage;

  const errorData = error?.response?.data || error?.data || error;

  // Check for validation errors array (422)
  if (
    errorData?.errors &&
    Array.isArray(errorData.errors) &&
    errorData.errors.length > 0
  ) {
    const firstError = errorData.errors[0];
    return (
      firstError?.message || firstError?.msg || firstError || defaultMessage
    );
  }

  // Check for nested error object
  if (errorData?.error) {
    if (typeof errorData.error === "string") {
      return errorData.error;
    }
    if (errorData.error?.message) {
      return errorData.error.message;
    }
  }

  // Check for message field (multiple possible locations)
  if (errorData?.message) {
    return errorData.message;
  }

  // Check for error string
  if (typeof errorData === "string") {
    return errorData;
  }

  // Check for statusText
  if (error?.response?.statusText) {
    return error.response.statusText;
  }

  // Fallback to error message or default
  return error?.message || defaultMessage;
};

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

  // Create Company
  const createCompanyAsync = async (data: CreateCompanyData) => {
    try {
      setLoading(true);
      // Debug: Log the data being sent
      console.log("Creating Company with data:", JSON.stringify(data, null, 2));
      const response = await createCompany(data);

      // Debug logging
      console.log("Create Company Response:", response);
      console.log("Response Data:", response?.data);

      // Check if the response indicates success
      if (
        response?.data?.success === true ||
        response?.data?.success === undefined
      ) {
        customizeToast("Company created successfully", "success");
        return {
          success: true,
          data: response?.data,
          message: response.data?.message || "Company created successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response?.data?.message || "Failed to create company";
        console.error("API Error Response:", response?.data);
        customizeToast(errorMessage, "danger");
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);

      // Handle network errors or other exceptions
      const errorMessage = getErrorMessage(
        error,
        "Failed to create company. Please check all fields and try again."
      );
      customizeToast(errorMessage, "danger");
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  // Get Companies
  const getCompaniesAsync = async (filters?: CompanyFilters) => {
    try {
      setLoading(true);
      const response = await getCompanies(filters);

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

  // Get Company by ID
  const getCompanyByIdAsync = async (id: string) => {
    try {
      setLoading(true);
      const response = await getCompanyById(id);

      // Check if the response indicates success
      if (response?.data?.success !== false) {
        return {
          success: true,
          data: response.data,
          message: response.data?.message || "Company fetched successfully",
        };
      } else {
        // Backend returned success: false, show the backend error message
        const errorMessage =
          response.data?.message || "Failed to fetch company";
        customizeToast(errorMessage, "danger");
        return {
          success: false,
          data: null,
          message: errorMessage,
        };
      }
    } catch (error: any) {
      setLoading(false);
      // Handle network errors or other exceptions
      const errorMessage = getErrorMessage(
        error,
        "Failed to update company. Please check all fields and try again."
      );
      customizeToast(errorMessage, "danger");
      return {
        success: false,
        data: null,
        message: errorMessage,
      };
    } finally {
      setLoading(false);
    }
  };

  // Update Company
  const updateCompanyAsync = async (data: UpdateCompanyData) => {
    try {
      setLoading(true);
      const response = await updateCompany(data);

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

  // Delete Company
  const deleteCompanyAsync = async (id: string) => {
    try {
      setLoading(true);
      const response = await deleteCompany(id);

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

  // Toggle Company Status
  const toggleCompanyStatusAsync = async (id: string) => {
    try {
      setLoading(true);
      const response = await toggleCompanyStatus(id);

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

  return {
    loading,
    createCompany: createCompanyAsync,
    getCompanies: getCompaniesAsync,
    getCompanyById: getCompanyByIdAsync,
    updateCompany: updateCompanyAsync,
    deleteCompany: deleteCompanyAsync,
    toggleCompanyStatus: toggleCompanyStatusAsync,
  };
}

export default useCompanyService;
