/**
 * InitiatorActionModal Component
 * Modal for Initiator to take action on a returned/rejected request
 * Actions: Reopen, Request Revised Quotation, Cancel
 */

import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { 
  RefreshCw, 
  MessageSquare, 
  FileEdit, 
  XOctagon, 
  AlertTriangle,
  Loader2
} from 'lucide-react';
import { toast } from 'sonner';

interface InitiatorActionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAction: (action: 'REOPEN' | 'REVISE' | 'CANCEL', comments: string) => Promise<void>;
  requestTitle?: string;
  requestId?: string;
  defaultAction?: 'REOPEN' | 'REVISE' | 'CANCEL';
}

export function InitiatorActionModal({
  isOpen,
  onClose,
  onAction,
  requestTitle = 'Request',
  requestId: _requestId,
  defaultAction,
}: InitiatorActionModalProps) {
  const [comments, setComments] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [selectedAction, setSelectedAction] = useState<'REOPEN' | 'REVISE' | 'CANCEL' | null>(defaultAction || null);
  
  // Update selectedAction when defaultAction changes
  useEffect(() => {
    if (defaultAction) {
      setSelectedAction(defaultAction);
    }
  }, [defaultAction]);

  const actions = [
    {
      id: 'REOPEN',
      label: 'Reopen & Resubmit',
      description: 'Resubmit the request to the department head for approval.',
      icon: <RefreshCw className="w-5 h-5 text-blue-600" />,
      color: 'blue',
      variant: 'default' as const
    },
    {
      id: 'REVISE',
      label: 'Request Revised Quotation',
      description: 'Ask dealer to submit a new proposal/quotation.',
      icon: <FileEdit className="w-5 h-5 text-amber-600" />,
      color: 'amber',
      variant: 'default' as const
    },
    {
      id: 'CANCEL',
      label: 'Cancel Request',
      description: 'Permanently close and cancel this request.',
      icon: <XOctagon className="w-5 h-5 text-red-600" />,
      color: 'red',
      variant: 'destructive' as const
    }
  ];

  const handleActionClick = (actionId: any) => {
    setSelectedAction(actionId);
  };

  const handleSubmit = async () => {
    if (!selectedAction) {
      toast.error('Please select an action');
      return;
    }

    if (!comments.trim()) {
      toast.error('Please provide a reason or comments for this action');
      return;
    }

    try {
      setSubmitting(true);
      await onAction(selectedAction, comments);
      handleReset();
      onClose();
    } catch (error: any) {
      console.error('Failed to perform initiator action:', error);
      const errorMessage = error?.response?.data?.message || error?.message || 'Action failed. Please try again.';
      toast.error(errorMessage);
    } finally {
      setSubmitting(false);
    }
  };

  const handleReset = () => {
    setComments('');
    setSelectedAction(null);
  };

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

  if (!isOpen) return null;

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle className="text-xl">Action Required: {requestTitle}</DialogTitle>
          <DialogDescription>
            This request has been returned to you. Please select how you would like to proceed.
          </DialogDescription>
        </DialogHeader>

        <div className="py-4 space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {actions.map((action) => (
              <div
                key={action.id}
                onClick={() => handleActionClick(action.id)}
                className={`
                  cursor-pointer p-4 border-2 rounded-xl transition-all duration-200
                  ${selectedAction === action.id 
                    ? `border-${action.color}-600 bg-${action.color}-50 shadow-sm` 
                    : 'border-gray-100 hover:border-gray-200 hover:bg-gray-50'}
                `}
              >
                <div className="flex items-center gap-3 mb-2">
                  <div className={`p-2 rounded-lg bg-white border border-gray-100`}>
                    {action.icon}
                  </div>
                  <h4 className="font-bold text-sm text-gray-900">{action.label}</h4>
                </div>
                <p className="text-xs text-gray-500 leading-relaxed">
                  {action.description}
                </p>
              </div>
            ))}
          </div>

          <div className="space-y-2">
            <h3 className="text-sm font-semibold text-gray-900 flex items-center gap-2">
              <MessageSquare className="w-4 h-4 text-gray-500" />
              Comments / Reason
            </h3>
            <Textarea
              placeholder="Provide a detailed reason for your decision..."
              value={comments}
              onChange={(e) => setComments(e.target.value)}
              className="min-h-[120px] text-sm resize-none"
            />
          </div>

          {selectedAction === 'CANCEL' && (
            <div className="p-3 bg-red-50 border border-red-100 rounded-lg flex items-start gap-3">
              <AlertTriangle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
              <div className="text-xs text-red-800">
                <p className="font-bold mb-1">Warning: Irreversible Action</p>
                <p>Cancelling this request will permanently close it. This action cannot be undone.</p>
              </div>
            </div>
          )}
        </div>

        <DialogFooter className="border-t pt-4">
          <Button
            variant="outline"
            onClick={handleClose}
            disabled={submitting}
          >
            Cancel
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={!selectedAction || !comments.trim() || submitting}
            className={`
              min-w-[120px]
              ${selectedAction === 'CANCEL' ? 'bg-red-600 hover:bg-red-700' : 'bg-purple-600 hover:bg-purple-700'}
            `}
          >
            {submitting ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Processing...
              </>
            ) : (
              'Confirm Action'
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
