import { Button } from '@admin/components/ui/button';
import { CommandDialog, CommandEmpty, CommandList } from '@admin/components/ui/command';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@admin/components/ui/select';
import { router } from '@inertiajs/react';
import axios from 'axios';
import { Contact, FileText, Folder, Loader2, Search, User } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { useDebouncedCallback } from 'use-debounce';

interface SearchResult {
    type: 'user' | 'contact';
    id: number;
    uid: string | number;
    title: string;
    subtitle: string;
    url: string;
    icon: string;
}

interface SearchResponse {
    success: boolean;
    results: SearchResult[];
    query: string;
    count: number;
}

interface Module {
    value: string;
    label: string;
}

interface Suggestion {
    id: string;
    title: string;
    subtitle: string;
    icon: string;
    action: () => void;
}

const MODULES: Module[] = [
    { value: 'all', label: 'All Modules' },
    { value: 'users', label: 'Users' },
    { value: 'contacts', label: 'Contacts' },
    { value: 'tasks', label: 'Tasks' },
    { value: 'projects', label: 'Projects' },
];

const DEFAULT_SUGGESTIONS: Suggestion[] = [
    {
        id: 'recent-users',
        title: 'Recent Users',
        subtitle: 'View recently added users',
        icon: 'user',
        action: () => router.visit('/users'),
    },
    {
        id: 'recent-contacts',
        title: 'Recent Contacts',
        subtitle: 'View recently added contacts',
        icon: 'contact',
        action: () => router.visit('/contacts'),
    },
    {
        id: 'all-tasks',
        title: 'All Tasks',
        subtitle: 'Browse all tasks',
        icon: 'file',
        action: () => router.visit('/tasks'),
    },
    {
        id: 'all-projects',
        title: 'All Projects',
        subtitle: 'Browse all projects',
        icon: 'folder',
        action: () => router.visit('/projects'),
    },
];

