<script setup lang="ts">
import { ref, computed } from "vue";
import Icon from "./Icon.vue";

const tomlContent = ref("");
const isGenerating = ref(false);
const error = ref<string | null>(null);
const activeTab = ref<"upload" | "edit">("upload");
const dragActive = ref(false);
const modalOpen = ref(false);

const hasContent = computed(() => tomlContent.value.trim().length > 0);

const openModal = () => {
    modalOpen.value = true;
};

const closeModal = () => {
    modalOpen.value = false;
    error.value = null;
    tomlContent.value = "";
    activeTab.value = "upload";
};

const handleFileUpload = (file: File) => {
    if (!file.name.endsWith(".toml")) {
        error.value = "Please upload a .toml file";
        return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
        const content = e.target?.result as string;
        tomlContent.value = content;
        error.value = null;
        activeTab.value = "edit";
    };
    reader.onerror = () => {
        error.value = "Error reading file";
    };
    reader.readAsText(file);
};

const handleDrop = (e: DragEvent) => {
    e.preventDefault();
    dragActive.value = false;

    const files = e.dataTransfer?.files;
    if (files && files.length > 0) {
        handleFileUpload(files[0]);
    }
};

const handleDragOver = (e: DragEvent) => {
    e.preventDefault();
    dragActive.value = true;
};

const handleDragLeave = (e: DragEvent) => {
    e.preventDefault();
    dragActive.value = false;
};

const handleFileInput = (e: Event) => {
    const target = e.target as HTMLInputElement;
    const files = target.files;
    if (files && files.length > 0) {
        handleFileUpload(files[0]);
    }
};

const downloadTemplate = async () => {
    try {
        const response = await fetch("/api/resume/template");
        if (!response.ok) {
            throw new Error("Failed to download template");
        }

        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);

        const link = document.createElement("a");
        link.href = url;
        link.download = "resume-template.toml";
        document.body.appendChild(link);
        link.click();

        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (err) {
        error.value = "Failed to download template";
    }
};

const generatePDF = async () => {
    if (!hasContent.value) {
        error.value = "Please provide TOML content";
        return;
    }

    isGenerating.value = true;
    error.value = null;

    try {
        const response = await fetch("/api/resume/generate", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ toml: tomlContent.value }),
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(
                errorText || `Failed to generate PDF: ${response.status}`,
            );
        }

        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);

        const link = document.createElement("a");
        link.href = url;
        link.download = "resume.pdf";
        document.body.appendChild(link);
        link.click();

        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (err) {
        console.error("Error generating PDF:", err);
        error.value =
            err instanceof Error ? err.message : "Failed to generate PDF";
    } finally {
        isGenerating.value = false;
    }
};

const loadTemplate = async () => {
    try {
        const response = await fetch("/api/resume/template");
        if (!response.ok) {
            throw new Error("Failed to load template");
        }

        const template = await response.text();
        tomlContent.value = template;
        activeTab.value = "edit";
        error.value = null;
    } catch (err) {
        error.value = "Failed to load template";
    }
};
</script>

