import { Dispatch, SetStateAction, useCallback } from 'react';
import { toast } from 'sonner';
import { onboardingService } from '@/services/onboarding.service';

interface UseApplicationDetailsLocalActionsParams {
  application: any;
  applicationId: string;
  tempFirmType: string;
  setUpdatingFirmType: Dispatch<SetStateAction<boolean>>;
  setShowFirmTypeModal: Dispatch<SetStateAction<boolean>>;
  setStatutoryForm: Dispatch<SetStateAction<any>>;
  setIsEditingStatutory: Dispatch<SetStateAction<boolean>>;
  setIsSavingStatutory: Dispatch<SetStateAction<boolean>>;
  statutoryForm: any;
  setFddAgencies: Dispatch<SetStateAction<any[]>>;
  selectedAgencyId: string;
  setIsAssigningAgency: Dispatch<SetStateAction<boolean>>;
  fetchApplication: (silent?: boolean) => Promise<void>;
}

export function useApplicationDetailsLocalActions({
  application,
  applicationId,
  tempFirmType,
  setUpdatingFirmType,
  setShowFirmTypeModal,
  setStatutoryForm,
  setIsEditingStatutory,
  setIsSavingStatutory,
  statutoryForm,
  setFddAgencies,
  selectedAgencyId,
  setIsAssigningAgency,
  fetchApplication,
}: UseApplicationDetailsLocalActionsParams) {
  const handleUpdateFirmType = async () => {
    try {
      setUpdatingFirmType(true);
      await onboardingService.updateApplication(applicationId, { constitutionType: tempFirmType });
      toast.success('Firm type updated successfully');
      setShowFirmTypeModal(false);
      await fetchApplication();
    } catch {
      toast.error('Failed to update firm type');
    } finally {
      setUpdatingFirmType(false);
    }
  };

  const handleEditStatutory = () => {
    if (!application) return;
    setStatutoryForm({
      accountHolderName: application.accountHolderName || '',
      panNumber: application.panNumber || '',
      gstNumber: application.gstNumber || '',
      bankName: application.bankName || '',
      accountNumber: application.accountNumber || '',
      ifscCode: application.ifscCode || '',
      registeredAddress: application.registeredAddress || '',
    });
    setIsEditingStatutory(true);
  };

  const handleSaveStatutory = async () => {
    try {
      setIsSavingStatutory(true);
      await onboardingService.updateApplication(applicationId, statutoryForm);
      toast.success('Statutory & Bank details updated successfully');
      setIsEditingStatutory(false);
      await fetchApplication(true);
    } catch {
      toast.error('Failed to update details');
    } finally {
      setIsSavingStatutory(false);
    }
  };

  const fetchFddAgencies = useCallback(async () => {
    try {
      const agencies = await onboardingService.getUsers({ roleCode: 'FDD' });
      setFddAgencies(Array.isArray(agencies) ? agencies : []);
    } catch {
      setFddAgencies([]);
    }
  }, [setFddAgencies]);

  const handleAssignAgency = async () => {
    if (!selectedAgencyId) {
      toast.warning('Please select an agency');
      return;
    }
    try {
      setIsAssigningAgency(true);
      await onboardingService.assignFddAgency({
        applicationId: application?.id || applicationId,
        assignedToAgency: selectedAgencyId,
      });
      await onboardingService.addParticipant({
        requestId: application?.id || applicationId,
        requestType: 'application',
        userId: selectedAgencyId,
        participantType: 'contributor',
      });
      toast.success('FDD Agency assigned and added as participant');
      await fetchApplication();
    } catch {
      toast.error('Failed to assign agency');
    } finally {
      setIsAssigningAgency(false);
    }
  };

  return {
    handleUpdateFirmType,
    handleEditStatutory,
    handleSaveStatutory,
    fetchFddAgencies,
    handleAssignAgency,
  };
}

