import { useForm } from "@inertiajs/react";
import { useEffect } from "react";
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Spinner } from "@/components/ui/spinner";
import { Save } from "lucide-react";
import { toast } from "sonner";
import { CurrencyType } from "@/types/dashboard/currency";

type CurrencyRate = {
    id?: number;
    base_currency: string;
    rates: Record<string, number | string>;
    updated_by?: string;
};

type Props = {
    rate: CurrencyRate | null;
    systemCurrency: string;
    open: boolean;
    setOpen: (val: boolean) => void;
    email: string;
    currencyType: CurrencyType[];
};

export default function ExchangeRateMaker({ rate, systemCurrency, open, setOpen, email, currencyType }: Props) {

    const { data, setData, post, put, processing, errors } =
        useForm<CurrencyRate>({
            base_currency: '',
            rates: {},
            updated_by: email,
        });


    const is_edit = rate !== null

    /**
     * Initialize rates dynamically from currency list
     */
    useEffect(() => {
        const initialRates: Record<string, number | string> = {};

        currencyType.forEach((c) => { initialRates[c.code] = rate?.rates?.[c.code] ?? 0; });

        setData({
            base_currency: systemCurrency,
            rates: initialRates,
            updated_by: rate?.updated_by || email,
        });
    }, [rate, currencyType]);

    /**
     * Handle input change
     */
    const handleRateChange = (code: string, value: string) => {


        setData("rates", {
            ...data.rates,
            [code]: value,
        });
    };

    const validate = () => {
        // base checks
        if (!data.base_currency) {
            toast.error("Base currency is required");
            return false;
        }

        if (!data.updated_by) {
            toast.error("Updated by is required");
            return false;
        }

        // rates validation
        for (const [code, value] of Object.entries(data.rates)) {
            if (value === null || value === undefined || value === 0) {
                toast.error(`${code} rate is required`);
                return false;
            }

            if (Number(value) <= 0) {
                toast.error(`${code} must be greater than 0`);
                return false;
            }
        }

        return true;
    };

    /**
     * Submit
     */
    const submit = () => {

        if (!validate()) {
            toast.error("Please enter valid rates for all currencies.");
            return
        }

        is_edit ? put(`/dashboard/exchange-rates/${rate.id}`, {
            onSuccess: () => {
                toast.success("Rates updated");
                handleClose();
            },
            onError: () => toast.error('Something went wrong'),
        }) : post(`/dashboard/exchange-rates`, {
            onSuccess: () => {
                toast.success("Rates saved");
                handleClose();
            },
            onError: () => toast.error('Something went wrong'),
        });

    };

    const handleClose = () => {
        setOpen(false);
    };

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
                <Button variant="outline" size="sm">
                    Add New Rate
                </Button>
            </DialogTrigger>

            <DialogContent>
                <DialogHeader>
                    <DialogTitle>{is_edit ? `Update (${rate?.id})` : 'Create'} Exchange Rates</DialogTitle>
                </DialogHeader>

                <div className="space-y-6">

                    {/* Base currency */}
                    <div className="flex gap-4 w-full">
                        <div className="space-y-1.5 flex-1">
                            <Label>System Currency</Label>
                            <div className="p-2 border rounded-sm bg-muted text-sm font-medium">
                                {data.base_currency || 'Worng'} (Locked)
                            </div>
                            {errors.base_currency && <span className="text-sm text-destructive">{errors.base_currency}</span>}
                        </div>

                        <div className="space-y-1.5 flex-1">
                            <Label>Updated By</Label>
                            <div className="p-2 border rounded-sm bg-muted text-sm font-medium">
                                {data.updated_by}
                            </div>
                            {errors.updated_by && <span className="text-sm text-destructive">{errors.updated_by}</span>}
                        </div>
                    </div>

                    {/* Dynamic currency inputs */}
                    <div className="space-y-3">
                        <Label>Rates</Label>

                        {currencyType.map((currency) => (
                            <div
                                key={currency.code}
                                className="flex gap-3 items-center"
                            >
                                <div className="w-20 p-1.5 text-sm border rounded-sm bg-muted text-center">
                                    {currency.code}
                                </div>

                                <Input
                                    type="number"
                                    value={data.rates[currency.code] ?? ""}
                                    onChange={(e) =>
                                        handleRateChange(
                                            currency.code,
                                            e.target.value
                                        )
                                    }
                                    placeholder={`Enter ${currency.name} rate`}
                                />
                            </div>
                        ))}


                        {errors.rates && <span className="text-sm text-destructive">{errors.rates}</span>}
                    </div>

                </div>

                <DialogFooter>
                    <Button variant="outline" onClick={handleClose}>
                        Close
                    </Button>

                    <Button onClick={submit} disabled={processing}>
                        {processing ? (
                            <>
                                <Spinner /> Saving...
                            </>
                        ) : (
                            <>
                                <Save /> Save
                            </>
                        )}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}