import { IconX } from "@tabler/icons-solidjs";
import { type Component, For } from "solid-js";
import { formatKey } from "./utils/formatKey";
import { sortKeys } from "./utils/sortKeys";

interface ShortcutItemProps {
    shortcut: string[];
    isEditing: boolean;
    currentKeys: string[];
    onEdit: () => void;
    onSave: () => void;
    onCancel: () => void;
}

export const ShortcutItem: Component<ShortcutItemProps> = (props) => {
    const renderKeys = (keys: string[]) => {
        const sortedKeys = sortKeys(keys);
        return (
            <For each={sortedKeys}>
                {(key) => (
                    <kbd class="px-2 py-1 text-sm font-semibold rounded  bg-neutral-100 border border-neutral-300 text-neutral-900 ">
                        {formatKey(key)}
                    </kbd>
                )}
            </For>
        );
    };

    return (
        <div class="flex">
            <div class="flex items-center gap-4">
                {props.isEditing ? (
                    <>
                        <div class="flex gap-1 min-w-[144px]">
                            {props.currentKeys.length > 0 ? (
                                renderKeys(props.currentKeys)
                            ) : (
                                <span class="text-neutral-500">
                                    Press keys...
                                </span>
                            )}
                        </div>
                        <div class="flex gap-2">
                            <button
                                type="button"
                                onClick={props.onSave}
                                disabled={props.currentKeys.length < 2}
                                class="px-3 py-1 text-sm rounded bg-neutral-900 text-white"
                            >
                                Save
                            </button>
                            <button
                                type="button"
                                onClick={props.onCancel}
                                class="p-1 rounded text-neutral-500"
                            >
                                <IconX class="w-4 h-4" />
                            </button>
                        </div>
                    </>
                ) : (
                    <>
                        <div class="flex gap-1">
                            {renderKeys(props.shortcut)}
                        </div>
                        <button
                            type="button"
                            onClick={props.onEdit}
                            class="px-3 py-1 text-sm rounded bg-neutral-200 text-neutral-700 "
                        >
                            Edit
                        </button>
                    </>
                )}
            </div>
        </div>
    );
};
