'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useCallback, useEffect, useRef } from 'react';
import { Check, CheckIcon, ChevronsUpDown, GitBranch, Loader2 } from 'lucide-react';
import { BaseDrawer } from '../../common/base-drawer/index.js';
import { DrawerTitle, DrawerDescription } from '../../ui/drawer.js';
import { Button } from '../../ui/button.js';
import { Input } from '../../ui/input.js';
import { Label } from '../../ui/label.js';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from '../../ui/command.js';
import { Popover, PopoverContent, PopoverTrigger } from '../../ui/popover.js';
import { cn } from '../../../lib/utils.js';
export function AdoptBranchDrawer({ open, onClose, onSubmit, isSubmitting = false, error, repositories = [], selectedRepositoryPath, onRepositoryChange, branches = [], branchesLoading = false, }) {
    const [branchName, setBranchName] = useState('');
    const [comboboxOpen, setComboboxOpen] = useState(false);
    const [inputValue, setInputValue] = useState('');
    const inputRef = useRef(null);
    const [repoOpen, setRepoOpen] = useState(false);
    const [repoQuery, setRepoQuery] = useState('');
    const repoInputRef = useRef(null);
    const selectedRepo = repositories.find((r) => r.path === selectedRepositoryPath);
    const hasRepo = !!selectedRepositoryPath;
    // Reset state when drawer closes
    useEffect(() => {
        if (!open) {
            setBranchName('');
            setInputValue('');
            setComboboxOpen(false);
            setRepoOpen(false);
            setRepoQuery('');
        }
    }, [open]);
    // Reset branch selection when repository changes
    useEffect(() => {
        setBranchName('');
        setInputValue('');
    }, [selectedRepositoryPath]);
    const handleSubmit = useCallback((e) => {
        e.preventDefault();
        const trimmed = branchName.trim();
        if (!trimmed || !selectedRepositoryPath || isSubmitting)
            return;
        onSubmit(trimmed, selectedRepositoryPath);
    }, [branchName, selectedRepositoryPath, isSubmitting, onSubmit]);
    const handleClose = useCallback(() => {
        setBranchName('');
        setInputValue('');
        onClose();
    }, [onClose]);
    const handleSelect = useCallback((branch) => {
        setBranchName(branch);
        setInputValue(branch);
        setComboboxOpen(false);
    }, []);
    const handleInputChange = useCallback((e) => {
        setInputValue(e.target.value);
        if (!comboboxOpen)
            setComboboxOpen(true);
    }, [comboboxOpen]);
    const handleInputKeyDown = useCallback((e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            const trimmed = inputValue.trim();
            if (trimmed) {
                setBranchName(trimmed);
                setComboboxOpen(false);
            }
        }
        if (e.key === 'Escape') {
            setComboboxOpen(false);
            setInputValue(branchName);
        }
    }, [inputValue, branchName]);
    const handleRepoSelect = useCallback((path) => {
        onRepositoryChange?.(path);
        setRepoOpen(false);
        setRepoQuery('');
    }, [onRepositoryChange]);
    const filteredBranches = branches.filter((b) => b.toLowerCase().includes(inputValue.toLowerCase()));
    const filteredRepos = repoQuery.trim()
        ? repositories.filter((r) => r.name.toLowerCase().includes(repoQuery.toLowerCase()) ||
            r.path.toLowerCase().includes(repoQuery.toLowerCase()))
        : repositories;
    useEffect(() => {
        if (repoOpen) {
            setTimeout(() => repoInputRef.current?.focus(), 0);
        }
        else {
            setRepoQuery('');
        }
    }, [repoOpen]);
    const isDisabled = !branchName.trim() || !selectedRepositoryPath || isSubmitting;
    const header = (_jsxs("div", { children: [_jsxs(DrawerTitle, { className: "flex items-center gap-2", children: [_jsx(GitBranch, { className: "h-4 w-4" }), "Adopt Branch"] }), _jsx(DrawerDescription, { className: "text-muted-foreground text-sm", children: "Import an existing git branch into Shep's feature tracking" })] }));
    return (_jsx(BaseDrawer, { open: open, onClose: handleClose, size: "sm", modal: false, header: header, "data-testid": "adopt-branch-drawer", children: _jsxs("form", { onSubmit: handleSubmit, className: "flex flex-1 flex-col", children: [_jsx("div", { className: "flex-1 overflow-y-auto p-4", children: _jsxs("div", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(Label, { children: "Repository" }), _jsxs(Popover, { open: repoOpen, onOpenChange: setRepoOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs("button", { type: "button", role: "combobox", "aria-expanded": repoOpen, "aria-label": "Repository", disabled: isSubmitting, "data-testid": "adopt-repo-combobox", className: cn('border-input bg-background ring-offset-background focus:ring-ring flex h-9 w-full items-center justify-between rounded-md border px-3 py-2 text-sm focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50', !selectedRepo && 'text-muted-foreground'), children: [_jsx("span", { className: "truncate", children: selectedRepo ? selectedRepo.name : 'Select repository...' }), _jsx(ChevronsUpDown, { className: "ms-2 h-4 w-4 shrink-0 opacity-50" })] }) }), _jsx(PopoverContent, { className: "w-80 p-0", align: "start", "data-testid": "adopt-repo-combobox-content", children: _jsxs("div", { className: "flex flex-col", children: [_jsx("div", { className: "border-b p-2", children: _jsx(Input, { ref: repoInputRef, placeholder: "Search repositories...", value: repoQuery, onChange: (e) => setRepoQuery(e.target.value), className: "h-8 border-0 p-0 text-sm shadow-none focus-visible:ring-0", "data-testid": "adopt-repo-search" }) }), _jsx("div", { className: "max-h-48 overflow-y-auto py-1", role: "listbox", "aria-label": "Repositories", children: filteredRepos.length === 0 ? (_jsx("p", { className: "text-muted-foreground px-3 py-2 text-sm", children: "No repositories found." })) : (filteredRepos.map((r) => (_jsxs("button", { type: "button", role: "option", "aria-selected": selectedRepositoryPath === r.path, onClick: () => handleRepoSelect(r.path), className: cn('hover:bg-accent hover:text-accent-foreground flex w-full items-center gap-2 px-3 py-2 text-sm', selectedRepositoryPath === r.path && 'bg-accent/50'), "data-testid": `adopt-repo-option-${r.id}`, children: [_jsx(CheckIcon, { className: cn('h-4 w-4 shrink-0', selectedRepositoryPath !== r.path && 'invisible') }), _jsxs("span", { className: "flex flex-col items-start truncate", children: [_jsx("span", { className: "truncate", children: r.name }), _jsx("span", { className: "text-muted-foreground truncate text-xs", children: r.path })] })] }, r.id)))) })] }) })] }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Select the repository that contains the branch you want to adopt." })] }), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(Label, { htmlFor: "branch-name", children: "Branch name" }), _jsxs(Popover, { open: comboboxOpen, onOpenChange: setComboboxOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { variant: "outline", role: "combobox", "aria-expanded": comboboxOpen, disabled: isSubmitting || !hasRepo, className: "w-full justify-between font-normal", "data-testid": "adopt-branch-input", children: [_jsx("span", { className: "truncate", children: !hasRepo
                                                                ? 'Select a repository first...'
                                                                : branchesLoading
                                                                    ? 'Loading branches...'
                                                                    : branchName || 'Select a branch...' }), _jsx(ChevronsUpDown, { className: "ms-2 h-4 w-4 shrink-0 opacity-50" })] }) }), _jsx(PopoverContent, { className: "w-[var(--radix-popover-trigger-width)] p-0", align: "start", children: _jsxs(Command, { children: [_jsx(CommandInput, { ref: inputRef, placeholder: "Search branches...", value: inputValue, onChange: handleInputChange, onKeyDown: handleInputKeyDown, "data-testid": "adopt-branch-search" }), _jsxs(CommandList, { children: [!branchesLoading && filteredBranches.length === 0 && (_jsx(CommandEmpty, { children: branches.length === 0
                                                                        ? 'No branches found.'
                                                                        : inputValue
                                                                            ? 'No match — press Enter to use this value.'
                                                                            : 'No branches available.' })), branchesLoading ? (_jsx(CommandEmpty, { children: _jsx(Loader2, { className: "mx-auto h-4 w-4 animate-spin" }) })) : null, filteredBranches.length > 0 && (_jsx(CommandGroup, { children: filteredBranches.map((branch) => (_jsxs(CommandItem, { selected: branch === branchName, onClick: () => handleSelect(branch), children: [_jsx(Check, { className: cn('me-2 h-4 w-4', branch === branchName ? 'opacity-100' : 'opacity-0') }), _jsx(GitBranch, { className: "me-2 h-3 w-3 opacity-50" }), branch] }, branch))) }))] })] }) })] }), _jsx("p", { className: "text-muted-foreground text-xs", children: hasRepo
                                            ? 'Select a branch from the dropdown or type to search. Local and remote branches are shown.'
                                            : 'Please select a repository above to see available branches.' })] }), error ? (_jsx("p", { className: "text-destructive text-sm", "data-testid": "adopt-branch-error", children: error })) : null] }) }), _jsx("div", { className: "border-t p-4", children: _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { type: "button", variant: "outline", onClick: handleClose, disabled: isSubmitting, className: "flex-1", children: "Cancel" }), _jsx(Button, { type: "submit", disabled: isDisabled, className: "flex-1", "data-testid": "adopt-branch-submit", children: isSubmitting ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "me-2 h-4 w-4 animate-spin" }), "Adopting..."] })) : ('Adopt Branch') })] }) })] }) }));
}
