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 DeliveryOrderDTO = {
  id: string;
  order_number: string;
  client_user_id: string;
  client_name: string | null;
  delivery_branch_id: string;
  vault_id: string;
  bar_id: string | null;
  custody_id: string | null;
  transfer_order_id: string | null;
  delivery_type: string;
  status: string;
  grams: number;
  otp_code: string | null;
  otp_expires_at: string | null;
  otp_verified_at: string | null;
  identity_document_type: string | null;
  identity_document_number: string | null;
  identity_verified_at: string | null;
  identity_verified_by: string | null;
  prepared_by: string | null;
  prepared_at: string | null;
  handed_over_by: string | null;
  handed_over_at: string | null;
  completed_at: string | null;
  cancelled_at: string | null;
  cancellation_reason: string | null;
  notes: string | null;
  created_at: string;
  updated_at: string;
};

export type DeliveryOrderCreateDTO = {
  order_number?: string | null;
  client_user_id: string;
  delivery_branch_id: string;
  vault_id: string;
  bar_id?: string | null;
  custody_id?: string | null;
  transfer_order_id?: string | null;
  delivery_type?: string;
  grams: number;
  notes?: string | null;
};

export const useDeliveriesBase = createEntityHook<DeliveryOrderDTO, DeliveryOrderCreateDTO, never>(
  i18n.t('hooks.useDeliveries.text_1'),
  ENDPOINTS.DELIVERIES.LIST,
);

export function useDeliveries() {
  const base = useDeliveriesBase();

  const verifyIdentity = useCallback(async (id: string, identity_document_type: string, identity_document_number: string, notes?: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.DELIVERIES.VERIFY_IDENTITY(id), { identity_document_type, identity_document_number, notes });
      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 verifyOtp = useCallback(async (id: string, otp_code: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.DELIVERIES.VERIFY_OTP(id), { otp_code });
      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 prepareDelivery = useCallback(async (id: string, notes?: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.DELIVERIES.PREPARE(id), { notes });
      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 readyForPickup = useCallback(async (id: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.DELIVERIES.READY_FOR_PICKUP(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 handOver = useCallback(async (id: string, notes?: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.DELIVERIES.HAND_OVER(id), { notes });
      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 completeDelivery = useCallback(async (id: string, notes?: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.DELIVERIES.COMPLETE(id), { notes });
      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 addProtocolSignature = useCallback(async (id: string, signatory_role: string, signatory_name: string, signature_data?: string) => {
    base.setIsLoading(true);
    base.setError(null);
    try {
      const res = await api.post(ENDPOINTS.DELIVERIES.SIGNATURES(id), { signatory_role, signatory_name, signature_data });
      if (res.success) {
        return true;
      }
      return false;
    } catch (err: any) {
      base.setError(err.message);
      return false;
    } finally {
      base.setIsLoading(false);
    }
  }, [base]);

  const fetchSignatures = useCallback(async (id: string) => {
    try {
      const res = await api.get(ENDPOINTS.DELIVERIES.SIGNATURES(id));
      return (res as any)?.data || res || [];
    } catch (err) {
      console.error(err);
      return [];
    }
  }, []);

  return {
    ...base,
    verifyIdentity,
    verifyOtp,
    prepareDelivery,
    readyForPickup,
    handOver,
    completeDelivery,
    addProtocolSignature,
    fetchSignatures,
  };
}
