"use client"; // Mark as client component

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

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

    const uploadDB = async (formData: FormData, setStatus: Dispatch<string>) => {
        try {
            const response = await fetch("/api/db/upload", {
                method: "POST",
                body: formData,
            });

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

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

        const formData = new FormData(event.currentTarget);
        uploadDB(formData, setUploadStatus);
    };

    const remoteCopy = async () => {

        const remoteUrl = "https://lifetracker.ryanpandya.com/api/db/download";

        setRemoteCopyStatus("Downloading...");
        const download = await fetch(remoteUrl);
        if (!download.ok) {
            throw new Error(`Failed to fetch from ${remoteUrl}: ${download.statusText}`);
        }

        const dbData = await download.blob();

        const formData = new FormData();
        formData.append('sqlFile', dbData, 'remoteDB-file.sql');
        uploadDB(formData, setRemoteCopyStatus);

        // 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="mt-8 mb-2 flex w-full flex-col sm:flex-row">
            <div className="mb-4 w-full text-lg font-medium sm:w-1/3">
                Upload Postgres SQL
            </div>
            <div className="w-full">
                <div className="mb-2">
                    <form onSubmit={handleSubmit} encType="multipart/form-data">
                        <input type="file" name="sqlFile" accept=".sql" required />
                        <button type="submit">Upload</button>
                    </form>
                    {uploadStatus && <p>{uploadStatus}</p>}
                </div>
            </div>
        </div>
            <div className="mb-2 flex w-full flex-col sm:flex-row">
                <div className="mb-4 w-full text-lg font-medium sm:w-1/3">
                    Download Postgres SQL
                </div>
                <div className="w-full">
                    <div className="mb-2">
                        <a href="/api/db/download" download>
                            <button>Download</button>
                        </a>
                    </div>
                </div>
            </div>
            {process.env.NODE_ENV === 'development' ?
                <div className="mb-2 flex w-full flex-col sm:flex-row">
                    <div className="mb-4 w-full text-lg font-medium sm:w-1/3">
                        Copy from Remote URL
                    </div>
                    <div className="w-full">
                        <div className="mb-2">
                            <button onClick={remoteCopy}>Copy</button>
                            {remoteCopyStatus && <p>{remoteCopyStatus}</p>}
                        </div>
                    </div>
                </div>
                : ""}
        </>
    );
}

