import { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Loader2, Play } from 'lucide-react';
import { toast } from 'sonner';
import { resumeWorkflow } from '@/services/workflowApi';

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

export function ResumeModal({ isOpen, onClose, requestId, onSuccess }: ResumeModalProps) {
  const [notes, setNotes] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    try {
      setSubmitting(true);
      await resumeWorkflow(requestId, notes.trim() || undefined);
      toast.success('Workflow resumed successfully');
      
      // Wait for parent to refresh data before closing modal
      if (onSuccess) {
        await onSuccess();
      }
      
      setNotes('');
      onClose();
    } catch (error: any) {
      console.error('Failed to resume workflow:', error);
      toast.error(error?.response?.data?.error || error?.response?.data?.message || 'Failed to resume workflow');
    } finally {
      setSubmitting(false);
    }
  };

  const handleClose = () => {
    if (!submitting) {
      setNotes('');
      onClose();
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Play className="w-5 h-5 text-green-600" />
            Resume Workflow
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div className="bg-green-50 border border-green-200 rounded-lg p-3">
            <p className="text-sm text-green-800">
              <strong>Note:</strong> Resuming will restart TAT calculations and notifications. The workflow will continue from where it was paused.
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="resume-notes" className="text-sm font-medium">
              Notes (Optional)
            </Label>
            <Textarea
              id="resume-notes"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="Add any notes about why you're resuming this workflow..."
              className="min-h-[100px] text-sm"
              disabled={submitting}
            />
            <p className="text-xs text-gray-500">
              {notes.length} / 1000 characters
            </p>
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={handleClose}
            disabled={submitting}
          >
            Cancel
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={submitting}
            className="bg-green-600 hover:bg-green-700 text-white"
          >
            {submitting ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Resuming...
              </>
            ) : (
              <>
                <Play className="w-4 h-4 mr-2" />
                Resume Workflow
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