export function GlobalSearch() {
    const [open, setOpen] = useState(false);
    const [query, setQuery] = useState('');
    const [results, setResults] = useState<SearchResult[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const [selectedModule, setSelectedModule] = useState('all');

    // Command+K or Ctrl+K to open search
    useEffect(() => {
        const down = (e: KeyboardEvent) => {
            if (e.key === 'k' && (e.metaKey || e.ctrlKey)) {
                e.preventDefault();
                setOpen((open) => !open);
            }
        };

        document.addEventListener('keydown', down);
        return () => document.removeEventListener('keydown', down);
    }, []);

    // Debounced search function
    const performSearch = useDebouncedCallback(async (searchQuery: string, moduleType: string) => {
        if (searchQuery.length < 2) {
            setResults([]);
            setIsLoading(false);
            return;
        }

        setIsLoading(true);

        try {
            const typeParam = moduleType === 'all' ? 'all_modules' : moduleType;
            const response = await axios.get(`/search/quick?q=${encodeURIComponent(searchQuery)}&type=${typeParam}`);
            const data: SearchResponse = response.data;

            console.log('Search API Response:', data);
            console.log('Results count:', data.results?.length || 0);

            if (data.success) {
                console.log('Setting results:', data.results);
                setResults(data.results);
                console.log('Results state after set:', data.results);
            } else {
                console.error('Search returned unsuccessful:', data);
                setResults([]);
            }
        } catch (error: any) {
            console.error('Search error:', error);
            console.error('Error response:', error.response?.data);
            setResults([]);
        } finally {
            setIsLoading(false);
        }
    }, 300);

    // Handle query change
    const handleQueryChange = useCallback(
        (value: string) => {
            setQuery(value);
            if (value.length >= 2) {
                setIsLoading(true);
                performSearch(value, selectedModule);
            } else {
                setResults([]);
                setIsLoading(false);
            }
        },
        [performSearch, selectedModule],
    );

    // Handle module change - re-trigger search if query exists
    const handleModuleChange = (value: string) => {
        setSelectedModule(value);
        if (query.length >= 2) {
            setIsLoading(true);
            performSearch(query, value);
        }
    };

    // Handle result selection
    const handleSelect = (url: string) => {
        console.log('Navigating to:', url);
        setOpen(false);
        setQuery('');
        setResults([]);
        router.visit(url);
    };

    // Get icon component based on type
    const getIcon = (type: string) => {
        switch (type) {
            case 'user':
                return <User className="h-5 w-5" />;
            case 'contact':
                return <Contact className="h-5 w-5" />;
            case 'file':
                return <FileText className="h-5 w-5" />;
            case 'folder':
                return <Folder className="h-5 w-5" />;
            default:
                return <Search className="h-5 w-5" />;
        }
    };

    // Get type label
    const getTypeLabel = (type: string) => {
        switch (type) {
            case 'user':
                return 'Users';
            case 'contact':
                return 'Contacts';
            default:
                return 'Results';
        }
    };

    // Group results by type
    const groupedResults = results.reduce(
        (acc, result) => {
            if (!acc[result.type]) {
                acc[result.type] = [];
            }
            acc[result.type].push(result);
            return acc;
        },
        {} as Record<string, SearchResult[]>,
    );

    return (
        <>
            {/* Search Trigger Button */}
            <Button
                variant="outline"
                className="relative h-9 w-full justify-start border-input bg-none text-sm text-muted-foreground sm:pr-12 md:w-40 lg:w-64"
                onClick={() => setOpen(true)}
            >
                <Search className="mr-2 h-4 w-4" />
                <span className="hidden lg:inline-flex">Search...</span>
                <span className="inline-flex lg:hidden">Search...</span>
                <kbd className="pointer-events-none absolute top-1.5 right-1.5 hidden h-6 items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 select-none sm:flex">
                    <span className="text-xs">⌘</span>K
                </kbd>
            </Button>

            {/* Search Dialog */}
            <CommandDialog open={open} onOpenChange={setOpen}>
                <div className="flex items-center gap-2 border-b">
                    <Select value={selectedModule} onValueChange={handleModuleChange}>
                        <SelectTrigger className="h-8 w-[128px] border-0 border-r font-medium shadow-none focus:ring-0">
                            <SelectValue />
                        </SelectTrigger>
                        <SelectContent className="font-medium">
                            {MODULES.map((module) => (
                                <SelectItem key={module.value} value={module.value}>
                                    {module.label}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                    <Search className="h-4 w-4 shrink-0 opacity-50" />
                    <input
                        placeholder="Search users, contacts..."
                        value={query}
                        onChange={(e) => handleQueryChange(e.target.value)}
                        className="flex h-11 flex-1 rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"
                    />
                </div>
                <CommandList>
                    {isLoading && (
                        <div className="flex items-center justify-center py-6">
                            <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                        </div>
                    )}

                    {!isLoading && query.length === 0 && (
                        <div className="space-y-4 p-2">
                            <div className="px-1">
                                <div className="space-y-1">
                                    {DEFAULT_SUGGESTIONS.map((suggestion) => (
                                        <div
                                            key={suggestion.id}
                                            className="group relative flex cursor-pointer items-center gap-3 rounded-lg border border-transparent px-1 py-2.5 text-sm transition-all select-none hover:border-border hover:bg-accent/50 hover:shadow-sm"
                                            onClick={() => {
                                                setOpen(false);
                                                setQuery('');
                                                suggestion.action();
                                            }}
                                        >
                                            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary transition-colors group-hover:bg-primary/20">
                                                {getIcon(suggestion.icon)}
                                            </div>
                                            <div className="flex min-w-0 flex-1 flex-col">
                                                <span className="truncate font-medium text-foreground">{suggestion.title}</span>
                                                <span className="truncate text-xs text-muted-foreground">{suggestion.subtitle}</span>
                                            </div>
                                            <div className="transition-opacity">
                                                <svg className="h-4 w-4 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                                </svg>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    )}

                    {!isLoading && query.length >= 2 && results.length === 0 && <CommandEmpty>No results found for "{query}"</CommandEmpty>}

                    {!isLoading && query.length > 0 && query.length < 2 && (
                        <div className="py-6 text-center text-sm text-muted-foreground">Type at least 2 characters to search...</div>
                    )}

                    {!isLoading && Object.entries(groupedResults).length > 0 ? (
                        <div className="space-y-4 py-2">
                            {Object.entries(groupedResults).map(([type, items]) => {
                                console.log('Rendering group:', type, 'with items:', items);
                                return (
                                    <div key={type} className="px-2">
                                        {/* Group Header */}
                                        <div className="mb-2 flex items-center gap-2 px-2">
                                            <div className="h-px flex-1 bg-border" />
                                            <span className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                                                {getTypeLabel(type)}
                                            </span>
                                            <div className="h-px flex-1 bg-border" />
                                        </div>

                                        {/* Group Items */}
                                        <div className="space-y-1">
                                            {items.map((result) => {
                                                console.log('Rendering item:', result);
                                                return (
                                                    <div
                                                        key={`${result.type}-${result.id}`}
                                                        className="group relative flex cursor-pointer items-center gap-3 rounded-lg border border-transparent px-3 py-2.5 text-sm transition-all select-none hover:border-border hover:bg-accent/50 hover:shadow-sm"
                                                        onClick={() => {
                                                            console.log('Clicked!', result);
                                                            handleSelect(result.url);
                                                        }}
                                                    >
                                                        {/* Icon with background */}
                                                        <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary transition-colors group-hover:bg-primary/20">
                                                            {getIcon(result.type)}
                                                        </div>

                                                        {/* Content */}
                                                        <div className="flex min-w-0 flex-1 flex-col">
                                                            <span className="truncate font-medium text-foreground">{result.title}</span>
                                                            <span className="truncate text-xs text-muted-foreground">{result.subtitle}</span>
                                                        </div>

                                                        {/* Arrow indicator on hover */}
                                                        <div className="shrink-0 opacity-0 transition-opacity group-hover:opacity-100">
                                                            <svg
                                                                className="h-4 w-4 text-muted-foreground"
                                                                fill="none"
                                                                stroke="currentColor"
                                                                viewBox="0 0 24 24"
                                                            >
                                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                                            </svg>
                                                        </div>
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    ) : (
                        !isLoading && query.length >= 2 && <div className="py-6 text-center text-sm text-muted-foreground">No results found</div>
                    )}
                </CommandList>
            </CommandDialog>
        </>
    );
}
