

import Spinner2 from '@/components/core/Spinner2'
import SwitchField from '@/components/core/SwitchField'
import TimePicker from '@/components/core/TimePicker'
import { Button } from '@/components/ui/button'
import { useForm } from '@inertiajs/react'
import { Save } from 'lucide-react'
import { useEffect } from 'react'
import { toast } from 'sonner'

type FormType = {
    exchange_rate_update_auto: boolean,
    exchange_rate_update_time: string,
}

export default function ExchangeRateSettings({ currency_settings }: { currency_settings: Record<string, string> }) {

    const { data, setData, post, put, processing, errors } = useForm<FormType>({
        exchange_rate_update_auto: false,
        exchange_rate_update_time: '',
    })


    function saveData() {

        if (data.exchange_rate_update_auto && data.exchange_rate_update_time === '') {
            toast.warning('Select a time for automatic exchange rate updates');
            return
        }
        //  put(`/dashboard/meal-packages/${mealPackage.id}`, { onSuccess: () => toast.success('Sucsessfuly Updated the Meal Package'), onError: (error) => toast.error(error.message || 'Something Worng, Please try again') })

        put(`/dashboard/currency-settings/update`, {
            onSuccess: () => {
                toast.success('Settings updated successfully');
            },
            onError: () => {
                toast.error('Something went wrong, please try again');
            },
        });
    }

    useEffect(() => {
        setData({
            exchange_rate_update_auto: Boolean(currency_settings?.exchange_rate_update_auto === "1"),
            exchange_rate_update_time: String(currency_settings?.exchange_rate_update_time ?? ''),
        });
    }, [currency_settings]);


    return <div className="bg-card/60 border rounded-sm p-4 flex-1 space-y-4 h-fit">
        <div className="flex flex-1 flex-col justify-center gap-1 border-b pb-2 text-sm">
            <p>Exchange Rate Settings</p>
        </div>

        <SwitchField title='Auto Update' checked={data.exchange_rate_update_auto} onChecked={(value: boolean) => setData('exchange_rate_update_auto', value)} disabled={processing} description='If turned on, exchange rate will update automatically using API' />

        <TimePicker
            label='Exchange Rate Update Time'
            error={errors.exchange_rate_update_time}
            value={data.exchange_rate_update_time}
            onChange={(val) => setData("exchange_rate_update_time", val)}
            disabled={!data.exchange_rate_update_auto}
        />


        <div className='w-full justify-end flex'>
            <Button size='sm' onClick={saveData} disabled={processing}>
                {processing ? (<><Spinner2 /> Saving...</>) : (<><Save /> Save</>)}
            </Button>
        </div>

    </div>
}
