'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { useState, useMemo, useCallback, useEffect } from 'react';
import { Copy, Check, Spinner, Code, MagnifyingGlass } from '@phosphor-icons/react';
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CodeViewer } from './code-editor';
import { generateCodeAsync, getCodegenByCategory, getMonacoLanguage } from '@/lib/api-docs/codegen';
export function CodeSnippet({ request, defaultLanguage = 'shell-curl', className = '' }) {
    const [selectedLanguage, setSelectedLanguage] = useState(defaultLanguage);
    const [copied, setCopied] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');
    const [generatedCode, setGeneratedCode] = useState('// Loading...');
    const [isLoading, setIsLoading] = useState(true);
    // Get codegen definitions grouped by category
    const codegenByCategory = useMemo(()=>getCodegenByCategory(), []);
    // Filter definitions based on search
    const filteredCategories = useMemo(()=>{
        if (!searchQuery) return codegenByCategory;
        const filtered = {};
        const query = searchQuery.toLowerCase();
        for (const [category, definitions] of Object.entries(codegenByCategory)){
            const matchedDefs = definitions.filter((def)=>def.caption.toLowerCase().includes(query) || def.category.toLowerCase().includes(query) || def.lang.toLowerCase().includes(query));
            if (matchedDefs.length > 0) {
                filtered[category] = matchedDefs;
            }
        }
        return filtered;
    }, [
        codegenByCategory,
        searchQuery
    ]);
    // Generate code async when language or request changes
    useEffect(()=>{
        let cancelled = false;
        setIsLoading(true);
        generateCodeAsync(selectedLanguage, request).then((result)=>{
            if (!cancelled) {
                setGeneratedCode(result.success ? result.code || '' : `// Error: ${result.error}`);
                setIsLoading(false);
            }
        });
        return ()=>{
            cancelled = true;
        };
    }, [
        selectedLanguage,
        request
    ]);
    // Get Monaco language for syntax highlighting
    const monacoLanguage = useMemo(()=>getMonacoLanguage(selectedLanguage), [
        selectedLanguage
    ]);
    // Handle copy to clipboard
    const handleCopy = useCallback(async ()=>{
        try {
            await navigator.clipboard.writeText(generatedCode);
            setCopied(true);
            setTimeout(()=>setCopied(false), 2000);
        } catch (err) {
            console.error('Failed to copy:', err);
        }
    }, [
        generatedCode
    ]);
    // Get current language display name
    const currentLanguageDisplay = useMemo(()=>{
        for (const definitions of Object.values(codegenByCategory)){
            const found = definitions.find((def)=>def.name === selectedLanguage);
            if (found) {
                return `${found.category} - ${found.caption}`;
            }
        }
        return selectedLanguage;
    }, [
        codegenByCategory,
        selectedLanguage
    ]);
    return /*#__PURE__*/ _jsxs("div", {
        className: `flex flex-col h-full ${className}`,
        children: [
            /*#__PURE__*/ _jsxs("div", {
                className: "flex items-center justify-between gap-2 border-b border-border bg-muted/30 px-4 py-2",
                children: [
                    /*#__PURE__*/ _jsxs("div", {
                        className: "flex items-center gap-2 flex-1",
                        children: [
                            /*#__PURE__*/ _jsx(Code, {
                                size: 16,
                                className: "text-muted-foreground"
                            }),
                            /*#__PURE__*/ _jsx("span", {
                                className: "text-sm font-medium text-muted-foreground",
                                children: "Code Snippet"
                            })
                        ]
                    }),
                    /*#__PURE__*/ _jsxs(Select, {
                        value: selectedLanguage,
                        onValueChange: (value)=>setSelectedLanguage(value),
                        children: [
                            /*#__PURE__*/ _jsx(SelectTrigger, {
                                className: "w-[200px] h-8 text-xs",
                                children: /*#__PURE__*/ _jsx(SelectValue, {
                                    placeholder: "Select language",
                                    children: currentLanguageDisplay
                                })
                            }),
                            /*#__PURE__*/ _jsxs(SelectContent, {
                                className: "max-h-[300px]",
                                children: [
                                    /*#__PURE__*/ _jsx("div", {
                                        className: "sticky top-0 bg-popover p-2 border-b border-border",
                                        children: /*#__PURE__*/ _jsxs("div", {
                                            className: "relative",
                                            children: [
                                                /*#__PURE__*/ _jsx(MagnifyingGlass, {
                                                    size: 14,
                                                    className: "absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground"
                                                }),
                                                /*#__PURE__*/ _jsx(Input, {
                                                    placeholder: "Search languages...",
                                                    value: searchQuery,
                                                    onChange: (e)=>setSearchQuery(e.target.value),
                                                    className: "h-7 pl-7 text-xs"
                                                })
                                            ]
                                        })
                                    }),
                                    Object.entries(filteredCategories).map(([category, definitions])=>/*#__PURE__*/ _jsxs(SelectGroup, {
                                            children: [
                                                /*#__PURE__*/ _jsx(SelectLabel, {
                                                    className: "text-xs text-muted-foreground font-medium px-2 py-1",
                                                    children: category
                                                }),
                                                definitions.map((def)=>/*#__PURE__*/ _jsx(SelectItem, {
                                                        value: def.name,
                                                        className: "text-xs pl-4",
                                                        children: /*#__PURE__*/ _jsxs("div", {
                                                            className: "flex items-center gap-2",
                                                            children: [
                                                                /*#__PURE__*/ _jsx("span", {
                                                                    children: def.caption
                                                                }),
                                                                def.name === selectedLanguage && /*#__PURE__*/ _jsx(Check, {
                                                                    size: 12,
                                                                    className: "text-primary"
                                                                })
                                                            ]
                                                        })
                                                    }, def.name))
                                            ]
                                        }, category)),
                                    Object.keys(filteredCategories).length === 0 && /*#__PURE__*/ _jsxs("div", {
                                        className: "p-4 text-center text-sm text-muted-foreground",
                                        children: [
                                            "No languages found for “",
                                            searchQuery,
                                            "”"
                                        ]
                                    })
                                ]
                            })
                        ]
                    }),
                    /*#__PURE__*/ _jsx(TooltipProvider, {
                        children: /*#__PURE__*/ _jsxs(Tooltip, {
                            children: [
                                /*#__PURE__*/ _jsx(TooltipTrigger, {
                                    asChild: true,
                                    children: /*#__PURE__*/ _jsx(Button, {
                                        variant: "ghost",
                                        size: "icon",
                                        className: "h-8 w-8",
                                        onClick: handleCopy,
                                        disabled: isLoading,
                                        children: copied ? /*#__PURE__*/ _jsx(Check, {
                                            size: 16,
                                            className: "text-green-500"
                                        }) : /*#__PURE__*/ _jsx(Copy, {
                                            size: 16
                                        })
                                    })
                                }),
                                /*#__PURE__*/ _jsx(TooltipContent, {
                                    children: /*#__PURE__*/ _jsx("p", {
                                        children: copied ? 'Copied!' : 'Copy to clipboard'
                                    })
                                })
                            ]
                        })
                    })
                ]
            }),
            /*#__PURE__*/ _jsxs("div", {
                className: "flex-1 min-h-0 relative",
                children: [
                    isLoading && /*#__PURE__*/ _jsx("div", {
                        className: "absolute inset-0 flex items-center justify-center bg-background/80 z-10",
                        children: /*#__PURE__*/ _jsx(Spinner, {
                            size: 24,
                            className: "animate-spin text-muted-foreground"
                        })
                    }),
                    /*#__PURE__*/ _jsx(CodeViewer, {
                        value: generatedCode,
                        language: monacoLanguage,
                        height: "100%",
                        theme: "dark",
                        showLineNumbers: false,
                        className: "border-0"
                    })
                ]
            })
        ]
    });
}
// Method color mapping
const methodColors = {
    GET: 'text-green-400',
    POST: 'text-blue-400',
    PUT: 'text-orange-400',
    PATCH: 'text-yellow-400',
    DELETE: 'text-red-400',
    HEAD: 'text-purple-400',
    OPTIONS: 'text-gray-400'
};
export function CodeSnippetCompact({ request }) {
    const [selectedLanguage, setSelectedLanguage] = useState('shell-curl');
    const [copied, setCopied] = useState(false);
    const [generatedCode, setGeneratedCode] = useState('// Loading...');
    const [isLoading, setIsLoading] = useState(true);
    const codegenByCategory = useMemo(()=>getCodegenByCategory(), []);
    // Generate code async when language or request changes
    useEffect(()=>{
        let cancelled = false;
        setIsLoading(true);
        generateCodeAsync(selectedLanguage, request).then((result)=>{
            if (!cancelled) {
                setGeneratedCode(result.success ? result.code || '' : `// Error: ${result.error}`);
                setIsLoading(false);
            }
        });
        return ()=>{
            cancelled = true;
        };
    }, [
        selectedLanguage,
        request
    ]);
    const monacoLanguage = useMemo(()=>getMonacoLanguage(selectedLanguage), [
        selectedLanguage
    ]);
    const handleCopy = useCallback(async ()=>{
        try {
            await navigator.clipboard.writeText(generatedCode);
            setCopied(true);
            setTimeout(()=>setCopied(false), 2000);
        } catch (err) {
            console.error('Failed to copy:', err);
        }
    }, [
        generatedCode
    ]);
    const currentCaption = useMemo(()=>{
        for (const definitions of Object.values(codegenByCategory)){
            const found = definitions.find((def)=>def.name === selectedLanguage);
            if (found) return `${found.category} ${found.caption}`;
        }
        return 'Shell Curl';
    }, [
        codegenByCategory,
        selectedLanguage
    ]);
    // Get shortened endpoint path (decode URL-encoded characters like <<id>>)
    const endpointPath = useMemo(()=>{
        try {
            const url = new URL(request.endpoint);
            // Decode URL-encoded characters to show original path placeholders like <<id>>
            return decodeURIComponent(url.pathname);
        } catch  {
            return request.endpoint;
        }
    }, [
        request.endpoint
    ]);
    return /*#__PURE__*/ _jsxs("div", {
        className: "border-b border-border",
        children: [
            /*#__PURE__*/ _jsxs("div", {
                className: "bg-[#1e1e1e] overflow-hidden",
                children: [
                    /*#__PURE__*/ _jsxs("div", {
                        className: "flex items-center justify-between px-4 py-2 border-b border-[#333]",
                        children: [
                            /*#__PURE__*/ _jsxs("div", {
                                className: "flex items-center gap-2 font-mono text-sm",
                                children: [
                                    /*#__PURE__*/ _jsx("span", {
                                        className: `font-semibold ${methodColors[request.method] || 'text-gray-400'}`,
                                        children: request.method
                                    }),
                                    /*#__PURE__*/ _jsx("span", {
                                        className: "text-gray-300",
                                        children: endpointPath
                                    })
                                ]
                            }),
                            /*#__PURE__*/ _jsxs(Select, {
                                value: selectedLanguage,
                                onValueChange: (value)=>setSelectedLanguage(value),
                                children: [
                                    /*#__PURE__*/ _jsx(SelectTrigger, {
                                        className: "h-7 w-auto gap-1 border-0 bg-transparent text-gray-300 text-xs hover:bg-[#333] focus:ring-0 focus:ring-offset-0",
                                        children: /*#__PURE__*/ _jsx(SelectValue, {
                                            children: currentCaption
                                        })
                                    }),
                                    /*#__PURE__*/ _jsx(SelectContent, {
                                        className: "max-h-[300px]",
                                        children: Object.entries(codegenByCategory).map(([category, definitions])=>/*#__PURE__*/ _jsxs(SelectGroup, {
                                                children: [
                                                    /*#__PURE__*/ _jsx(SelectLabel, {
                                                        className: "text-xs",
                                                        children: category
                                                    }),
                                                    definitions.map((def)=>/*#__PURE__*/ _jsx(SelectItem, {
                                                            value: def.name,
                                                            className: "text-xs",
                                                            children: def.caption
                                                        }, def.name))
                                                ]
                                            }, category))
                                    })
                                ]
                            })
                        ]
                    }),
                    /*#__PURE__*/ _jsxs("div", {
                        className: "relative bg-[#1e1e1e] dark-editor",
                        children: [
                            isLoading && /*#__PURE__*/ _jsx("div", {
                                className: "absolute inset-0 flex items-center justify-center bg-[#1e1e1e]/80 z-10",
                                children: /*#__PURE__*/ _jsx(Spinner, {
                                    size: 20,
                                    className: "animate-spin text-gray-400"
                                })
                            }),
                            /*#__PURE__*/ _jsx(CodeViewer, {
                                value: generatedCode,
                                language: monacoLanguage,
                                height: "auto",
                                minHeight: 80,
                                maxHeight: 200,
                                theme: "dark",
                                showLineNumbers: false,
                                className: "!bg-[#1e1e1e]"
                            })
                        ]
                    })
                ]
            }),
            /*#__PURE__*/ _jsx("div", {
                className: "flex justify-end px-2 py-1 bg-muted/30",
                children: /*#__PURE__*/ _jsx(Button, {
                    variant: "ghost",
                    size: "sm",
                    className: "h-6 text-xs gap-1",
                    onClick: handleCopy,
                    disabled: isLoading,
                    children: copied ? /*#__PURE__*/ _jsxs(_Fragment, {
                        children: [
                            /*#__PURE__*/ _jsx(Check, {
                                size: 12,
                                className: "text-green-500"
                            }),
                            "Copied"
                        ]
                    }) : /*#__PURE__*/ _jsxs(_Fragment, {
                        children: [
                            /*#__PURE__*/ _jsx(Copy, {
                                size: 12
                            }),
                            "Copy"
                        ]
                    })
                })
            })
        ]
    });
}
