<script lang="ts">
    import { editorStore } from "$lib/stores/editor.svelte";
    import { KvButton, KvCheckbox } from "$lib/components/kuldvillak/ui";
    import { ConfirmDialog } from "$lib/components";
    import { trapFocus } from "$lib/utils/focusTrap";
    import * as m from "$lib/paraglide/messages";

    interface Props {
        roundIndex?: number;
        catIndex?: number;
        qIndex?: number;
        onClose: () => void;
        finalRound?: boolean;
    }

    let {
        roundIndex = 0,
        catIndex = 0,
        qIndex = 0,
        onClose,
        finalRound = false,
    }: Props = $props();

    // Get the original question data
    let originalQuestion = $derived(
        finalRound
            ? {
                  question: "",
                  answer: "",
                  imageUrl: "",
                  isDailyDouble: false,
                  points: 0,
              }
            : editorStore.getQuestion(roundIndex, catIndex, qIndex),
    );
    let category = $derived(
        finalRound
            ? null
            : editorStore.rounds[roundIndex]?.categories[catIndex],
    );
    let maxDD = $derived(
        finalRound
            ? 0
            : (editorStore.settings.dailyDoublesPerRound[roundIndex] ?? 1),
    );
    let currentDD = $derived(
        finalRound ? 0 : editorStore.countDailyDoubles(roundIndex),
    );

    // Local editing state (only saved when user clicks save)
    let localCategory = $state("");
    let localQuestion = $state("");
    let localAnswer = $state("");
    let localImageUrl = $state("");
    let localIsDailyDouble = $state(false);

    // Track if there are unsaved changes
    let hasChanges = $derived(
        finalRound
            ? localCategory !== editorStore.finalRound.category ||
                  localQuestion !== editorStore.finalRound.question ||
                  localAnswer !== editorStore.finalRound.answer
            : originalQuestion &&
                  (localQuestion !== originalQuestion.question ||
                      localAnswer !== originalQuestion.answer ||
                      localImageUrl !== (originalQuestion.imageUrl || "") ||
                      localIsDailyDouble !== originalQuestion.isDailyDouble),
    );

    // Can toggle DD (either already DD or have room for more)
    let canToggleDD = $derived(localIsDailyDouble || currentDD < maxDD);

    // Confirmation dialog state
    let showConfirmClose = $state(false);

    // Initialize local state when question changes
    $effect(() => {
        if (finalRound) {
            localCategory = editorStore.finalRound.category;
            localQuestion = editorStore.finalRound.question;
            localAnswer = editorStore.finalRound.answer;
        } else if (originalQuestion) {
            localQuestion = originalQuestion.question;
            localAnswer = originalQuestion.answer;
            localImageUrl = originalQuestion.imageUrl || "";
            localIsDailyDouble = originalQuestion.isDailyDouble;
        }
    });

    function handleSaveAndClose() {
        if (finalRound) {
            editorStore.updateFinalRound({
                category: localCategory,
                question: localQuestion,
                answer: localAnswer,
            });
        } else if (originalQuestion) {
            editorStore.updateQuestion(roundIndex, catIndex, qIndex, {
                question: localQuestion,
                answer: localAnswer,
                imageUrl: localImageUrl || undefined,
                isDailyDouble: localIsDailyDouble,
            });
        }
        onClose();
    }

    function handleCloseAttempt() {
        if (hasChanges) {
            showConfirmClose = true;
        } else {
            onClose();
        }
    }

    function handleDiscardAndClose() {
        showConfirmClose = false;
        onClose();
    }

    function handleSaveFromConfirm() {
        showConfirmClose = false;
        handleSaveAndClose();
    }

    function handleBackdropClick(e: MouseEvent) {
        if (e.target === e.currentTarget) handleCloseAttempt();
    }

    function handleKeydown(e: KeyboardEvent) {
        if (e.key === "Escape") handleCloseAttempt();
    }

    const CloseIcon = `<path d="M6.6188 19.4811L4.5188 17.3811L9.9188 11.9811L4.5188 6.61855L6.6188 4.51855L12.0188 9.91855L17.3813 4.51855L19.4813 6.61855L14.0813 11.9811L19.4813 17.3811L17.3813 19.4811L12.0188 14.0811L6.6188 19.4811Z"/>`;
</script>

