import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { PageProps } from "@/types";
import { Head, useForm } from "@inertiajs/react";
import React, { useState } from "react";
import TextInput from "@/Components/TextInput";
import InputError from "@/Components/InputError";
import PrimaryButton from "@/Components/PrimaryButton";
import InputLabel from "@/Components/InputLabel";

export default function Create({ auth }: PageProps) {
    const { setData, post, errors } = useForm<{ file: string | File }>({
        file: "",
    });
    const [processing, setProcessing] = useState(false);

    function submit(e: React.FormEvent<HTMLFormElement>) {
        e.preventDefault();
        setProcessing(true);
        post(route("admin.meals.store"), {
            forceFormData: true,
            onFinish: () => setProcessing(false), 
        });
    }

    function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
        e.preventDefault();
        if (e.currentTarget.files) {
            setData("file", e.currentTarget.files[0]);
        }
    }

    return (
        <AuthenticatedLayout user={auth.user} header={"Étlap feltöltés"} processing={processing}>
            <Head title="Étlap feltöltés" />

            <form
                onSubmit={submit}
                className="flex flex-col items-center justify-center w-full max-w-md mx-auto p-6 bg-babolygo-ocean rounded-lg shadow-md"
            >
                <InputLabel
                    className="block text-sm font-medium text-gray-700 mb-4"
                    htmlFor="file_input"
                >
                    Fájl feltöltése
                </InputLabel>
                <TextInput
                    className="block w-full text-sm text-gray-900 border border-gray-300 rounded-lg cursor-pointer bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    aria-describedby="file_input_help"
                    id="file_input"
                    type="file"
                    onChange={handleFileChange}
                />
                <p className="mt-2 text-sm text-gray-500" id="file_input_help">
                    Támogatott formátum: xlsx.
                </p>
                {errors.file && (
                    <InputError message={errors.file} className="mt-2" />
                )}
                <PrimaryButton type="submit" className="mt-6" disabled={processing}>
                    {processing ? "Feltöltés folyamatban..." : "Feltöltés"}
                </PrimaryButton>
            </form>
        </AuthenticatedLayout>
    );
}
