'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useMemo } from 'react';
import { ShieldCheck, Key, Lock, User, X, Star } from '@phosphor-icons/react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogClose } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useAuth } from '@/lib/api-docs/auth';
import { cn } from '@/lib/utils';
const BASE_AUTH_TYPES = [
    {
        value: 'none',
        label: 'No Auth',
        icon: ShieldCheck
    },
    {
        value: 'basic',
        label: 'Basic Auth',
        icon: User
    },
    {
        value: 'bearer',
        label: 'Bearer Token',
        icon: Key
    },
    {
        value: 'api-key',
        label: 'API Key',
        icon: Lock
    }
];
export function GlobalAuthModal({ open, onClose }) {
    const { globalAuth, setGlobalAuth, clearAuth, specSchemes, specDefaultAuth } = useAuth();
    // Local state for editing
    const [authType, setAuthType] = useState('none');
    const [basicUsername, setBasicUsername] = useState('');
    const [basicPassword, setBasicPassword] = useState('');
    const [bearerToken, setBearerToken] = useState('');
    const [apiKeyName, setApiKeyName] = useState('X-API-Key');
    const [apiKeyValue, setApiKeyValue] = useState('');
    const [apiKeyLocation, setApiKeyLocation] = useState('HEADERS');
    const [showPassword, setShowPassword] = useState(false);
    // Build auth types with spec-recommended first
    const AUTH_TYPES = useMemo(()=>{
        // If we have a spec default auth, put it first with a recommended label
        if (specDefaultAuth && specDefaultAuth.authType !== 'none') {
            const specType = specDefaultAuth.authType;
            const baseType = BASE_AUTH_TYPES.find((t)=>t.value === specType);
            if (baseType) {
                // Get scheme info but use short label
                const scheme = specSchemes.find((s)=>s.type === specType);
                const label = `${baseType.label} (Recommended)`;
                const description = scheme?.description;
                return [
                    {
                        ...baseType,
                        label,
                        isRecommended: true,
                        description
                    },
                    ...BASE_AUTH_TYPES.filter((t)=>t.value !== specType).map((t)=>({
                            ...t,
                            isRecommended: false,
                            description: undefined
                        }))
                ];
            }
        }
        return BASE_AUTH_TYPES.map((t)=>({
                ...t,
                isRecommended: false,
                description: undefined
            }));
    }, [
        specDefaultAuth,
        specSchemes
    ]);
    // Sync local state with global auth when modal opens
    useEffect(()=>{
        if (open && globalAuth) {
            setAuthType(globalAuth.authType);
            if (globalAuth.authType === 'basic') {
                setBasicUsername(globalAuth.username);
                setBasicPassword(globalAuth.password);
            } else if (globalAuth.authType === 'bearer') {
                setBearerToken(globalAuth.token);
            } else if (globalAuth.authType === 'api-key') {
                setApiKeyName(globalAuth.key);
                setApiKeyValue(globalAuth.value);
                setApiKeyLocation(globalAuth.addTo);
            }
        } else if (open) {
            // If no global auth set, use spec default as the initial type
            if (specDefaultAuth && specDefaultAuth.authType !== 'none') {
                setAuthType(specDefaultAuth.authType);
                // Pre-populate fields from spec (like API key name)
                if (specDefaultAuth.authType === 'api-key') {
                    setApiKeyName(specDefaultAuth.key || 'X-API-Key');
                    setApiKeyLocation(specDefaultAuth.addTo || 'HEADERS');
                    setApiKeyValue(''); // User needs to enter value
                }
            } else {
                setAuthType('none');
            }
            setBasicUsername('');
            setBasicPassword('');
            setBearerToken('');
            if (!specDefaultAuth || specDefaultAuth.authType !== 'api-key') {
                setApiKeyName('X-API-Key');
                setApiKeyValue('');
                setApiKeyLocation('HEADERS');
            }
        }
    }, [
        open,
        globalAuth,
        specDefaultAuth
    ]);
    const handleSave = ()=>{
        let auth;
        switch(authType){
            case 'basic':
                auth = {
                    authType: 'basic',
                    authActive: true,
                    username: basicUsername.trim(),
                    password: basicPassword
                };
                break;
            case 'bearer':
                auth = {
                    authType: 'bearer',
                    authActive: true,
                    token: bearerToken.trim()
                };
                break;
            case 'api-key':
                auth = {
                    authType: 'api-key',
                    authActive: true,
                    addTo: apiKeyLocation,
                    key: apiKeyName.trim(),
                    value: apiKeyValue.trim()
                };
                break;
            default:
                auth = {
                    authType: 'none',
                    authActive: true
                };
        }
        setGlobalAuth(auth);
        onClose();
    };
    const handleClear = ()=>{
        clearAuth();
        setAuthType('none');
        setBasicUsername('');
        setBasicPassword('');
        setBearerToken('');
        setApiKeyName('X-API-Key');
        setApiKeyValue('');
        onClose();
    };
    const currentType = AUTH_TYPES.find((t)=>t.value === authType) || AUTH_TYPES[0];
    const CurrentIcon = currentType.icon;
    return /*#__PURE__*/ _jsx(Dialog, {
        open: open,
        onOpenChange: (isOpen)=>!isOpen && onClose(),
        children: /*#__PURE__*/ _jsxs(DialogContent, {
            children: [
                /*#__PURE__*/ _jsxs(DialogHeader, {
                    children: [
                        /*#__PURE__*/ _jsx(DialogTitle, {
                            children: "Global Authentication"
                        }),
                        /*#__PURE__*/ _jsx(DialogClose, {
                            className: "text-muted-foreground hover:text-foreground transition-colors p-1 hover:bg-muted rounded",
                            children: /*#__PURE__*/ _jsx(X, {
                                className: "h-4 w-4"
                            })
                        })
                    ]
                }),
                /*#__PURE__*/ _jsxs("div", {
                    className: "p-5 space-y-4",
                    children: [
                        /*#__PURE__*/ _jsxs("div", {
                            className: "space-y-1.5",
                            children: [
                                /*#__PURE__*/ _jsx("label", {
                                    className: "text-xs font-medium text-muted-foreground uppercase tracking-wide",
                                    children: "Type"
                                }),
                                /*#__PURE__*/ _jsxs(Select, {
                                    value: authType,
                                    onValueChange: setAuthType,
                                    children: [
                                        /*#__PURE__*/ _jsx(SelectTrigger, {
                                            className: "w-full h-9",
                                            children: /*#__PURE__*/ _jsx(SelectValue, {
                                                children: /*#__PURE__*/ _jsxs("span", {
                                                    className: "flex items-center gap-2",
                                                    children: [
                                                        /*#__PURE__*/ _jsx(CurrentIcon, {
                                                            className: "h-3.5 w-3.5",
                                                            weight: "bold"
                                                        }),
                                                        /*#__PURE__*/ _jsx("span", {
                                                            className: "text-sm truncate",
                                                            children: currentType.label
                                                        }),
                                                        currentType.isRecommended && /*#__PURE__*/ _jsx(Star, {
                                                            className: "h-3 w-3 text-amber-500 flex-shrink-0",
                                                            weight: "fill"
                                                        })
                                                    ]
                                                })
                                            })
                                        }),
                                        /*#__PURE__*/ _jsx(SelectContent, {
                                            children: AUTH_TYPES.map((type)=>/*#__PURE__*/ _jsx(SelectItem, {
                                                    value: type.value,
                                                    children: /*#__PURE__*/ _jsxs("div", {
                                                        className: "flex items-center gap-2",
                                                        children: [
                                                            /*#__PURE__*/ _jsx(type.icon, {
                                                                className: "h-3.5 w-3.5",
                                                                weight: "bold"
                                                            }),
                                                            /*#__PURE__*/ _jsx("span", {
                                                                children: type.label
                                                            }),
                                                            type.isRecommended && /*#__PURE__*/ _jsx(Star, {
                                                                className: "h-3 w-3 text-amber-500 ml-1",
                                                                weight: "fill"
                                                            })
                                                        ]
                                                    })
                                                }, type.value))
                                        })
                                    ]
                                }),
                                currentType.description && /*#__PURE__*/ _jsx("p", {
                                    className: "text-xs text-muted-foreground mt-1.5 line-clamp-2",
                                    children: currentType.description.split('\n')[0]
                                })
                            ]
                        }),
                        authType === 'none' && /*#__PURE__*/ _jsx("div", {
                            className: "flex items-center justify-center py-8 text-center",
                            children: /*#__PURE__*/ _jsx("p", {
                                className: "text-sm text-muted-foreground",
                                children: "No authentication will be applied"
                            })
                        }),
                        authType === 'basic' && /*#__PURE__*/ _jsxs("div", {
                            className: "space-y-3",
                            children: [
                                /*#__PURE__*/ _jsxs("div", {
                                    className: "space-y-1.5",
                                    children: [
                                        /*#__PURE__*/ _jsx("label", {
                                            className: "text-xs font-medium text-muted-foreground",
                                            children: "Username"
                                        }),
                                        /*#__PURE__*/ _jsx(Input, {
                                            type: "text",
                                            value: basicUsername,
                                            onChange: (e)=>setBasicUsername(e.target.value),
                                            placeholder: "Enter username",
                                            className: "h-9"
                                        })
                                    ]
                                }),
                                /*#__PURE__*/ _jsxs("div", {
                                    className: "space-y-1.5",
                                    children: [
                                        /*#__PURE__*/ _jsx("label", {
                                            className: "text-xs font-medium text-muted-foreground",
                                            children: "Password"
                                        }),
                                        /*#__PURE__*/ _jsxs("div", {
                                            className: "relative",
                                            children: [
                                                /*#__PURE__*/ _jsx(Input, {
                                                    type: showPassword ? 'text' : 'password',
                                                    value: basicPassword,
                                                    onChange: (e)=>setBasicPassword(e.target.value),
                                                    placeholder: "Enter password",
                                                    className: "h-9 pr-14"
                                                }),
                                                /*#__PURE__*/ _jsx("button", {
                                                    type: "button",
                                                    onClick: ()=>setShowPassword(!showPassword),
                                                    className: "absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground text-xs px-1.5 py-0.5 rounded hover:bg-muted",
                                                    children: showPassword ? 'Hide' : 'Show'
                                                })
                                            ]
                                        })
                                    ]
                                })
                            ]
                        }),
                        authType === 'bearer' && /*#__PURE__*/ _jsxs("div", {
                            className: "space-y-1.5",
                            children: [
                                /*#__PURE__*/ _jsx("label", {
                                    className: "text-xs font-medium text-muted-foreground",
                                    children: "Token"
                                }),
                                /*#__PURE__*/ _jsx("textarea", {
                                    value: bearerToken,
                                    onChange: (e)=>setBearerToken(e.target.value),
                                    placeholder: "Paste your bearer token...",
                                    className: "w-full min-h-[80px] px-3 py-2 rounded-md border border-input bg-background font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-ring placeholder:text-muted-foreground/50"
                                })
                            ]
                        }),
                        authType === 'api-key' && /*#__PURE__*/ _jsxs("div", {
                            className: "space-y-3",
                            children: [
                                /*#__PURE__*/ _jsxs("div", {
                                    className: "space-y-1.5",
                                    children: [
                                        /*#__PURE__*/ _jsx("label", {
                                            className: "text-xs font-medium text-muted-foreground",
                                            children: "Add to"
                                        }),
                                        /*#__PURE__*/ _jsxs("div", {
                                            className: "flex p-0.5 bg-muted rounded-md",
                                            children: [
                                                /*#__PURE__*/ _jsx("button", {
                                                    type: "button",
                                                    onClick: ()=>setApiKeyLocation('HEADERS'),
                                                    className: cn('flex-1 px-3 py-1 rounded text-xs font-medium transition-all', apiKeyLocation === 'HEADERS' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'),
                                                    children: "Header"
                                                }),
                                                /*#__PURE__*/ _jsx("button", {
                                                    type: "button",
                                                    onClick: ()=>setApiKeyLocation('QUERY_PARAMS'),
                                                    className: cn('flex-1 px-3 py-1 rounded text-xs font-medium transition-all', apiKeyLocation === 'QUERY_PARAMS' ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'),
                                                    children: "Query"
                                                })
                                            ]
                                        })
                                    ]
                                }),
                                /*#__PURE__*/ _jsxs("div", {
                                    className: "space-y-1.5",
                                    children: [
                                        /*#__PURE__*/ _jsx("label", {
                                            className: "text-xs font-medium text-muted-foreground",
                                            children: "Key Name"
                                        }),
                                        /*#__PURE__*/ _jsx(Input, {
                                            type: "text",
                                            value: apiKeyName,
                                            onChange: (e)=>setApiKeyName(e.target.value),
                                            placeholder: "X-API-Key",
                                            className: "font-mono h-9"
                                        })
                                    ]
                                }),
                                /*#__PURE__*/ _jsxs("div", {
                                    className: "space-y-1.5",
                                    children: [
                                        /*#__PURE__*/ _jsx("label", {
                                            className: "text-xs font-medium text-muted-foreground",
                                            children: "Key Value"
                                        }),
                                        /*#__PURE__*/ _jsxs("div", {
                                            className: "relative",
                                            children: [
                                                /*#__PURE__*/ _jsx(Input, {
                                                    type: showPassword ? 'text' : 'password',
                                                    value: apiKeyValue,
                                                    onChange: (e)=>setApiKeyValue(e.target.value),
                                                    placeholder: "Enter API key",
                                                    className: "font-mono h-9 pr-14"
                                                }),
                                                /*#__PURE__*/ _jsx("button", {
                                                    type: "button",
                                                    onClick: ()=>setShowPassword(!showPassword),
                                                    className: "absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground text-xs px-1.5 py-0.5 rounded hover:bg-muted",
                                                    children: showPassword ? 'Hide' : 'Show'
                                                })
                                            ]
                                        })
                                    ]
                                })
                            ]
                        })
                    ]
                }),
                /*#__PURE__*/ _jsxs(DialogFooter, {
                    children: [
                        /*#__PURE__*/ _jsx("button", {
                            onClick: handleClear,
                            className: "text-xs text-muted-foreground hover:text-destructive transition-colors",
                            children: "Clear"
                        }),
                        /*#__PURE__*/ _jsxs("div", {
                            className: "flex gap-2",
                            children: [
                                /*#__PURE__*/ _jsx(Button, {
                                    variant: "ghost",
                                    size: "sm",
                                    onClick: onClose,
                                    className: "h-8 px-3 text-xs",
                                    children: "Cancel"
                                }),
                                /*#__PURE__*/ _jsx(Button, {
                                    size: "sm",
                                    onClick: handleSave,
                                    className: "h-8 px-4 text-xs",
                                    children: "Apply"
                                })
                            ]
                        })
                    ]
                })
            ]
        })
    });
}
