'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useMemo, useCallback } from 'react';
import { Copy, Check, Clock, Database, WarningCircle, Lightning, Bug, Lightbulb } from '@phosphor-icons/react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CodeViewer } from '../code-editor';
// Detect language from content type
function detectLanguage(contentType, body) {
    if (!contentType) return 'plaintext';
    if (contentType.includes('json')) return 'json';
    if (contentType.includes('xml')) return 'xml';
    if (contentType.includes('html')) return 'html';
    if (contentType.includes('javascript')) return 'javascript';
    if (contentType.includes('typescript')) return 'typescript';
    if (contentType.includes('event-stream')) return 'json';
    if (body && body.trim().startsWith('{')) return 'json';
    return 'plaintext';
}
function formatSize(bytes) {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
}
// Format response body - handles both SSE and regular JSON
function formatBody(body, contentType, isSSE) {
    if (!body) return '';
    // Check if this is SSE format
    if (isSSE || body.includes('data: ')) {
        const lines = body.split(/\r?\n/).filter((line)=>line.trim());
        const events = [];
        for (const line of lines){
            if (line.startsWith('data: ')) {
                const data = line.slice(6);
                try {
                    const parsed = JSON.parse(data);
                    events.push(JSON.stringify(parsed, null, 2));
                } catch  {
                    events.push(data);
                }
            } else {
                events.push(line);
            }
        }
        return events.join('\n');
    }
    // Regular JSON - try to parse and format
    if (contentType?.includes('json')) {
        try {
            const parsed = JSON.parse(body);
            return JSON.stringify(parsed, null, 2);
        } catch  {
            return body;
        }
    }
    return body;
}
export function ResponseBodyCard({ meta, body, headers, contentType, isError = false, errorMessage, onDebug, onExplain }) {
    const [copied, setCopied] = useState(false);
    const isSSE = contentType?.includes('event-stream');
    const detectedLanguage = useMemo(()=>detectLanguage(contentType, body), [
        contentType,
        body
    ]);
    const formattedBody = useMemo(()=>formatBody(body, contentType, !!isSSE), [
        body,
        contentType,
        isSSE
    ]);
    const headersCount = Object.keys(headers).length;
    const copyToClipboard = useCallback((text)=>{
        navigator.clipboard.writeText(text);
        setCopied(true);
        setTimeout(()=>setCopied(false), 2000);
    }, []);
    const statusVariant = isError ? 'destructive' : 'default';
    return /*#__PURE__*/ _jsx(TooltipProvider, {
        children: /*#__PURE__*/ _jsxs("div", {
            className: "flex flex-col h-full",
            children: [
                /*#__PURE__*/ _jsxs("div", {
                    className: "sticky top-0 z-10 flex items-center justify-between bg-muted/50 px-4 py-3 border-b border-border",
                    children: [
                        /*#__PURE__*/ _jsxs("div", {
                            className: "flex items-center gap-4 text-sm",
                            children: [
                                /*#__PURE__*/ _jsxs(Badge, {
                                    variant: statusVariant,
                                    className: "font-semibold",
                                    children: [
                                        meta.status,
                                        " ",
                                        meta.statusText
                                    ]
                                }),
                                /*#__PURE__*/ _jsxs("span", {
                                    className: "flex items-center gap-1.5 text-muted-foreground",
                                    children: [
                                        /*#__PURE__*/ _jsx(Clock, {
                                            className: "h-4 w-4",
                                            weight: "bold"
                                        }),
                                        /*#__PURE__*/ _jsxs("span", {
                                            children: [
                                                meta.responseTime,
                                                "ms"
                                            ]
                                        })
                                    ]
                                }),
                                /*#__PURE__*/ _jsxs("span", {
                                    className: "flex items-center gap-1.5 text-muted-foreground",
                                    children: [
                                        /*#__PURE__*/ _jsx(Database, {
                                            className: "h-4 w-4",
                                            weight: "bold"
                                        }),
                                        /*#__PURE__*/ _jsx("span", {
                                            children: formatSize(meta.size)
                                        })
                                    ]
                                }),
                                meta.isStreaming && /*#__PURE__*/ _jsxs("span", {
                                    className: "flex items-center gap-1.5 text-amber-600 dark:text-amber-400",
                                    children: [
                                        /*#__PURE__*/ _jsx(Lightning, {
                                            className: "h-4 w-4 animate-pulse",
                                            weight: "fill"
                                        }),
                                        /*#__PURE__*/ _jsx("span", {
                                            children: "SSE"
                                        })
                                    ]
                                })
                            ]
                        }),
                        /*#__PURE__*/ _jsxs("div", {
                            className: "flex items-center gap-2",
                            children: [
                                errorMessage && /*#__PURE__*/ _jsxs("span", {
                                    className: "flex items-center gap-1.5 text-red-500 text-sm",
                                    children: [
                                        /*#__PURE__*/ _jsx(WarningCircle, {
                                            className: "h-4 w-4",
                                            weight: "fill"
                                        }),
                                        "Error"
                                    ]
                                }),
                                formattedBody && /*#__PURE__*/ _jsxs(Tooltip, {
                                    children: [
                                        /*#__PURE__*/ _jsx(TooltipTrigger, {
                                            asChild: true,
                                            children: /*#__PURE__*/ _jsx(Button, {
                                                variant: "ghost",
                                                size: "icon",
                                                className: "h-8 w-8",
                                                onClick: ()=>copyToClipboard(formattedBody),
                                                children: copied ? /*#__PURE__*/ _jsx(Check, {
                                                    className: "h-4 w-4 text-green-500",
                                                    weight: "bold"
                                                }) : /*#__PURE__*/ _jsx(Copy, {
                                                    className: "h-4 w-4",
                                                    weight: "bold"
                                                })
                                            })
                                        }),
                                        /*#__PURE__*/ _jsx(TooltipContent, {
                                            children: copied ? 'Copied!' : 'Copy response'
                                        })
                                    ]
                                })
                            ]
                        })
                    ]
                }),
                /*#__PURE__*/ _jsxs(Tabs, {
                    defaultValue: "body",
                    className: "flex flex-col flex-1 gap-0",
                    children: [
                        /*#__PURE__*/ _jsxs(TabsList, {
                            className: "w-full justify-start rounded-none border-b bg-background h-auto p-0",
                            children: [
                                /*#__PURE__*/ _jsx(TabsTrigger, {
                                    value: "body",
                                    className: "rounded-none border-b-2 border-transparent data-[state=active]:border-primary px-4 py-3",
                                    children: "Body"
                                }),
                                /*#__PURE__*/ _jsxs(TabsTrigger, {
                                    value: "headers",
                                    className: "rounded-none border-b-2 border-transparent data-[state=active]:border-primary px-4 py-3",
                                    children: [
                                        "Headers",
                                        /*#__PURE__*/ _jsx(Badge, {
                                            variant: "secondary",
                                            className: "ml-2 h-5 px-1.5",
                                            children: headersCount
                                        })
                                    ]
                                })
                            ]
                        }),
                        /*#__PURE__*/ _jsxs(TabsContent, {
                            value: "body",
                            className: "flex-1 m-0 overflow-hidden relative",
                            children: [
                                formattedBody ? /*#__PURE__*/ _jsx(CodeViewer, {
                                    value: formattedBody,
                                    language: detectedLanguage,
                                    height: "100%",
                                    minHeight: 200,
                                    theme: "dark",
                                    showLineNumbers: false,
                                    showBorder: false,
                                    rounded: false
                                }) : /*#__PURE__*/ _jsx("div", {
                                    className: "flex items-center justify-center h-full text-muted-foreground",
                                    children: "No response body"
                                }),
                                /*#__PURE__*/ _jsxs("div", {
                                    className: "absolute top-2.5 right-3 z-20 flex items-center gap-2",
                                    children: [
                                        !isError && onExplain && /*#__PURE__*/ _jsxs(Tooltip, {
                                            children: [
                                                /*#__PURE__*/ _jsx(TooltipTrigger, {
                                                    asChild: true,
                                                    children: /*#__PURE__*/ _jsxs("button", {
                                                        className: "flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-white/70 bg-white/10 hover:bg-white/20 hover:text-white transition-colors rounded-md backdrop-blur-sm",
                                                        onClick: onExplain,
                                                        children: [
                                                            /*#__PURE__*/ _jsx(Lightbulb, {
                                                                className: "h-3.5 w-3.5",
                                                                weight: "bold"
                                                            }),
                                                            /*#__PURE__*/ _jsx("span", {
                                                                children: "Explain"
                                                            })
                                                        ]
                                                    })
                                                }),
                                                /*#__PURE__*/ _jsx(TooltipContent, {
                                                    side: "left",
                                                    children: "Ask AI to explain this response"
                                                })
                                            ]
                                        }),
                                        isError && onDebug && /*#__PURE__*/ _jsxs(Tooltip, {
                                            children: [
                                                /*#__PURE__*/ _jsx(TooltipTrigger, {
                                                    asChild: true,
                                                    children: /*#__PURE__*/ _jsxs("button", {
                                                        className: "flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-white/70 bg-white/10 hover:bg-white/20 hover:text-white transition-colors rounded-md backdrop-blur-sm",
                                                        onClick: onDebug,
                                                        children: [
                                                            /*#__PURE__*/ _jsx(Bug, {
                                                                className: "h-3.5 w-3.5",
                                                                weight: "bold"
                                                            }),
                                                            /*#__PURE__*/ _jsx("span", {
                                                                children: "Debug"
                                                            })
                                                        ]
                                                    })
                                                }),
                                                /*#__PURE__*/ _jsx(TooltipContent, {
                                                    side: "left",
                                                    children: "Ask AI to help debug this error"
                                                })
                                            ]
                                        })
                                    ]
                                })
                            ]
                        }),
                        /*#__PURE__*/ _jsx(TabsContent, {
                            value: "headers",
                            className: "flex-1 m-0 overflow-auto",
                            children: /*#__PURE__*/ _jsxs("div", {
                                className: "divide-y divide-border",
                                children: [
                                    Object.entries(headers).map(([key, value])=>/*#__PURE__*/ _jsxs("div", {
                                            className: "flex items-start gap-4 px-4 py-3",
                                            children: [
                                                /*#__PURE__*/ _jsx("span", {
                                                    className: "font-mono text-sm font-semibold text-foreground min-w-[180px]",
                                                    children: key
                                                }),
                                                /*#__PURE__*/ _jsx("span", {
                                                    className: "font-mono text-sm text-muted-foreground break-all",
                                                    children: value
                                                })
                                            ]
                                        }, key)),
                                    headersCount === 0 && /*#__PURE__*/ _jsx("div", {
                                        className: "flex items-center justify-center p-8 text-muted-foreground",
                                        children: "No response headers"
                                    })
                                ]
                            })
                        })
                    ]
                })
            ]
        })
    });
}
