import { useForm } from '@inertiajs/react'
import { currency_types } from '@/constants/currency-types'
import CurrencyTypesSelector from '@/components/core/CurrencyTypesSelector'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Button } from '@/components/ui/button'
import Spinner2 from '@/components/core/Spinner2'
import { Save } from 'lucide-react'
import { useEffect } from 'react'
import { CurrencyType } from '@/types/dashboard/currency'
import { toast } from 'sonner'

type FormType = {
    website_currency_types: CurrencyType[],
    website_currency: string,
}

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

    const { data, setData, put, processing, errors } = useForm<FormType>({
        website_currency_types: [],
        website_currency: '',
    })

    function saveData() {
        if (data.website_currency_types.length < 1) {
            toast.warning('Select at least one currency type for display')
            return
        }

        if (!data.website_currency) {
            toast.warning('Select a default currency')
            return
        }

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

    // ✅ Only for initial load (safe)
    useEffect(() => {
        const parsed: CurrencyType[] = JSON.parse(currency_settings.website_currency_types || '[]')
        const defaultCurrency = String(currency_settings.website_currency || '')

        let updated = parsed

        const exists = parsed.some(c => c.code === defaultCurrency)

        if (defaultCurrency && !exists) {
            const found = currency_types.find(c => c.code === defaultCurrency)
            if (found) updated = [...parsed, found]
        }

        setData({
            website_currency_types: updated,
            website_currency: defaultCurrency
        })
    }, [currency_settings])

    // ✅ Controlled handler (NO useEffect needed)
    const handleCurrencyChange = (value: CurrencyType[]) => {
        let newDefault = data.website_currency

        const exists = value.some(c => c.code === newDefault)

        // if removed → reset default
        if (!exists) {
            newDefault = ''
        }

        setData({
            website_currency_types: value,
            website_currency: newDefault
        })
    }

    return (
        <div className="bg-card/60 border rounded-sm p-4 flex-1 space-y-4 h-fit">

            <CurrencyTypesSelector
                title="Display Currency Types"
                items={currency_types}
                selected={data.website_currency_types}
                onSelected={handleCurrencyChange}
                defaultCurrency={data.website_currency}
                edit={true}
                disabled={processing}
            />

            <div className="space-y-2">
                <Label>Website Default Currency</Label>

                <Select
                    value={data.website_currency}
                    onValueChange={(value) => {
                        // ✅ Only allow valid selection
                        const exists = data.website_currency_types.some(
                            c => c.code === value
                        )

                        if (!exists) return

                        setData('website_currency', value)
                    }}
                    disabled={processing}
                >
                    <SelectTrigger>
                        <SelectValue placeholder="Select default currency" />
                    </SelectTrigger>

                    <SelectContent>
                        {data.website_currency_types.map(currency => (
                            <SelectItem
                                key={currency.code}
                                value={currency.code}
                            >
                                {currency.code} - {currency.country}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>

                {errors.website_currency && (
                    <p className="text-red-600 text-sm">
                        {errors.website_currency}
                    </p>
                )}
            </div>

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