import { Inertia } from "@inertiajs/inertia";
import React, { useState, useEffect } from "react";

const ModalInput = ({ fields, tableName, options, initialData, onClose }) => {
    const [formData, setFormData] = useState({});
    const [errors, setErrors] = useState({});

    useEffect(() => {
        setFormData(initialData || {})
    }, [initialData]);

    const handleChange = (e) => {
        if (e.target.type === "file") {
            setFormData({ ...formData, [e.target.name]: e.target.files[0] });
        } else {
            setFormData({ ...formData, [e.target.name]: e.target.value });
        }
    };

    const handleSubmit = (e) => {
        e.preventDefault()
        // console.log("tableName:", tableName); 

        const formDataObj = new FormData()
        Object.keys(formData).forEach((key) => {
            if (key === 'foto' && !(formData[key] instanceof File)) {
                return
            }
            formDataObj.append(key, formData[key])
        })

        if (initialData) {
            Inertia.post(`/update${tableName}/${initialData.id}`, formDataObj, {
                forceFormData: true,
                onError: (errors) => setErrors(errors),
                onSuccess: () => {
                    document.getElementById('modal_input').checked = false
                    setFormData({})
                    setErrors({})
                    onClose({})
                }
            })
        } else {
            Inertia.post(`/add${tableName}`, formDataObj, {
                forceFormData: true,
                onError: (errors) => setErrors(errors),
                onSuccess: () => {
                    document.getElementById('modal_input').checked = false
                    setFormData({})
                    setErrors({})
                }
            })
        }
    }

    return (
        <div>
            <input type="checkbox" id="modal_input" className="modal-toggle" />
            <div className="modal" role="dialog">
                <div className="modal-box">
                    <h2 className="font-bold text-lg text-center mb-5">
                        {initialData ? "Edit Data" : "Tambah Data"}
                    </h2>
                    <form onSubmit={handleSubmit} encType="multipart/form-data">
                        {Object.keys(fields).map((field) => (
                            <div key={field} className="mb-2">
                                <label className="input input-bordered input-secondary flex items-center gap-2">
                                    {field.replace("_", " ")}
                                    {fields[field] === "select" ? (
                                        <select
                                            name={field}
                                            value={formData[field] || ""}
                                            onChange={handleChange}
                                            className="select select-bordered w-full select-secondary"
                                        >
                                            <option disabled value="">
                                                Pilih {field.replace("_", " ")}
                                            </option>
                                            {options[field] && Object.entries(options[field]).map(([key, value]) => (
                                                <option key={key} value={key}>{value}</option>
                                            ))}
                                        </select>
                                    ) : fields[field] === "file" ? (
                                        <input
                                            type="file"
                                            name={field}
                                            onChange={handleChange}
                                            className="file-input file-input-bordered w-full file-input-secondary"
                                        />
                                    ) : (
                                        <input
                                            type={fields[field]}
                                            name={field}
                                            value={formData[field] || ""}
                                            onChange={handleChange}
                                            className="grow border-none focus:ring-0"
                                            placeholder={`Masukkan ${field.replace("_", " ")}`}
                                        />
                                    )}
                                </label>
                                {errors[field] && <p className="text-red-500 text-sm">{errors[field]}</p>}
                            </div>
                        ))}

                        <button type="submit" className="btn btn-secondary">
                            {initialData ? "Simpan Perubahan" : "Tambah Data"}
                        </button>
                    </form>
                </div>
                <label className="modal-backdrop" htmlFor="modal_input">Close</label>
            </div>
        </div>
    );
};

export default ModalInput;


