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

export type InspectionRecordDTO = {
  id: string;
  receiving_batch_id: string;
  bar_id?: string | null;
  serial_number: string;
  expected_weight?: number | null;
  actual_weight?: number | null;
  expected_purity_id?: string | null;
  actual_purity_id?: string | null;
  result: string;
  visual_inspection?: string | null;
  weight_inspection?: string | null;
  purity_inspection?: string | null;
  photo_file_id?: string | null;
  difference_weight?: number | null;
  notes?: string | null;
  inspected_by?: string | null;
  approved_by?: string | null;
  inspected_at: string;
  created_at: string;
};

export type InspectionRecordCreateDTO = Omit<InspectionRecordDTO, 'id' | 'result' | 'inspected_by' | 'approved_by' | 'inspected_at' | 'created_at'>;

export const useInspectionsBase = createEntityHook<InspectionRecordDTO, InspectionRecordCreateDTO, never>(
  i18n.t('hooks.useInspections.text_1'),
  ENDPOINTS.INSPECTIONS.LIST,
);

export function useInspections() {
  const base = useInspectionsBase();

  const fetchPendingInspections = useCallback(async () => {
    // We override fetchItems to always append ?result=pending or use filters correctly.
    // The createEntityHook supports filters, so we can just call it with filters.
    await base.fetchItems(base.currentPage, base.pageSize, base.searchTerm, { result: 'pending' });
  }, [base.fetchItems, base.currentPage, base.pageSize, base.searchTerm]);

  const approveInspection = async (id: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.INSPECTIONS.APPROVE(id));
      if (res.success) {
        await fetchPendingInspections();
        return true;
      }
      return false;
    } catch (err: any) {
      base.setError(err.message);
      return false;
    } finally {
      base.setIsLoading(false);
    }
  };

  const rejectInspection = async (id: string, reason: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.INSPECTIONS.REJECT(id) + `?reason=${encodeURIComponent(reason)}`);
      if (res.success) {
        await fetchPendingInspections();
        return true;
      }
      return false;
    } catch (err: any) {
      base.setError(err.message);
      return false;
    } finally {
      base.setIsLoading(false);
    }
  };

  return {
    ...base,
    fetchPendingInspections,
    approveInspection,
    rejectInspection,
  };
}
