import { useState, useEffect, useCallback, useRef } from 'react';
import itemService from '../services/itemService';
import type { Item, CreateItemData } from '../services/itemService';

export interface ItemFilters {
  item_code?: string;
  item_name?: string;
  item_group?: string;
  custom_hospital_name?: string;
  disabled?: number;
  is_stock_item?: number;
  [key: string]: any;
}

/**
 * Hook to fetch list of items with filters and pagination
 */
export function useItems(
  filters?: ItemFilters,
  limit: number = 20,
  offset: number = 0,
  orderBy?: string
) {
  const [items, setItems] = useState<Item[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [hasMore, setHasMore] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refetchTrigger, setRefetchTrigger] = useState(0);
  const hasAttemptedRef = useRef(false);

  const filtersJson = JSON.stringify(filters);

  useEffect(() => {
    if (hasAttemptedRef.current && error) {
      return;
    }

    let isCancelled = false;
    hasAttemptedRef.current = true;
    
    const fetchItems = async () => {
      try {
        setLoading(true);
        
        const fields = ['name', 'item_code', 'item_name', 'item_group', 'stock_uom', 'disabled', 'is_stock_item','custom_hospital_name', 'opening_stock', 'valuation_rate', 'standard_rate', 'creation', 'modified', 'owner', 'docstatus'];
        const response = await itemService.getItems(filters, fields, limit, offset);
        
        if (!isCancelled) {
          setItems(response.data);
          setTotalCount(response.total);
          setHasMore(response.data.length === limit);
          setError(null);
        }
      } catch (err) {
        if (!isCancelled) {
          const errorMessage = err instanceof Error ? err.message : 'Failed to fetch items';
          setError(errorMessage);
          setItems([]);
          setTotalCount(0);
          setHasMore(false);
        }
      } finally {
        if (!isCancelled) {
          setLoading(false);
        }
      }
    };
    
    fetchItems();
    
    return () => {
      isCancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filtersJson, limit, offset, orderBy, refetchTrigger]);

  const refetch = useCallback(() => {
    hasAttemptedRef.current = false;
    setRefetchTrigger(prev => prev + 1);
  }, []);

  return { items, totalCount, hasMore, loading, error, refetch };
}

/**
 * Hook to fetch a single item by name
 */
export function useItemDetails(itemName: string | null) {
  const [item, setItem] = useState<Item | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchItem = useCallback(async () => {
    if (!itemName) {
      setItem(null);
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      
      const data = await itemService.getItem(itemName);
      setItem(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch item details');
    } finally {
      setLoading(false);
    }
  }, [itemName]);

  useEffect(() => {
    fetchItem();
  }, [fetchItem]);

  const refetch = useCallback(() => {
    fetchItem();
  }, [fetchItem]);

  return { item, loading, error, refetch };
}

/**
 * Hook to manage item operations (create, update, delete)
 */
export function useItemMutations() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const createItem = useCallback(async (data: CreateItemData) => {
    try {
      setLoading(true);
      setError(null);
      const result = await itemService.createItem(data);
      return result;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to create item';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const updateItem = useCallback(async (itemName: string, data: Partial<CreateItemData>) => {
    try {
      setLoading(true);
      setError(null);
      const result = await itemService.updateItem(itemName, data);
      return result;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to update item';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const deleteItem = useCallback(async (itemName: string) => {
    try {
      setLoading(true);
      setError(null);
      await itemService.deleteItem(itemName);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to delete item';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const submitItem = useCallback(async (itemName: string) => {
    try {
      setLoading(true);
      setError(null);
      const result = await itemService.submitItem(itemName);
      return result;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to submit item';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  return { createItem, updateItem, deleteItem, submitItem, loading, error };
}



