import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { memo, useCallback, useEffect, useState } from 'react';
import { ChevronRight, Download, GitBranch, RefreshCw, Sparkles, Upload, X, } from 'lucide-react';
import { useQueryClient } from '@tanstack/react-query';
import { useGitStore } from '../../stores/gitStore';
import { usePanelWidthStore } from '../../stores/panelWidthStore';
import { useGitStatus, usePullChanges, usePushCommits, } from '../../hooks/useGit';
import { Button } from '../ui/Button';
import { GitFileList } from './GitFileList';
import { ResizeHandle } from '../ui/ResizeHandle';
const PANEL_KEY = 'git';
const DEFAULT_WIDTH = 320;
const MIN_WIDTH = 320;
const MAX_WIDTH = 600;
export const GitSidebar = memo(function GitSidebar({ onFixWithAI, }) {
    const isExpanded = useGitStore((state) => state.isExpanded);
    const collapseSidebar = useGitStore((state) => state.collapseSidebar);
    const panelWidth = usePanelWidthStore((s) => s.widths[PANEL_KEY] ?? DEFAULT_WIDTH);
    const { data: status, isLoading, error, refetch } = useGitStatus();
    const queryClient = useQueryClient();
    const pushMutation = usePushCommits();
    const pullMutation = usePullChanges();
    const [errors, setErrors] = useState([]);
    useEffect(() => {
        if (isExpanded) {
            queryClient.invalidateQueries({ queryKey: ['git', 'status'] });
        }
    }, [isExpanded, queryClient]);
    const handleRefresh = () => {
        refetch();
    };
    const addError = useCallback((message, context) => {
        const id = `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
        setErrors((prev) => [...prev, { id, message, context }]);
    }, []);
    const dismissError = useCallback((id) => {
        setErrors((prev) => prev.filter((e) => e.id !== id));
    }, []);
    const handlePush = async () => {
        try {
            await pushMutation.mutateAsync();
        }
        catch (err) {
            addError(err instanceof Error ? err.message : 'Failed to push', 'git push');
        }
    };
    const handlePull = async () => {
        try {
            await pullMutation.mutateAsync();
        }
        catch (err) {
            addError(err instanceof Error ? err.message : 'Failed to pull', 'git pull');
        }
    };
    const handleFixWithAI = useCallback((gitError) => {
        const prompt = gitError.context
            ? `I got a git error during ${gitError.context}:\n\n${gitError.message}\n\nPlease help me fix this.`
            : `I got a git error:\n\n${gitError.message}\n\nPlease help me fix this.`;
        dismissError(gitError.id);
        onFixWithAI?.(prompt);
    }, [onFixWithAI, dismissError]);
    if (!isExpanded)
        return null;
    const allFiles = [
        ...(status?.conflicted || []),
        ...(status?.staged || []),
        ...(status?.unstaged || []),
        ...(status?.untracked || []),
    ];
    const totalChanges = allFiles.length;
    const canPush = status && status.ahead > 0;
    const canPull = status && status.behind > 0;
    const isActing = pushMutation.isPending || pullMutation.isPending;
    return (_jsxs("div", { className: "border-l border-border bg-background flex h-full relative", style: { width: panelWidth }, children: [_jsx(ResizeHandle, { panelKey: PANEL_KEY, side: "right", minWidth: MIN_WIDTH, maxWidth: MAX_WIDTH, defaultWidth: DEFAULT_WIDTH }), _jsxs("div", { className: "flex-1 flex flex-col h-full min-w-0 w-full", children: [_jsxs("div", { className: "h-14 border-b border-border px-3 flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-2 flex-1", children: [_jsx(GitBranch, { className: "w-4 h-4 text-muted-foreground" }), _jsxs("span", { className: "font-medium text-foreground", children: ["Git Changes", totalChanges > 0 && (_jsxs("span", { className: "ml-2 text-xs text-muted-foreground", children: ["(", totalChanges, ")"] }))] })] }), _jsx(Button, { variant: "ghost", size: "icon", onClick: collapseSidebar, title: "Close sidebar", children: _jsx(ChevronRight, { className: "w-4 h-4" }) })] }), _jsx("div", { className: "flex-1 overflow-y-auto", children: isLoading ? (_jsx("div", { className: "p-4 text-sm text-muted-foreground", children: "Loading git status..." })) : error ? (_jsx("div", { className: "p-3 text-sm text-muted-foreground", children: _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("span", { className: "text-orange-500", children: error instanceof Error
                                            ? error.message
                                            : 'Failed to load git status' }), _jsx(Button, { variant: "secondary", size: "sm", onClick: handleRefresh, children: "Retry" })] }) })) : !status || totalChanges === 0 ? (_jsx("div", { className: "p-3 text-sm text-muted-foreground", children: "No changes detected" })) : (_jsx(GitFileList, { status: status })) }), errors.length > 0 && (_jsx("div", { className: "border-t border-border", children: errors.map((gitError) => (_jsxs("div", { className: "px-3 py-2 text-xs border-b border-border last:border-b-0 bg-orange-50 dark:bg-orange-950/20 flex items-start gap-2", children: [_jsx("span", { className: "text-orange-500 flex-1 min-w-0 break-words", children: gitError.message }), _jsxs("div", { className: "flex items-center gap-1 flex-shrink-0", children: [onFixWithAI && (_jsxs("button", { type: "button", onClick: () => handleFixWithAI(gitError), className: "flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20 transition-colors", title: "Fix with AI", children: [_jsx(Sparkles, { className: "w-3 h-3" }), "Fix"] })), _jsx("button", { type: "button", onClick: () => dismissError(gitError.id), className: "text-muted-foreground hover:text-foreground transition-colors p-0.5", title: "Dismiss", children: _jsx(X, { className: "w-3 h-3" }) })] })] }, gitError.id))) })), _jsxs("div", { className: "h-12 border-t border-border flex items-center gap-1 px-2", children: [_jsxs(Button, { variant: "secondary", size: "sm", onClick: handlePull, disabled: !canPull || isActing, title: canPull
                                    ? `Pull ${status?.behind} commit(s) from remote`
                                    : 'Nothing to pull', className: "flex-1 h-8 text-xs gap-1.5", children: [_jsx(Download, { className: `w-3.5 h-3.5 ${pullMutation.isPending ? 'animate-pulse' : ''}` }), "Pull", canPull && (_jsxs("span", { className: "text-orange-500", children: ["\u2193", status?.behind] }))] }), _jsxs(Button, { variant: "secondary", size: "sm", onClick: handlePush, disabled: !canPush || isActing, title: canPush
                                    ? `Push ${status?.ahead} commit(s) to remote`
                                    : 'Nothing to push', className: "flex-1 h-8 text-xs gap-1.5", children: [_jsx(Upload, { className: `w-3.5 h-3.5 ${pushMutation.isPending ? 'animate-pulse' : ''}` }), "Push", canPush && (_jsxs("span", { className: "text-green-500", children: ["\u2191", status?.ahead] }))] })] }), _jsxs("div", { className: "h-10 px-3 border-t border-border text-xs text-muted-foreground flex items-center justify-between gap-2", children: [_jsxs("div", { className: "flex items-center gap-2 min-w-0 flex-1", children: [_jsx(GitBranch, { className: "w-3 h-3 flex-shrink-0" }), status?.branch && (_jsx("span", { className: "truncate", children: status.branch }))] }), _jsx(Button, { variant: "ghost", size: "icon", onClick: handleRefresh, title: "Refresh git status", className: "h-6 w-6 flex-shrink-0", disabled: isLoading, children: _jsx(RefreshCw, { className: `w-3 h-3 ${isLoading ? 'animate-spin' : ''}` }) })] })] })] }));
});
//# sourceMappingURL=GitSidebar.js.map