import React, { useState } from 'react';
import { FlaskConical, Plus, Trash2, Send, X } from 'lucide-react';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import axios from 'axios';

const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];

const methodColor: Record<string, string> = {
    GET:    'text-emerald-600 dark:text-emerald-400',
    POST:   'text-blue-600 dark:text-blue-400',
    PUT:    'text-amber-600 dark:text-amber-400',
    PATCH:  'text-violet-600 dark:text-violet-400',
    DELETE: 'text-rose-600 dark:text-rose-400',
};

const statusColor = (s: number) =>
    s >= 500 ? 'text-rose-500' : s >= 400 ? 'text-amber-500' : s >= 200 ? 'text-emerald-500' : 'text-muted-foreground';

export function ApiTestModal({ conn }: { conn: any }) {
    const [open, setOpen]       = useState(false);
    const [method, setMethod]   = useState('GET');
    const [url, setUrl]         = useState('');
    const [body, setBody]       = useState('');
    const [headers, setHeaders] = useState<{ key: string; value: string }[]>([]);
    const [response, setResponse] = useState<any>(null);
    const [loading, setLoading]   = useState(false);
    const [error, setError]       = useState('');

    const urls: string[] = conn.enterprise_data?.urls
        ? Object.values(conn.enterprise_data.urls).filter(Boolean) as string[]
        : [];

    const addHeader = () => setHeaders(h => [...h, { key: '', value: '' }]);
    const removeHeader = (i: number) => setHeaders(h => h.filter((_, idx) => idx !== i));
    const updateHeader = (i: number, field: 'key' | 'value', val: string) =>
        setHeaders(h => h.map((row, idx) => idx === i ? { ...row, [field]: val } : row));

    const run = async () => {
        if (!url) return;
        setLoading(true);
        setError('');
        setResponse(null);
        try {
            const headersMap = Object.fromEntries(headers.filter(h => h.key).map(h => [h.key, h.value]));
            const { data } = await axios.post(`/conexoes/${conn.id}/api-test`, {
                method_type:    method,
                url,
                body:           body || null,
                headers_extra:  headersMap,
            });
            setResponse(data);
        } catch (e: any) {
            setError(e.response?.data?.error ?? e.message);
        } finally {
            setLoading(false);
        }
    };

    const bodyStr = response?.body
        ? typeof response.body === 'string'
            ? response.body
            : JSON.stringify(response.body, null, 2)
        : '';

    return (
        <>
            <Tooltip>
                <TooltipTrigger asChild>
                    <button
                        onClick={() => setOpen(true)}
                        className="bg-violet-50 dark:bg-violet-950 rounded-lg p-1.5 flex items-center hover:bg-violet-100 dark:hover:bg-violet-900 transition-colors cursor-pointer"
                    >
                        <FlaskConical size={15} className="text-violet-600 dark:text-violet-400" strokeWidth={2.2} />
                    </button>
                </TooltipTrigger>
                <TooltipContent>Testar API — {conn.name}</TooltipContent>
            </Tooltip>

            <Dialog open={open} onOpenChange={setOpen}>
                <DialogContent className="bg-card border border-border rounded-2xl shadow-sm p-0 overflow-hidden sm:max-w-3xl">
                    <DialogHeader className="flex flex-row items-center gap-2.5 px-6 py-4 border-b border-border">
                        <span className="bg-violet-50 dark:bg-violet-950 rounded-lg p-1.5 flex items-center">
                            <FlaskConical size={15} className="text-violet-600 dark:text-violet-400" strokeWidth={2.2} />
                        </span>
                        <DialogTitle className="text-sm font-semibold text-foreground tracking-tight">
                            API Test — {conn.name}
                            <span className="ml-2 text-[10px] font-normal text-muted-foreground">
                                {conn.enterprise_data?.name}
                            </span>
                        </DialogTitle>
                    </DialogHeader>

                    <div className="px-6 py-5 flex flex-col gap-4 max-h-[75vh] overflow-y-auto">

                        {/* URL bar */}
                        <div className="flex items-center gap-2">
                            <select
                                value={method}
                                onChange={e => setMethod(e.target.value)}
                                className={`h-9 rounded-lg border border-border bg-background px-2 text-xs font-semibold focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/40 ${methodColor[method]}`}
                            >
                                {METHODS.map(m => <option key={m} value={m}>{m}</option>)}
                            </select>
                            <Input
                                value={url}
                                onChange={e => setUrl(e.target.value)}
                                placeholder="https://..."
                                className="h-9 text-xs font-mono flex-1"
                                onKeyDown={e => e.key === 'Enter' && run()}
                            />
                            <button
                                onClick={run}
                                disabled={loading || !url}
                                className="inline-flex items-center gap-1.5 h-9 px-4 rounded-lg bg-primary text-primary-foreground text-xs font-semibold hover:bg-primary/90 transition-colors disabled:opacity-50"
                            >
                                <Send size={12} strokeWidth={2.2} />
                                {loading ? 'Enviando...' : 'Enviar'}
                            </button>
                        </div>

                        {/* URL sugerida */}
                        {urls.length > 0 && (
                            <div className="flex items-center gap-1.5 flex-wrap">
                                <span className="text-[10px] text-muted-foreground uppercase tracking-widest">URLs:</span>
                                {urls.map((u, i) => (
                                    <button key={i} onClick={() => setUrl(u as string)}
                                        className="text-[11px] font-mono text-blue-500 hover:underline truncate max-w-[260px]">
                                        {u as string}
                                    </button>
                                ))}
                            </div>
                        )}

                        {/* Headers */}
                        <div>
                            <div className="flex items-center justify-between mb-2">
                                <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">Headers</span>
                                <button onClick={addHeader} className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors">
                                    <Plus size={11} /> Adicionar
                                </button>
                            </div>
                            {headers.length === 0 && (
                                <p className="text-[11px] text-muted-foreground italic">Nenhum header adicional</p>
                            )}
                            <div className="flex flex-col gap-1.5">
                                {headers.map((h, i) => (
                                    <div key={i} className="flex items-center gap-2">
                                        <Input value={h.key}   onChange={e => updateHeader(i, 'key',   e.target.value)} placeholder="Header" className="h-8 text-xs font-mono w-40" />
                                        <Input value={h.value} onChange={e => updateHeader(i, 'value', e.target.value)} placeholder="Valor"  className="h-8 text-xs font-mono flex-1" />
                                        <button onClick={() => removeHeader(i)} className="text-muted-foreground hover:text-rose-500 transition-colors">
                                            <X size={13} />
                                        </button>
                                    </div>
                                ))}
                            </div>
                        </div>

                        {/* Body */}
                        {['POST', 'PUT', 'PATCH'].includes(method) && (
                            <div>
                                <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground block mb-2">Body (JSON)</span>
                                <textarea
                                    value={body}
                                    onChange={e => setBody(e.target.value)}
                                    placeholder={'{\n  \n}'}
                                    rows={5}
                                    className="w-full rounded-lg border border-border bg-muted px-3 py-2 text-xs font-mono text-foreground resize-y focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/40"
                                />
                            </div>
                        )}

                        {/* Auth info */}
                        <div className="rounded-lg border border-border bg-muted/40 px-3 py-2 text-[11px] text-muted-foreground">
                            <span className="font-semibold">Auth:</span>{' '}
                            {conn.bearer_token
                                ? 'Bearer Token'
                                : conn.login
                                    ? `Basic Auth (${conn.login})`
                                    : 'Sem autenticação configurada'}
                        </div>

                        {/* Erro */}
                        {error && (
                            <div className="rounded-lg border border-rose-200 bg-rose-50 dark:bg-rose-950/30 px-3 py-2 text-xs text-rose-600 dark:text-rose-400 font-mono">
                                {error}
                            </div>
                        )}

                        {/* Resposta */}
                        {response && (
                            <div>
                                <div className="flex items-center gap-2 mb-2">
                                    <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">Resposta</span>
                                    <span className={`text-xs font-bold font-mono ${statusColor(response.status)}`}>
                                        {response.status}
                                    </span>
                                </div>
                                <pre className="rounded-lg border border-border bg-muted px-3 py-3 text-[11px] font-mono text-foreground overflow-x-auto whitespace-pre-wrap max-h-64 overflow-y-auto">
                                    {bodyStr}
                                </pre>
                            </div>
                        )}
                    </div>
                </DialogContent>
            </Dialog>
        </>
    );
}