import { useState } from 'react';
import { ShieldAlert, Check, X, ChevronDown, ChevronUp, ClipboardList, ThumbsUp, ThumbsDown, Play } from 'lucide-react';

// Tool risk levels and descriptions
const TOOL_INFO = {
  Bash: { risk: 'high', description: 'Execute shell commands' },
  Edit: { risk: 'medium', description: 'Modify file contents' },
  Write: { risk: 'medium', description: 'Create or overwrite files' },
  Read: { risk: 'low', description: 'Read file contents' },
  Glob: { risk: 'low', description: 'Search for files by pattern' },
  Grep: { risk: 'low', description: 'Search file contents' },
  Task: { risk: 'low', description: 'Launch sub-agent' },
  WebFetch: { risk: 'low', description: 'Fetch web content' },
  WebSearch: { risk: 'low', description: 'Search the web' },
  TodoWrite: { risk: 'low', description: 'Update task list' },
  NotebookEdit: { risk: 'medium', description: 'Edit Jupyter notebook' },
  ExitPlanMode: { risk: 'low', description: 'Exit plan mode and start implementation' },
  default: { risk: 'medium', description: 'Execute tool' }
};

function getRiskColor(risk) {
  switch (risk) {
    case 'high': return 'text-red-400 bg-red-500/20 border-red-500/30';
    case 'medium': return 'text-yellow-400 bg-yellow-500/20 border-yellow-500/30';
    case 'low': return 'text-green-400 bg-green-500/20 border-green-500/30';
    default: return 'text-dark-400 bg-dark-700 border-dark-600';
  }
}

export function PermissionDialog({ permission, onAllow, onDeny }) {
  const [showDetails, setShowDetails] = useState(false);

  if (!permission) return null;

  const { requestId, toolName, toolInput, blockedPath, isPlanApproval } = permission;
  const toolInfo = TOOL_INFO[toolName] || TOOL_INFO.default;
  const riskColor = getRiskColor(toolInfo.risk);

  // Format tool input for display
  const formatInput = (input) => {
    if (!input) return null;
    try {
      return JSON.stringify(input, null, 2);
    } catch {
      return String(input);
    }
  };

  const inputStr = formatInput(toolInput);

  // Special UI for Plan Approval
  if (isPlanApproval) {
    const launchSwarm = toolInput?.launchSwarm;
    const teammateCount = toolInput?.teammateCount;

    return (
      <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
        <div className="bg-gradient-to-br from-purple-900/50 to-dark-900 border-2 border-purple-500/50 rounded-xl shadow-2xl shadow-purple-500/20 max-w-lg w-full">
          {/* Header */}
          <div className="flex items-center gap-3 p-5 border-b border-purple-500/30 bg-purple-900/20">
            <div className="w-12 h-12 rounded-lg bg-purple-500/30 border border-purple-400/50 flex items-center justify-center">
              <ClipboardList className="w-6 h-6 text-purple-300" />
            </div>
            <div className="flex-1">
              <h3 className="text-lg font-semibold text-purple-200">Plan Review</h3>
              <p className="text-sm text-purple-400/70">Claude has created an implementation plan for your approval</p>
            </div>
          </div>

          {/* Swarm info if applicable */}
          {launchSwarm && (
            <div className="px-5 py-3 bg-indigo-900/20 border-b border-indigo-500/30 flex items-center gap-2">
              <Play className="w-4 h-4 text-indigo-400" />
              <span className="text-sm text-indigo-300">
                This plan will launch a swarm{teammateCount ? ` with ${teammateCount} teammates` : ''}
              </span>
            </div>
          )}

          {/* Content */}
          <div className="p-5">
            <p className="text-sm text-dark-300 mb-4">
              Review the plan in the conversation above. Once approved, Claude will begin implementing the changes.
            </p>

            {/* Show details toggle */}
            {inputStr && (
              <div>
                <button
                  onClick={() => setShowDetails(!showDetails)}
                  className="flex items-center gap-1 text-xs text-purple-400 hover:text-purple-300"
                >
                  {showDetails ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
                  {showDetails ? 'Hide' : 'Show'} tool parameters
                </button>
                {showDetails && (
                  <pre className="mt-2 text-xs bg-dark-800/50 rounded p-2 overflow-auto max-h-32 text-dark-400">
                    {inputStr}
                  </pre>
                )}
              </div>
            )}
          </div>

          {/* Actions */}
          <div className="flex gap-3 p-5 border-t border-purple-500/30">
            <button
              onClick={() => onDeny(requestId)}
              className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-dark-800 hover:bg-dark-700 text-dark-200 rounded-lg font-medium transition-colors border border-dark-600"
            >
              <ThumbsDown className="w-4 h-4" />
              Reject Plan
            </button>
            <button
              onClick={() => onAllow(requestId)}
              className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 hover:bg-green-500 text-white rounded-lg font-medium transition-colors"
            >
              <ThumbsUp className="w-4 h-4" />
              Approve Plan
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Standard permission dialog
  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-dark-900 border border-dark-700 rounded-lg shadow-xl max-w-lg w-full">
        {/* Header */}
        <div className="flex items-center gap-3 p-4 border-b border-dark-700">
          <div className={`p-2 rounded-lg ${riskColor}`}>
            <ShieldAlert className="w-5 h-5" />
          </div>
          <div>
            <h3 className="text-sm font-medium text-dark-100">Permission Required</h3>
            <p className="text-xs text-dark-400">Claude wants to use a tool</p>
          </div>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {/* Tool name and description */}
          <div className="flex items-center justify-between">
            <div>
              <span className="text-sm font-mono text-dark-200">{toolName}</span>
              <p className="text-xs text-dark-500">{toolInfo.description}</p>
            </div>
            <span className={`text-xs px-2 py-0.5 rounded border ${riskColor}`}>
              {toolInfo.risk} risk
            </span>
          </div>

          {/* Blocked path if any */}
          {blockedPath && (
            <div className="text-xs text-dark-400 bg-dark-800 rounded p-2">
              <span className="text-dark-500">Path: </span>
              <code className="text-orange-400">{blockedPath}</code>
            </div>
          )}

          {/* Tool input (collapsible) */}
          {inputStr && (
            <div>
              <button
                onClick={() => setShowDetails(!showDetails)}
                className="flex items-center gap-1 text-xs text-dark-400 hover:text-dark-300"
              >
                {showDetails ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
                {showDetails ? 'Hide' : 'Show'} details
              </button>
              {showDetails && (
                <pre className="mt-2 text-xs bg-dark-800 rounded p-2 overflow-auto max-h-48 text-dark-300">
                  {inputStr}
                </pre>
              )}
            </div>
          )}
        </div>

        {/* Actions */}
        <div className="flex gap-2 p-4 border-t border-dark-700">
          <button
            onClick={() => onDeny(requestId)}
            className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-dark-800 hover:bg-dark-700 text-dark-300 rounded-lg transition-colors"
          >
            <X className="w-4 h-4" />
            Deny
          </button>
          <button
            onClick={() => onAllow(requestId)}
            className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors"
          >
            <Check className="w-4 h-4" />
            Allow
          </button>
        </div>
      </div>
    </div>
  );
}
