import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from "react-redux";
import {getRdsSettings, insertRdsSettings} from "../httpServices/httpServiceSettings";
import {isEmpty} from "../actions/settingActions";
import {destroyAlerts, errorAlert, savedAlert, savingAlert} from "../actions/alertActions";
import {saveLog} from "../httpServices/httpServiceLog";

const RdsForm = () => {
    const {settings, loading, error} = useSelector(state => state.settings)
    const [database, setDatabase] = useState('');
    const [endpoint, setEndpoint] = useState('');
    const [password, setPassword] = useState('');
    const [username, setUsername] = useState('');
    const [port, setPort] = useState('');
    const [isLoading, setLoading] = useState(false)
    const dispatch = useDispatch();

    useEffect(()=>{
        dispatch(getRdsSettings())
    },[dispatch])

    useEffect(()=>{
        if (!isEmpty(settings)){
            if (settings.success){
                setDatabase(settings.data.rds_database)
                setEndpoint(settings.data.rds_endpoint)
                setPassword(settings.data.rds_password)
                setUsername(settings.data.rds_username)
                setPort(settings.data.rds_port)
                setLoading(false)
            }
        }
    },[settings, setEndpoint, setPassword, setUsername, setPort, setDatabase, setLoading])

    useEffect(() => {
        if (isLoading){
            if (!loading){
                if (settings.success){
                    destroyAlerts()
                    savedAlert({
                        title: 'Success',
                        description: 'Data saved successfully!',
                    })
                    dispatch(saveLog({
                        title: "Save DB credentials",
                        content: "Saved claude database credentials",
                        activity: "Saved database credentials",
                    }))
                }else{
                    destroyAlerts()
                    errorAlert({
                        title: 'Error',
                        description: settings.message,
                    })
                    dispatch(saveLog({
                        title: "Incorrect DB credentials",
                        content: "Saving the Claude database credentials was incorrect.",
                        activity: "Error in save database credentials",
                    }))
                    setLoading(false)
                }
            }
        }
    }, [isLoading, settings, loading, dispatch]);

    const handleSubmit = (e) => {
        e.preventDefault();
        savingAlert({
            title: (<span className="ml-[10px] inline">Saving ...</span>),
            description: 'Be patient, RDS Credentials is saving',
        })

        if (!database || !endpoint || !username || !port || !password) {
            destroyAlerts()
            errorAlert({
                title: 'Error',
                description: "Please fill in all fields",
            })
            return;
        }
        const data = { database, endpoint, username, port, password }
        dispatch(insertRdsSettings(data));
        setLoading(true)
    };

    return (
        <div className="rounded-sm border border-stroke bg-white shadow-default dark:border-strokedark dark:bg-boxdark h-full">
            <div className="border-b border-stroke px-6.5 py-4 dark:border-strokedark">
                <h3 className="font-medium text-black dark:text-white">
                    RDS Credentials
                </h3>
            </div>
            <form onSubmit={handleSubmit} action="javaScript:void(0)">
                <div className="p-6.5">
                    <div className="mb-4.5">
                        <label className="mb-3 block text-sm font-medium text-black dark:text-white">Database</label>
                        <input
                            type="text"
                            placeholder="Enter Database Name"
                            value={database}
                            onChange={(e) => setDatabase(e.target.value)}
                            className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 font-normal text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                        />
                    </div>

                    <div className="mb-4.5">
                        <label className="mb-3 block text-sm font-medium text-black dark:text-white">Username</label>
                        <input
                            type="text"
                            placeholder="Enter RDS Username"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                            className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 font-normal text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                        />
                    </div>

                    <div className="mb-4.5">
                        <label className="mb-3 block text-sm font-medium text-black dark:text-white">Port</label>
                        <input
                            type="text"
                            placeholder="Enter RDS Port"
                            value={port}
                            onChange={(e) => setPort(e.target.value)}
                            className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 font-normal text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                        />
                    </div>

                    <div className="mb-4.5">
                        <label className="mb-3 block text-sm font-medium text-black dark:text-white">Endpoint</label>
                        <input
                            type="text"
                            placeholder="Enter RDS Endpoint"
                            value={endpoint}
                            onChange={(e) => setEndpoint(e.target.value)}
                            className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 font-normal text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                        />
                    </div>

                    <div className="mb-5.5">
                        <label className="mb-3 block text-sm font-medium text-black dark:text-white">Password</label>
                        <input
                            type="password"
                            placeholder="Enter RDS password"
                            autoComplete="new-password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 font-normal text-black outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                        />
                    </div>

                    <button className="flex w-full justify-center rounded bg-primary p-3 font-medium text-gray hover:bg-opacity-90">Save</button>
                </div>
            </form>
        </div>
    );
};

export default RdsForm;