import { useState, useEffect } 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 { Input } from '@/components/ui/input';
import { Loader2, Pause } from 'lucide-react';
import { toast } from 'sonner';
import { pauseWorkflow } from '@/services/workflowApi';
import dayjs from 'dayjs';

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

export function PauseModal({ isOpen, onClose, requestId, levelId, onSuccess }: PauseModalProps) {
  const [reason, setReason] = useState('');
  const [resumeDate, setResumeDate] = useState('');
  const [submitting, setSubmitting] = useState(false);

  // Set default resume date to 1 month from now
  const getDefaultResumeDate = () => {
    const maxDate = dayjs().add(1, 'month').format('YYYY-MM-DD');
    return maxDate;
  };

  const getMaxResumeDate = () => {
    return dayjs().add(1, 'month').format('YYYY-MM-DD');
  };

  const getMinResumeDate = () => {
    return dayjs().add(1, 'day').format('YYYY-MM-DD'); // At least 1 day from now
  };

  // Initialize resume date when modal opens
  useEffect(() => {
    if (isOpen && !resumeDate) {
      setResumeDate(getDefaultResumeDate());
    }
  }, [isOpen]);

  const handleSubmit = async () => {
    if (!reason.trim()) {
      toast.error('Please provide a reason for pausing');
      return;
    }

    if (!resumeDate) {
      toast.error('Please select a resume date');
      return;
    }

    const selectedDate = dayjs(resumeDate);
    const maxDate = dayjs().add(1, 'month');
    const minDate = dayjs().add(1, 'day');

    if (selectedDate.isAfter(maxDate)) {
      toast.error('Resume date cannot be more than 1 month from now');
      return;
    }

    if (selectedDate.isBefore(minDate, 'day')) {
      toast.error('Resume date must be at least 1 day from now');
      return;
    }

    try {
      setSubmitting(true);
      await pauseWorkflow(requestId, levelId, reason.trim(), selectedDate.toDate());
      toast.success('Workflow paused successfully');
      
      // Wait for parent to refresh data before closing modal
      // This ensures the UI shows updated pause status
      if (onSuccess) {
        await onSuccess();
      }
      
      setReason('');
      setResumeDate(getDefaultResumeDate());
      onClose();
    } catch (error: any) {
      console.error('Failed to pause workflow:', error);
      toast.error(error?.response?.data?.error || error?.response?.data?.message || 'Failed to pause workflow');
    } finally {
      setSubmitting(false);
    }
  };

  const handleClose = () => {
    if (!submitting) {
      setReason('');
      setResumeDate(getDefaultResumeDate());
      onClose();
    }
  };

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

        <div className="space-y-4 py-4">
          <div className="bg-orange-50 border border-orange-200 rounded-lg p-3">
            <p className="text-sm text-orange-800">
              <strong>Note:</strong> Pausing will temporarily halt TAT calculations and notifications. The workflow will automatically resume on the selected date.
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="pause-reason" className="text-sm font-medium">
              Reason for Pausing <span className="text-red-500">*</span>
            </Label>
            <Textarea
              id="pause-reason"
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder="Enter the reason for pausing this workflow..."
              className="min-h-[100px] text-sm"
              disabled={submitting}
            />
            <p className="text-xs text-gray-500">
              {reason.length} / 1000 characters
            </p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="resume-date" className="text-sm font-medium">
              Resume Date <span className="text-red-500">*</span>
            </Label>
            <Input
              id="resume-date"
              type="date"
              value={resumeDate}
              onChange={(e) => setResumeDate(e.target.value)}
              min={getMinResumeDate()}
              max={getMaxResumeDate()}
              className="text-sm"
              disabled={submitting}
            />
            <p className="text-xs text-gray-500">
              Maximum 1 month from today. The workflow will automatically resume on this date.
            </p>
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={handleClose}
            disabled={submitting}
          >
            Cancel
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={submitting || !reason.trim() || !resumeDate}
            className="bg-orange-600 hover:bg-orange-700 text-white"
          >
            {submitting ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Pausing...
              </>
            ) : (
              <>
                <Pause className="w-4 h-4 mr-2" />
                Pause Workflow
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

