import { useState, useCallback } from 'react';
import { useSnackbar } from 'notistack';
import { contractsApi } from '@/shared/api/endpoints/hr/contracts';
import type { ContractGenerationRequest, ContractGenerationResponse } from '@/shared/types/contract';

export const useContractGeneration = () => {
  const { enqueueSnackbar } = useSnackbar();
  const [isGenerating, setIsGenerating] = useState(false);
  const [isSendingToDocuSign, setIsSendingToDocuSign] = useState(false);

  const generateContract = useCallback(async (request: ContractGenerationRequest): Promise<ContractGenerationResponse | null> => {
    setIsGenerating(true);
    
    try {
      const response = await contractsApi.generateContract(request);
      enqueueSnackbar('Contrat généré avec succès', { variant: 'success' });
      return response.data;
    } catch (error: any) {
      console.error('Error generating contract:', error);
      enqueueSnackbar('Erreur lors de la génération du contrat', { variant: 'error' });
      return null;
    } finally {
      setIsGenerating(false);
    }
  }, [enqueueSnackbar]);

  const sendToDocuSign = useCallback(async (request: ContractGenerationRequest): Promise<ContractGenerationResponse | null> => {
    setIsSendingToDocuSign(true);
    
    try {
      const response = await contractsApi.sendToDocuSign(request);
      enqueueSnackbar('Contrat envoyé à DocuSign avec succès', { variant: 'success' });
      return response.data;
    } catch (error: any) {
      console.error('Error sending to DocuSign:', error);
      enqueueSnackbar('Erreur lors de l\'envoi à DocuSign', { variant: 'error' });
      return null;
    } finally {
      setIsSendingToDocuSign(false);
    }
  }, [enqueueSnackbar]);

  const downloadContract = useCallback(async (contractId: string): Promise<void> => {
    try {
      const blob = await contractsApi.downloadContract(contractId);
      
      // Create download link
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `contract-${contractId}.html`; // Use .html extension since we're generating HTML
      
      // Trigger download
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      enqueueSnackbar('Contrat téléchargé avec succès', { variant: 'success' });
    } catch (error: any) {
      console.error('Error downloading contract:', error);
      enqueueSnackbar('Erreur lors du téléchargement du contrat', { variant: 'error' });
    }
  }, [enqueueSnackbar]);

  const getContractStatus = useCallback(async (contractId: string): Promise<ContractGenerationResponse | null> => {
    try {
      const response = await contractsApi.getContractStatus(contractId);
      return response.data;
    } catch (error: any) {
      console.error('Error getting contract status:', error);
      enqueueSnackbar('Erreur lors de la récupération du statut', { variant: 'error' });
      return null;
    }
  }, [enqueueSnackbar]);

  return {
    isGenerating,
    isSendingToDocuSign,
    generateContract,
    sendToDocuSign,
    downloadContract,
    getContractStatus,
  };
};
