import React, { useState, useEffect } from "react";
import axios from "axios";
import ToastNotification, {
    showSuccessToast,
    showErrorToast,
} from "@/Components/Notification/ToastNotification";
const API_URL = import.meta.env.VITE_API_URL;

function VariableSettings() {
    const [formData, setFormData] = useState({
        vat_percentage: "",
        sscl_percentage: "",
    });
    const [settingId, setSettingId] = useState(null); // store ID if record exists
    const [loading, setLoading] = useState(true);
    useEffect(() => {
        // Fetch existing settings
        axios
            .get(`${API_URL}/variableSettings/index`)
            .then((response) => {
                if (response.data && response.data.id) {
                    setFormData({
                        vat_percentage: response.data.vat_percentage,
                        sscl_percentage: response.data.sscl_percentage,
                    });
                    setSettingId(response.data.id);
                }
            })
            .catch((error) => {
                console.error("Failed to fetch variable settings:", error);
            })
            .finally(() => setLoading(false));
    }, []);

    const handleChange = (e) => {
        const { id, value } = e.target;
        setFormData((prevData) => ({
            ...prevData,
            [id]: value,
        }));
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        const method = settingId ? "put" : "post";
        const url = settingId
            ? `${API_URL}/variableSettings/update/${settingId}`
            : `${API_URL}/variableSettings/store`;

        axios[method](url, formData)
            .then((response) => {
                showSuccessToast("Data saved successfully!");
                if (!settingId && response.data.id) {
                    setSettingId(response.data.id); // update id after first save
                }
            })
            .catch((error) => {
                console.error("Error saving data:", error);
                showErrorToast("Failed to save data. Please try again.");
            });
    };

    if (loading) return <div className="p-5">Loading...</div>;

    return (
        <>
            <ToastNotification />{" "}
            <div className="grid lg:grid-cols-2 md:grid-cols-1 mobile:grid-cols-1 gap-4 bg-white p-5">
                <div className="bg-slate-100 rounded-lg p-4 shadow-lg">
                    <div>
                        <h2 className="text-lg font-semibold mb-2">
                            Variable Settings
                        </h2>
                    </div>
                    <div className="mb-4">
                        <form onSubmit={handleSubmit}>
                            <div className="flex flex-col space-y-2">
                                <label htmlFor="vat_percentage">
                                    VAT Percentage %
                                </label>
                                <input
                                    type="text"
                                    id="vat_percentage"
                                    value={formData.vat_percentage}
                                    onChange={handleChange}
                                    className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                    required
                                />
                                <label htmlFor="sscl_percentage">
                                    SSCL Percentage %
                                </label>
                                <input
                                    type="text"
                                    id="sscl_percentage"
                                    value={formData.sscl_percentage}
                                    onChange={handleChange}
                                    className="py-2.5 px-4 block w-full border-gray-200 rounded-lg sm:text-sm"
                                    required
                                />
                                <div className="flex justify-center mt-10">
                                    <button
                                        type="submit"
                                        className="bg-blue-600 px-2 py-1 rounded text-white w-32 hover:bg-blue-700 h-10"
                                    >
                                        Save
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </>
    );
}

export default VariableSettings;
