"use client"; // Mark as client component

import { Separator } from "@radix-ui/react-dropdown-menu";
import { useState } from "react";

export default function DatabaseSettings() {
    const [uploadStatus, setUploadStatus] = useState<string | null>(null);

    // Handle form submission
    const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault(); // Prevent default form submission

        const formData = new FormData(event.currentTarget);

        try {
            const response = await fetch("/api/db/upload", {
                method: "POST",
                body: formData,
            });

            if (response.ok) {
                setUploadStatus("Database uploaded successfully!");
            } else {
                const error = await response.json();
                setUploadStatus(error.message || "An error occurred during upload.");
            }
        } catch (error) {
            console.error("Error uploading the database:", error);
            setUploadStatus("An error occurred during upload.");
        }
    };

    return (
        <><div className="mb-8 flex w-full flex-col sm:flex-row">
            <div className="mb-4 w-full text-lg font-medium sm:w-1/3">
                Upload SQLite Database
            </div>
            <div className="w-full">
                <div className="mb-2">
                    <form onSubmit={handleSubmit} encType="multipart/form-data">
                        <input type="file" name="sqliteFile" accept=".db" required />
                        <button type="submit">Upload</button>
                    </form>
                    {uploadStatus && <p>{uploadStatus}</p>}
                </div>
            </div>
        </div>
            <div className="mb-8 flex w-full flex-col sm:flex-row">
                <div className="mb-4 w-full text-lg font-medium sm:w-1/3">
                    Download SQLite Database
                </div>
                <div className="w-full">
                    <div className="mb-2">
                        <a href="/api/db/download" download>
                            <button>Download</button>
                        </a>
                    </div>
                </div>
            </div>
        </>
    );
}

