import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Loader2, AlertCircle } from 'lucide-react';
import { toast } from 'sonner';
import { retriggerPause } from '@/services/workflowApi';

interface RetriggerPauseModalProps {
  isOpen: boolean;
  onClose: () => void;
  requestId: string;
  approverName?: string;
  onSuccess?: () => void | Promise<void>;
}

export function RetriggerPauseModal({ isOpen, onClose, requestId, approverName, onSuccess }: RetriggerPauseModalProps) {
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    try {
      setSubmitting(true);
      await retriggerPause(requestId);
      toast.success('Retrigger request sent to approver');
      
      // Wait for parent to refresh data before closing modal
      if (onSuccess) {
        await onSuccess();
      }
      
      onClose();
    } catch (error: any) {
      console.error('Failed to retrigger pause:', error);
      toast.error(error?.response?.data?.error || error?.response?.data?.message || 'Failed to send retrigger request');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[450px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <AlertCircle className="w-5 h-5 text-orange-600" />
            Request Resume
          </DialogTitle>
        </DialogHeader>

        <div className="py-4">
          <p className="text-sm text-gray-700 mb-4">
            You are requesting the approver{approverName ? ` (${approverName})` : ''} to cancel the pause and resume work on this request.
          </p>
          <div className="bg-orange-50 border border-orange-200 rounded-lg p-3">
            <p className="text-sm text-orange-800">
              A notification will be sent to the approver who paused this workflow, requesting them to resume it.
            </p>
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={onClose}
            disabled={submitting}
          >
            Cancel
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={submitting}
            className="bg-orange-600 hover:bg-orange-700 text-white"
          >
            {submitting ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Sending...
              </>
            ) : (
              <>
                <AlertCircle className="w-4 h-4 mr-2" />
                Send Request
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

