import {useEffect, useState} from 'react'
import type {SubmitHandler} from 'react-hook-form'
import {useForm} from 'react-hook-form'

import useApiUrlStore from '../../../app/store/apiStore'
import {Slider} from '../../../components/atoms'
import {FormInput, Modal, Toast} from '../../../components/mollecules'
import type {MoneyManagement} from '../../../generated/ManagingApi'
import {MoneyManagementClient, Timeframe,} from '../../../generated/ManagingApi'
import type {IMoneyManagementFormInput, IMoneyManagementModalProps,} from '../../../global/type'

const MoneyManagementModal: React.FC<IMoneyManagementModalProps> = ({
                                                                        showModal,
                                                                        onClose,
                                                                        moneyManagement,
                                                                        disableInputs = false,
                                                                    }) => {
    const [takeProfit, setTakeProfit] = useState<number>(20)
    const [name, setName] = useState<string>('')
    const [stopLoss, setStopLoss] = useState<number>(10)
    const [leverage, setLeverage] = useState<number>(1)
    const [timeframe, setTimeframe] = useState<Timeframe>(
        Timeframe.FifteenMinutes
    )
    const {reset, register, handleSubmit} = useForm<IMoneyManagementFormInput>()
    const {apiUrl} = useApiUrlStore()

    async function createMoneyManagement(form: IMoneyManagementFormInput) {
        const t = new Toast('Creating settings')
        const client = new MoneyManagementClient({}, apiUrl)
        const mm: MoneyManagement = {
            leverage: leverage,
            name: name,
            stopLoss: stopLoss / 100,
            takeProfit: takeProfit / 100,
            timeframe: form.timeframe,
        }

        await client
            .moneyManagement_PostMoneyManagement(mm)
            .then(() => {
                t.update('success', 'Settings created')
            })
            .catch((err) => {
                t.update('error', 'Error :' + err)
            })
    }

    const onSubmit: SubmitHandler<IMoneyManagementFormInput> = async (form) => {
        // @ts-ignore
        await createMoneyManagement(form)
        onClose()
    }

    function onChangeName(e: any) {
        setName(e.target.value)
    }

    function onTakeProfitChange(e: any) {
        setTakeProfit(e.target.value)
    }

    function onStopLossChange(e: any) {
        setStopLoss(e.target.value)
    }

    function onLeverageChange(e: any) {
        setLeverage(e.target.value)
    }


    useEffect(() => {
        if (moneyManagement) {
            console.log(moneyManagement)
            setTakeProfit(moneyManagement.takeProfit * 100)
            setStopLoss(moneyManagement.stopLoss * 100)
            setLeverage(moneyManagement.leverage)
            setTimeframe(moneyManagement.timeframe)
            setName(moneyManagement.name)

            const defaultValues: MoneyManagement = {
                leverage: moneyManagement.leverage,
                name: moneyManagement.name || '',
                stopLoss: moneyManagement.stopLoss,
                takeProfit: moneyManagement.takeProfit,
                timeframe: moneyManagement.timeframe,
            }
            reset({...defaultValues})
        }
    }, [showModal, moneyManagement])

    return (
        <Modal
            titleHeader="Money Management"
            showModal={showModal}
            onClose={onClose}
            onSubmit={handleSubmit(onSubmit)}
        >
            <FormInput label="Name" htmlFor="name">
                <input
                    value={name}
                    type="text"
                    placeholder="Ex: HighRiskMoneyManagement"
                    className="input input-bordered w-full max-w-xs"
                    {...register('name')}
                    onChange={onChangeName}
                    disabled={disableInputs}
                />
            </FormInput>

            <FormInput label="Timeframe" htmlFor="timeframe">
                <select
                    className="select w-full max-w-xs"
                    {...register('timeframe', {
                        disabled: disableInputs,
                        value: timeframe,
                    })}
                >
                    {Object.keys(Timeframe).map((item) => (
                        <option key={item} value={item}>
                            {item}
                        </option>
                    ))}
                </select>
            </FormInput>

            <FormInput label="TP%" htmlFor="takeProfit">
                <Slider
                    id="takeProfit"
                    value={takeProfit}
                    onChange={onTakeProfitChange}
                    step="0.01"
                    max="15"
                    suffixValue="%"
                    disabled={disableInputs}
                ></Slider>
            </FormInput>

            <FormInput label="SL%" htmlFor="stopLoss">
                <Slider
                    id="stopLoss"
                    value={stopLoss}
                    onChange={onStopLossChange}
                    step="0.01"
                    max="15"
                    suffixValue="%"
                    disabled={disableInputs}
                ></Slider>
            </FormInput>

            <FormInput label="Leverage" htmlFor="leverage">
                <Slider
                    id="leverage"
                    value={leverage}
                    onChange={onLeverageChange}
                    step="1"
                    min="1"
                    max="50"
                    prefixValue="x"
                    disabled={disableInputs}
                ></Slider>
            </FormInput>

            <div className="form-control mb-5">
                <div className="input-group">
                    <label htmlFor="leverage" className="form-label">
                        Risk reward
                    </label>
                    <div className="ml-4">{(takeProfit / stopLoss).toFixed(2)}</div>
                </div>
            </div>
            {disableInputs ? null : (
                <div className="modal-action">
                    <button type="submit" className="btn">
                        Build
                    </button>
                </div>
            )}
        </Modal>
    )
}

export default MoneyManagementModal