<template>
    <!-- Floating Settings Button -->
    <button
        @click="openModal"
        class="fixed top-4 right-4 z-20 btn btn-secondary hover:btn-primary btn-circle"
        :class="$attrs.class"
        aria-label="Resume Settings"
    >
        <Icon name="settings" class="text-lg" />
    </button>

    <!-- Modal -->
    <div class="modal" :class="{ 'modal-open': modalOpen }">
        <div
            class="modal-box w-11/12 max-w-5xl h-[90vh] flex flex-col relative z-50"
        >
            <div class="flex justify-between items-center mb-4">
                <h3 class="font-bold text-lg">Resume Generator</h3>
                <button
                    @click="closeModal"
                    class="btn btn-circle btn-secondary hover:btn-primary"
                >
                    <Icon name="x" class="text-lg" />
                </button>
            </div>

            <div class="flex-1 overflow-hidden flex flex-col">
                <p class="text-base-content/70 mb-4">
                    Create a custom PDF resume from a TOML file. Download the
                    template, edit it with your information, and generate your
                    resume.
                </p>

                <!-- Action Buttons -->
                <div class="flex flex-wrap gap-2 mb-6">
                    <button
                        @click="downloadTemplate"
                        class="btn btn-primary btn-sm font-bold"
                    >
                        Download Template
                    </button>
                    <button
                        @click="loadTemplate"
                        class="btn btn-secondary btn-sm font-bold"
                    >
                        Load Template in Editor
                    </button>
                </div>

                <!-- Tabs -->
                <div class="flex justify-center mb-4">
                    <div
                        role="tablist"
                        class="inline-flex bg-base-300 border border-base-content/20 rounded-full p-1"
                    >
                        <button
                            role="tab"
                            class="px-4 py-2 rounded-full text-sm transition-all duration-200 font-bold"
                            :class="
                                activeTab === 'upload'
                                    ? 'btn btn-primary shadow-sm'
                                    : 'text-base-content/70 hover:text-base-content hover:bg-base-200'
                            "
                            @click="activeTab = 'upload'"
                        >
                            Upload TOML
                        </button>
                        <button
                            role="tab"
                            class="px-4 py-2 rounded-full text-sm font-bold transition-all duration-200"
                            :class="
                                activeTab === 'edit'
                                    ? 'btn btn-primary shadow-sm'
                                    : 'text-base-content/70 hover:text-base-content hover:bg-base-200'
                            "
                            @click="activeTab = 'edit'"
                        >
                            Edit TOML
                        </button>
                    </div>
                </div>

                <!-- Content Area -->
                <div class="flex-1 overflow-hidden">
                    <!-- Upload Tab -->
                    <div v-if="activeTab === 'upload'" class="h-full">
                        <div
                            class="border-2 border-dashed rounded-lg p-6 text-center transition-colors h-full flex items-center justify-center"
                            :class="
                                dragActive ? 'bg-primary/20' : 'border-primary'
                            "
                            @drop="handleDrop"
                            @dragover="handleDragOver"
                            @dragleave="handleDragLeave"
                        >
                            <div class="space-y-4">
                                <div>
                                    <p class="text-lg font-medium">
                                        Drop your TOML file here
                                    </p>
                                    <p class="text-base-content/70">
                                        or click below to browse
                                    </p>
                                </div>
                                <input
                                    type="file"
                                    accept=".toml"
                                    @change="handleFileInput"
                                    class="file-input file-input-primary file-input-sm w-full max-w-xs"
                                />
                            </div>
                        </div>
                    </div>

                    <!-- Edit Tab -->
                    <div
                        v-if="activeTab === 'edit'"
                        class="h-full flex flex-col space-y-2"
                    >
                        <div class="label">
                            <span class="label-text font-bold"
                                >TOML Content</span
                            >
                            <span class="label-text-alt">
                                Edit your resume data below
                            </span>
                        </div>
                        <textarea
                            class="textarea textarea-bordered flex-1 font-mono text-xs resize-none w-full min-h-0"
                            placeholder="Paste your TOML content here or load the template..."
                            v-model="tomlContent"
                        ></textarea>
                    </div>
                </div>

                <!-- Error Display -->
                <div v-if="error" class="alert alert-error mt-4">
                    <span class="text-sm">{{ error }}</span>
                </div>

                <!-- Generate Button -->
                <div v-if="hasContent" class="mt-4">
                    <button
                        @click="generatePDF"
                        :disabled="isGenerating"
                        class="btn btn-primary btn-sm w-full"
                    >
                        <template v-if="isGenerating">
                            <span
                                class="loading loading-spinner loading-xs"
                            ></span>
                            Generating PDF...
                        </template>
                        <template v-else> Generate Custom Resume PDF </template>
                    </button>
                </div>
            </div>
        </div>
        <div class="modal-backdrop" @click="closeModal"></div>
    </div>
</template>
