import React, { useEffect, useState, useMemo } from "react";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from "./ui/sheet";
import { ScrollArea } from "./ui/scroll-area";
import { Switch } from "./ui/switch";
import { Badge } from "./ui/badge";
import { Loader2, Terminal, Sparkles, Coins, Shield, Backpack, TrendingUp, MessageSquare, User } from "lucide-react";
import { cn } from "../lib/utils";
import { toast } from "sonner";

interface Command {
    name: string;
    category: string;
}

interface CommandsDrawerProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
}

// Category metadata for visual styling
const CATEGORY_CONFIG: Record<string, { label: string; color: string; icon: React.ElementType }> = {
    admin: { label: "Admin", color: "bg-red-500/20 text-red-400 border-red-500/30", icon: Shield },
    economy: { label: "Economy", color: "bg-amber-500/20 text-amber-400 border-amber-500/30", icon: Coins },
    leveling: { label: "Leveling", color: "bg-emerald-500/20 text-emerald-400 border-emerald-500/30", icon: TrendingUp },
    inventory: { label: "Inventory", color: "bg-blue-500/20 text-blue-400 border-blue-500/30", icon: Backpack },
    quest: { label: "Quests", color: "bg-purple-500/20 text-purple-400 border-purple-500/30", icon: Sparkles },
    feedback: { label: "Feedback", color: "bg-cyan-500/20 text-cyan-400 border-cyan-500/30", icon: MessageSquare },
    user: { label: "User", color: "bg-pink-500/20 text-pink-400 border-pink-500/30", icon: User },
    uncategorized: { label: "Other", color: "bg-zinc-500/20 text-zinc-400 border-zinc-500/30", icon: Terminal },
};

