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 BarDTO = {
  id: string;
  bar_code: string;
  serial_number: string;
  metal_type: string;
  purity_id: string;
  weight: number;
  source_type: string;
  supplier_id?: string | null;
  purchase_order_id?: string | null;
  receiving_batch_id?: string | null;
  product_id?: string | null;
  current_vault_id?: string | null;
  current_branch_id?: string | null;
  current_owner_type: string;
  current_owner_id?: string | null;
  status: string;
  cost_basis?: number | null;
  inspection_status?: string | null;
  block_reason?: string | null;
  notes?: string | null;
  created_by?: string | null;
  created_at: string;
  updated_at: string;
};

export type BarCreateDTO = Omit<BarDTO, 'id' | 'status' | 'inspection_status' | 'block_reason' | 'created_by' | 'created_at' | 'updated_at'>;
export type BarUpdateDTO = Partial<BarCreateDTO> & { block_reason?: string | null };

export const useBarsBase = createEntityHook<BarDTO, BarCreateDTO, BarUpdateDTO>(
  i18n.t('hooks.useBars.text_1'),
  ENDPOINTS.BARS.LIST,
);

export function useBars() {
  const base = useBarsBase();
  const [barHistory, setBarHistory] = useState<any[]>([]);
  const [isHistoryLoading, setIsHistoryLoading] = useState(false);

  const fetchBarHistory = useCallback(async (id: string) => {
    setIsHistoryLoading(true);
    try {
      const logsRes = await api.get(`/audit/logs?entity_type=bar&entity_id=${id}`);
      setBarHistory((logsRes as any)?.data?.items || (logsRes as any)?.items || logsRes || []);
    } catch (err) {
      console.error("Failed to fetch bar history:", err);
      setBarHistory([]);
    } finally {
      setIsHistoryLoading(false);
    }
  }, []);

  const reserveBar = useCallback(async (id: string, reason?: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const query = reason ? `?reason=${encodeURIComponent(reason)}` : '';
      const res = await api.post(ENDPOINTS.BARS.RESERVE(id) + query);
      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 releaseBar = useCallback(async (id: string, reason?: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const query = reason ? `?reason=${encodeURIComponent(reason)}` : '';
      const res = await api.post(ENDPOINTS.BARS.RELEASE(id) + query);
      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 blockBar = useCallback(async (id: string, reason: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.BARS.BLOCK(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,
    reserveBar,
    releaseBar,
    blockBar,
    barHistory,
    isHistoryLoading,
    fetchBarHistory,
  };
}
