import { useState } from 'react';
import { AlertTriangle, Check, X } from 'lucide-react';
import { api } from '@/api/client';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';

interface Props {
  toolCallId: string;
  toolName: string;
  toolArgs: Record<string, unknown>;
  chatId: string;
  open: boolean;
  onClose: () => void;
}

function parseServerName(toolName: string): string {
  // Tool name format is <serverName>_<originalToolName>
  const idx = toolName.indexOf('_');
  if (idx === -1) return toolName;
  return toolName.slice(0, idx);
}

function parseToolShortName(toolName: string): string {
  const idx = toolName.indexOf('_');
  if (idx === -1) return toolName;
  return toolName.slice(idx + 1);
}

function summarizeArgs(args: Record<string, unknown>): string {
  const keys = Object.keys(args);
  if (keys.length === 0) return 'no arguments';
  const first = keys[0]!;
  const val = typeof args[first] === 'string' ? args[first] as string : JSON.stringify(args[first]);
  return `${first}: ${val.length > 60 ? val.slice(0, 59) + '…' : val}`;
}

export function McpPermissionDialog({ toolCallId, toolName, toolArgs, chatId, open, onClose }: Props) {
  const [loading, setLoading] = useState<string | null>(null);

  const serverName = parseServerName(toolName);
  const shortName = parseToolShortName(toolName);
  const argsSummary = summarizeArgs(toolArgs);

  const handleApprove = async (permission: 'allow_once' | 'allow_always' | 'deny') => {
    setLoading(permission);
    try {
      await api.chats.mcpApprove(chatId, toolCallId, permission);
      onClose();
    } catch {
      // Error is already surfaced by api client
    } finally {
      setLoading(null);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(open) => { if (!open) onClose(); }}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <AlertTriangle className="size-4 text-amber-500" />
            MCP Tool Approval
          </DialogTitle>
        </DialogHeader>
        <div className="space-y-3">
          <div className="rounded-lg bg-muted/50 p-3 text-xs space-y-1.5">
            <div>
              <span className="text-muted-foreground">Server:</span>{' '}
              <span className="font-mono font-medium">{serverName}</span>
            </div>
            <div>
              <span className="text-muted-foreground">Tool:</span>{' '}
              <span className="font-mono">{shortName}</span>
            </div>
            <div>
              <span className="text-muted-foreground">Args:</span>{' '}
              <span className="font-mono text-muted-foreground">{argsSummary}</span>
            </div>
          </div>
          <p className="text-xs text-muted-foreground">
            This MCP server requires approval before running tools. Choose how to proceed:
          </p>
        </div>
        <div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
          <Button
            variant="outline"
            size="sm"
            onClick={() => handleApprove('allow_once')}
            disabled={loading !== null}
          >
            {loading === 'allow_once' ? '…' : <><Check className="size-3 mr-1" /> Allow Once</>}
          </Button>
          <Button
            variant="default"
            size="sm"
            onClick={() => handleApprove('allow_always')}
            disabled={loading !== null}
          >
            {loading === 'allow_always' ? '…' : <><Check className="size-3 mr-1" /> Always Allow</>}
          </Button>
          <Button
            variant="destructive"
            size="sm"
            onClick={() => handleApprove('deny')}
            disabled={loading !== null}
          >
            {loading === 'deny' ? '…' : <><X className="size-3 mr-1" /> Deny</>}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