export function CommandsDrawer({ open, onOpenChange }: CommandsDrawerProps) {
    const [commands, setCommands] = useState<Command[]>([]);
    const [enabledState, setEnabledState] = useState<Record<string, boolean>>({});
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState<string | null>(null);

    // Fetch commands and their enabled state
    useEffect(() => {
        if (open) {
            setLoading(true);
            Promise.all([
                fetch("/api/settings/meta").then(res => res.json()),
                fetch("/api/settings").then(res => res.json()),
            ]).then(([meta, config]) => {
                setCommands(meta.commands || []);
                // Build enabled state from config.commands (undefined = enabled by default)
                const state: Record<string, boolean> = {};
                for (const cmd of meta.commands || []) {
                    state[cmd.name] = config.commands?.[cmd.name] !== false;
                }
                setEnabledState(state);
            }).catch(err => {
                toast.error("Failed to load commands", {
                    description: "Unable to fetch command list. Please try again."
                });
                console.error(err);
            }).finally(() => {
                setLoading(false);
            });
        }
    }, [open]);

    // Group commands by category
    const groupedCommands = useMemo(() => {
        const groups: Record<string, Command[]> = {};
        for (const cmd of commands) {
            const cat = cmd.category || "uncategorized";
            if (!groups[cat]) groups[cat] = [];
            groups[cat].push(cmd);
        }
        // Sort categories: admin first, then alphabetically
        const sortedCategories = Object.keys(groups).sort((a, b) => {
            if (a === "admin") return -1;
            if (b === "admin") return 1;
            return a.localeCompare(b);
        });
        return sortedCategories.map(cat => ({ category: cat, commands: groups[cat]! }));
    }, [commands]);

    // Toggle command enabled state
    const toggleCommand = async (commandName: string, enabled: boolean) => {
        setSaving(commandName);
        try {
            const response = await fetch("/api/settings", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    commands: {
                        [commandName]: enabled,
                    },
                }),
            });

            if (!response.ok) throw new Error("Failed to save");

            setEnabledState(prev => ({ ...prev, [commandName]: enabled }));
            toast.success(`/${commandName} ${enabled ? "enabled" : "disabled"}`, {
                description: `Command has been ${enabled ? "enabled" : "disabled"} successfully.`,
                duration: 2000,
                id: "command-toggle",
            });
        } catch (error) {
            toast.error("Failed to toggle command", {
                description: "Unable to update command status. Please try again."
            });
            console.error(error);
        } finally {
            setSaving(null);
        }
    };

    return (
        <Sheet open={open} onOpenChange={onOpenChange} modal={false}>
            <SheetContent side="right" className="w-[800px] sm:max-w-[800px] p-0 flex flex-col gap-0 border-l border-border/50 glass-card bg-background/95 text-foreground">
                <SheetHeader className="p-6 border-b border-border/50">
                    <SheetTitle className="flex items-center gap-2">
                        <Terminal className="w-5 h-5 text-primary" />
                        Command Manager
                    </SheetTitle>
                    <SheetDescription>
                        Enable or disable commands. Changes take effect immediately.
                    </SheetDescription>
                </SheetHeader>

                {loading ? (
                    <div className="flex-1 flex items-center justify-center">
                        <Loader2 className="w-8 h-8 animate-spin text-primary" />
                    </div>
                ) : (
                    <div className="flex-1 min-h-0 overflow-hidden">
                        <ScrollArea className="h-full">
                            <div className="space-y-6 p-6 pb-8">
                                {groupedCommands.map(({ category, commands: cmds }) => {
                                    const config = (CATEGORY_CONFIG[category] ?? CATEGORY_CONFIG.uncategorized)!;
                                    const IconComponent = config.icon;

                                    return (
                                        <div key={category} className="space-y-3">
                                            {/* Category Header */}
                                            <div className="flex items-center gap-2">
                                                <IconComponent className="w-4 h-4 text-muted-foreground" />
                                                <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
                                                    {config.label}
                                                </h3>
                                                <Badge variant="outline" className="text-[10px] px-1.5 py-0">
                                                    {cmds.length}
                                                </Badge>
                                            </div>

                                            {/* Commands Grid */}
                                            <div className="grid grid-cols-2 gap-3">
                                                {cmds.map(cmd => {
                                                    const isEnabled = enabledState[cmd.name] !== false;
                                                    const isSaving = saving === cmd.name;

                                                    return (
                                                        <div
                                                            key={cmd.name}
                                                            className={cn(
                                                                "group relative rounded-lg overflow-hidden transition-all duration-300",
                                                                "bg-gradient-to-r from-card/80 to-card/40",
                                                                "border border-border/20 hover:border-border/40",
                                                                "hover:shadow-lg hover:shadow-primary/5",
                                                                "hover:translate-x-1",
                                                                !isEnabled && "opacity-40 grayscale",
                                                                isSaving && "animate-pulse"
                                                            )}
                                                        >
                                                            {/* Category color accent bar */}
                                                            <div className={cn(
                                                                "absolute left-0 top-0 bottom-0 w-1 transition-all duration-300",
                                                                config.color.split(' ')[0],
                                                                "group-hover:w-1.5"
                                                            )} />

                                                            <div className="p-3 pl-4 flex items-center justify-between">
                                                                <div className="flex items-center gap-3">
                                                                    {/* Icon with glow effect */}
                                                                    <div className={cn(
                                                                        "w-9 h-9 rounded-lg flex items-center justify-center",
                                                                        "bg-gradient-to-br",
                                                                        config.color,
                                                                        "shadow-sm",
                                                                        isEnabled && "group-hover:shadow-md group-hover:scale-105",
                                                                        "transition-all duration-300"
                                                                    )}>
                                                                        <IconComponent className="w-4 h-4" />
                                                                    </div>

                                                                    <div className="flex flex-col">
                                                                        <span className={cn(
                                                                            "font-mono text-sm font-semibold tracking-tight",
                                                                            "transition-colors duration-300",
                                                                            isEnabled ? "text-foreground" : "text-muted-foreground"
                                                                        )}>
                                                                            /{cmd.name}
                                                                        </span>
                                                                        <span className="text-[10px] text-muted-foreground/70 uppercase tracking-wider">
                                                                            {category}
                                                                        </span>
                                                                    </div>
                                                                </div>

                                                                <Switch
                                                                    checked={isEnabled}
                                                                    onCheckedChange={(checked) => toggleCommand(cmd.name, checked)}
                                                                    disabled={isSaving}
                                                                    className={cn(
                                                                        "transition-opacity duration-300",
                                                                        !isEnabled && "opacity-60"
                                                                    )}
                                                                />
                                                            </div>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        </div>
                                    );
                                })}

                                {groupedCommands.length === 0 && (
                                    <div className="text-center text-muted-foreground py-8">
                                        No commands found.
                                    </div>
                                )}
                            </div>
                        </ScrollArea>
                    </div>
                )}
            </SheetContent>
        </Sheet>
    );
}
