import { useCallback, useState } from 'react';
import { createEntityHook } from './useEntityBase';
import { api } from '@/lib/api';
import { ENDPOINTS } from '@/constants/endpoints';
import i18n from "@/lib/i18n";

export type StockCountSessionDTO = {
  id: string;
  session_number: string;
  vault_id: string;
  branch_id: string | null;
  status: string;
  scheduled_at: string | null;
  started_at: string | null;
  completed_at: string | null;
  approved_by: string | null;
  approved_at: string | null;
  counted_by: string | null;
  expected_bars: number;
  counted_bars: number;
  variance_bars: number;
  expected_weight: number;
  counted_weight: number;
  variance_weight: number;
  notes: string | null;
  created_at: string;
  updated_at: string;
};

export type StockCountSessionCreateDTO = {
  session_number: string;
  vault_id: string;
  branch_id?: string | null;
  scheduled_at?: string | null;
  notes?: string | null;
};

export type StockCountItemDTO = {
  id: string;
  session_id: string;
  bar_id: string | null;
  serial_number: string | null;
  expected_weight: number | null;
  actual_weight: number | null;
  variance_weight: number | null;
  status: string;
  notes: string | null;
};

export const useStockCountsBase = createEntityHook<StockCountSessionDTO, StockCountSessionCreateDTO, never>(
  i18n.t('hooks.useStockCounts.text_1'),
  ENDPOINTS.STOCK_COUNTS.LIST,
);

export function useStockCounts() {
  const base = useStockCountsBase();

  const [sessionItems, setSessionItems] = useState<StockCountItemDTO[]>([]);

  const fetchSessionItems = useCallback(async (sessionId: string) => {
    try {
      const res = await api.get(ENDPOINTS.STOCK_COUNTS.GET_BY_ID(sessionId) + '/items');
      if (res.success && Array.isArray(res.data)) {
        setSessionItems(res.data);
      } else {
        setSessionItems([]);
      }
    } catch (err) {
      setSessionItems([]);
    }
  }, []);

  const startSession = useCallback(async (id: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.STOCK_COUNTS.START(id));
      if (res.success) {
        await base.fetchItems(base.currentPage, base.pageSize, base.searchTerm);
        return true;
      }
      return false;
    } catch (err: any) {
      base.setError(err.message);
      return false;
    } finally {
      base.setIsLoading(false);
    }
  }, [base]);

  const recordItem = useCallback(async (id: string, payload: { bar_id?: string, serial_number?: string, actual_weight?: number, status?: string, notes?: string }) => {
    try {
      const res = await api.post(ENDPOINTS.STOCK_COUNTS.RECORD_ITEM(id), payload);
      if (res.success) {
        await fetchSessionItems(id);
        await base.fetchItems(base.currentPage, base.pageSize, base.searchTerm); // Refresh to update counters
        return true;
      }
      return false;
    } catch (err: any) {
      base.setError(err.message);
      return false;
    }
  }, [base, fetchSessionItems]);

  const completeSession = useCallback(async (id: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.STOCK_COUNTS.COMPLETE(id));
      if (res.success) {
        await base.fetchItems(base.currentPage, base.pageSize, base.searchTerm);
        return true;
      }
      return false;
    } catch (err: any) {
      base.setError(err.message);
      return false;
    } finally {
      base.setIsLoading(false);
    }
  }, [base]);

  const approveSession = useCallback(async (id: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.STOCK_COUNTS.APPROVE(id));
      if (res.success) {
        await base.fetchItems(base.currentPage, base.pageSize, base.searchTerm);
        return true;
      }
      return false;
    } catch (err: any) {
      base.setError(err.message);
      return false;
    } finally {
      base.setIsLoading(false);
    }
  }, [base]);

  const cancelSession = useCallback(async (id: string, reason: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.STOCK_COUNTS.CANCEL(id) + `?reason=${encodeURIComponent(reason)}`);
      if (res.success) {
        await base.fetchItems(base.currentPage, base.pageSize, base.searchTerm);
        return true;
      }
      return false;
    } catch (err: any) {
      base.setError(err.message);
      return false;
    } finally {
      base.setIsLoading(false);
    }
  }, [base]);

  return {
    ...base,
    sessionItems,
    fetchSessionItems,
    startSession,
    recordItem,
    completeSession,
    approveSession,
    cancelSession,
  };
}