{#if originalQuestion || finalRound}
    <div
        class="fixed inset-0 bg-kv-background/50 flex items-center justify-center z-50 p-2 md:p-8"
        onclick={handleBackdropClick}
        onkeydown={handleKeydown}
        role="dialog"
        tabindex="-1"
    >
        <div
            class="bg-kv-blue border-8 md:border-[16px] border-kv-black p-4 md:p-8 w-full max-w-2xl flex flex-col gap-4 md:gap-8 max-h-[95vh] overflow-y-auto"
            use:trapFocus
        >
            <!-- Header -->
            <div class="flex items-start justify-between gap-4">
                <h3
                    class="font-kv-body text-xl md:text-[28px] text-kv-white uppercase kv-shadow-text m-0"
                >
                    {#if finalRound}
                        {m.kv_edit_final_round()}
                    {:else}
                        {category?.name || m.kv_edit_category()} - {originalQuestion?.points}€
                    {/if}
                </h3>
                <button
                    onclick={handleCloseAttempt}
                    class="w-8 h-8 bg-transparent border-none cursor-pointer p-0 hover:opacity-70 text-kv-yellow"
                    aria-label={m.kv_settings_close()}
                >
                    <svg
                        viewBox="0 0 24 24"
                        fill="currentColor"
                        class="w-full h-full"
                    >
                        {@html CloseIcon}
                    </svg>
                </button>
            </div>

            <!-- Category Input (Final Round only) -->
            {#if finalRound}
                <div class="flex flex-col gap-2">
                    <label
                        for="q-category"
                        class="font-kv-body text-sm text-kv-white uppercase kv-shadow-text"
                    >
                        {m.kv_edit_category()}
                    </label>
                    <input
                        id="q-category"
                        type="text"
                        bind:value={localCategory}
                        placeholder={m.kv_edit_category()}
                        class="w-full bg-kv-black/50 border-4 border-kv-black px-4 py-2 font-kv-body text-lg text-kv-white outline-none placeholder:text-kv-white/50 uppercase"
                    />
                </div>
            {/if}

            <!-- Question Input -->
            <div class="flex flex-col gap-2">
                <label
                    for="q-text"
                    class="font-kv-body text-sm text-kv-white uppercase kv-shadow-text"
                >
                    {m.kv_edit_question()}
                </label>
                <textarea
                    id="q-text"
                    bind:value={localQuestion}
                    placeholder={m.kv_edit_question()}
                    rows={4}
                    class="w-full bg-kv-black/50 border-4 border-kv-black px-4 py-2 font-kv-body text-lg text-kv-white outline-none resize-none placeholder:text-kv-white/50 uppercase"
                ></textarea>
            </div>

            <!-- Answer Input -->
            <div class="flex flex-col gap-2">
                <label
                    for="q-answer"
                    class="font-kv-body text-sm text-kv-white uppercase kv-shadow-text"
                >
                    {m.kv_edit_answer()}
                </label>
                <textarea
                    id="q-answer"
                    bind:value={localAnswer}
                    placeholder={m.kv_edit_answer()}
                    rows={3}
                    class="w-full bg-kv-black/50 border-4 border-kv-black px-4 py-2 font-kv-body text-lg text-kv-white outline-none resize-none placeholder:text-kv-white/50 uppercase"
                ></textarea>
            </div>

            <!-- Image URL Input (not for final round) -->
            {#if !finalRound}
                <div class="flex flex-col gap-2">
                    <label
                        for="q-image"
                        class="font-kv-body text-sm text-kv-white uppercase kv-shadow-text"
                    >
                        {m.kv_edit_image_link()}
                    </label>
                    <input
                        id="q-image"
                        type="text"
                        bind:value={localImageUrl}
                        placeholder="https://example.com/image.jpg"
                        class="w-full bg-kv-black/50 border-4 border-kv-black px-4 py-2 font-kv-body text-lg text-kv-white outline-none placeholder:text-kv-white/50 uppercase"
                    />
                </div>

                <!-- Daily Double Toggle -->
                <div class="flex items-center gap-4">
                    <KvCheckbox
                        checked={localIsDailyDouble}
                        disabled={!canToggleDD && !localIsDailyDouble}
                        onclick={() =>
                            (localIsDailyDouble = !localIsDailyDouble)}
                    />
                    <span
                        class="font-kv-body text-lg text-kv-white uppercase kv-shadow-text"
                    >
                        {m.kv_edit_daily_double()}
                    </span>
                    <span class="font-kv-body text-sm text-kv-yellow">
                        ({currentDD}/{maxDD})
                    </span>
                </div>
            {/if}

            <!-- Save Button (left aligned) -->
            <div class="flex justify-start">
                <KvButton variant="secondary" onclick={handleSaveAndClose}>
                    {m.kv_settings_save_exit()}
                </KvButton>
            </div>
        </div>
    </div>
{/if}

<!-- Confirmation Dialog for unsaved changes -->
<ConfirmDialog
    bind:open={showConfirmClose}
    title={m.kv_confirm_close_title()}
    message={m.kv_confirm_close_message()}
    confirmText={m.kv_confirm_discard()}
    cancelText={m.kv_settings_save_exit()}
    onconfirm={handleDiscardAndClose}
    oncancel={handleSaveFromConfirm}
/>
