import React, { useState } from 'react';
import { useWorkflow } from '../hooks/useWorkflow.ts';
import type { WorkflowTransition } from '../services/workflowService';
import { FaSpinner, FaExclamationTriangle, FaInfoCircle } from 'react-icons/fa';

interface WorkflowActionsProps {
  doctype: string;
  docname: string | null;
  workflowState?: string;
  onActionComplete?: (action: string, success: boolean) => void;
  onStateChange?: () => void;
  showStateInfo?: boolean;
  className?: string;
}

const WorkflowActions: React.FC<WorkflowActionsProps> = ({
  doctype,
  docname,
  workflowState,
  onActionComplete,
  onStateChange,
  showStateInfo = true,
  className = '',
}) => {
  const {
    transitions,
    loading,
    actionLoading,
    error,
    applyAction,
    getStateStyle,
    getButtonStyle,
    getIcon,
  } = useWorkflow({
    doctype,
    docname,
    workflowState,
    enabled: !!docname,
  });

  const [confirmAction, setConfirmAction] = useState<string | null>(null);

  // Actions that require confirmation
  const actionsRequiringConfirmation = ['Reject', 'Cancel', 'Close'];

  const handleActionClick = async (action: string) => {
    // Check if action requires confirmation
    if (actionsRequiringConfirmation.includes(action) && confirmAction !== action) {
      setConfirmAction(action);
      return;
    }

    setConfirmAction(null);

    const success = await applyAction(action);
    
    if (onActionComplete) {
      onActionComplete(action, success);
    }
    
    if (success && onStateChange) {
      onStateChange();
    }
  };

  const handleCancelConfirm = () => {
    setConfirmAction(null);
  };

  if (!docname) {
    return null;
  }

  const stateStyle = workflowState ? getStateStyle(workflowState) : getStateStyle('Draft');

  return (
    <div className={`space-y-4 ${className}`}>
      {/* Current State Display */}
      {showStateInfo && workflowState && (
        <div className={`p-4 rounded-lg border ${stateStyle.bg} ${stateStyle.border}`}>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Workflow State</p>
              <p className={`text-lg font-semibold ${stateStyle.text}`}>
                {workflowState}
              </p>
            </div>
            <div className={`w-3 h-3 rounded-full ${stateStyle.bg.replace('100', '500').replace('900/30', '500')}`} />
          </div>
        </div>
      )}

      {/* Loading State */}
      {loading && (
        <div className="flex items-center gap-2 text-gray-500 dark:text-gray-400">
          <FaSpinner className="animate-spin" />
          <span className="text-sm">Loading workflow actions...</span>
        </div>
      )}

      {/* Error Message */}
      {error && (
        <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
          <div className="flex items-start gap-2">
            <FaExclamationTriangle className="text-red-500 mt-0.5" />
            <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
          </div>
        </div>
      )}

      {/* Confirmation Dialog */}
      {confirmAction && (
        <div className="p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
          <div className="flex items-start gap-2 mb-3">
            <FaExclamationTriangle className="text-yellow-500 mt-0.5" />
            <div>
              <p className="text-sm font-medium text-yellow-800 dark:text-yellow-200">
                Confirm Action
              </p>
              <p className="text-xs text-yellow-600 dark:text-yellow-400 mt-1">
                Are you sure you want to <strong>{confirmAction}</strong> this work order?
              </p>
            </div>
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => handleActionClick(confirmAction)}
              disabled={actionLoading}
              className="px-3 py-1.5 bg-red-600 hover:bg-red-700 text-white text-sm rounded-md disabled:opacity-50"
            >
              {actionLoading ? (
                <span className="flex items-center gap-1">
                  <FaSpinner className="animate-spin" size={12} />
                  Processing...
                </span>
              ) : (
                `Yes, ${confirmAction}`
              )}
            </button>
            <button
              onClick={handleCancelConfirm}
              disabled={actionLoading}
              className="px-3 py-1.5 bg-gray-300 hover:bg-gray-400 text-gray-700 text-sm rounded-md disabled:opacity-50"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* Available Actions */}
      {!loading && transitions.length > 0 && !confirmAction && (
        <div className="space-y-2">
          <p className="text-xs font-medium text-gray-500 dark:text-gray-400 flex items-center gap-1">
            <FaInfoCircle size={12} />
            Available Actions
          </p>
          <div className="flex flex-wrap gap-2">
            {transitions.map((transition: WorkflowTransition, index: number) => (
              <button
                key={`${transition.action}-${index}`}
                onClick={() => handleActionClick(transition.action)}
                disabled={actionLoading}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 flex items-center gap-2 ${getButtonStyle(transition.action)}`}
                title={`Move to: ${transition.next_state}`}
              >
                {actionLoading ? (
                  <FaSpinner className="animate-spin" size={14} />
                ) : (
                  <span>{getIcon(transition.action)}</span>
                )}
                {transition.action}
              </button>
            ))}
          </div>
          
          {/* Show next states info */}
          <div className="mt-2 text-xs text-gray-500 dark:text-gray-400">
            {transitions.map((t: WorkflowTransition, i: number) => (
              <span key={i} className="inline-block mr-3">
                {t.action} → <span className="font-medium">{t.next_state}</span>
              </span>
            ))}
          </div>
        </div>
      )}

      {/* No Actions Available */}
      {!loading && transitions.length === 0 && docname && (
        <div className="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
          <p className="text-sm text-gray-500 dark:text-gray-400 text-center">
            No workflow actions available for your role
          </p>
        </div>
      )}
    </div>
  );
};

export default WorkflowActions;