import React, {
    forwardRef,
    useImperativeHandle,
    useState,
} from 'react';

import _ from 'lodash';
import {
    Check,
    XIcon,
} from 'lucide-react';

import { rpc } from '@/api/request';
import { GatewayCDKTType } from '@/api/types';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';

import { toast } from './ToastRoot';
import { Button } from './ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from './ui/dialog';
import { Input } from './ui/input';
import { Label } from './ui/label';
import {
    MobileFab,
    MobileLink,
    MobileNavbar,
    MobilePage,
    MobilePopup,
} from './ui/mobile';
import {
    RadioGroup,
    RadioGroupItem,
} from './ui/radio-group';

type ActionOpenParams = {
    gateways: GatewayCDKTType[];
}

type PaymentDialogRefProps = {
    open: (params: ActionOpenParams) => void;
}

export const paymentDialogRef = React.createRef<PaymentDialogRefProps>();

const PaymentDialog = forwardRef<PaymentDialogRefProps, {}>((propd, ref) => {


    const { isMobile } = useAppConfig();



    const [open, setOpen] = useState<boolean>(false);


    const [loading, setLoading] = useState<boolean>(false);

    const [selectedGateway, setSelectedGateway] = useState<GatewayCDKTType | null>(null);
    const [amount, setAmount] = useState<number>(0);
    const [gateways, setGateways] = useState<GatewayCDKTType[]>([]);

    useImperativeHandle(ref, () => ({
        open: (params: ActionOpenParams) => {

            setGateways(params.gateways);
            setSelectedGateway(null);
            setAmount(0);
            setOpen(true);
        }
    }));

    const onPayNow = () => {
        if (!selectedGateway?.key) {

            toast.error(Lang.key('select_payment_method'));

            return;
        }
        if (!!selectedGateway.minAmount && amount < (selectedGateway.minAmount ?? 0)) {
            toast.error(Lang.key('amount_is_less_than_minimum'));
            return;
        }
        if (!!selectedGateway.maxAmount && amount > (selectedGateway.maxAmount ?? 0)) {
            toast.error(Lang.key('amount_is_greater_than_maximum'));
            return;
        }



        setLoading(true);
        rpc.generatePaymentLink({
            currency: selectedGateway?.currency ?? '',
            gateway: selectedGateway.key,
            amount: amount,
        }).then((data) => {
            if (data?.result) {
                window.open(data.result, '_blank');
            }

            setOpen(false);

        }).finally(() => {
            setLoading(false);
        })

    }



    const getLimitsString = (gateway: GatewayCDKTType) => {


        let result = [];
        if (!!gateway?.minAmount) {
            result.push(Lang.key("min_amount") + " " + gateway?.minAmount);
        }
        if (!!gateway?.maxAmount) {
            result.push(Lang.key("max_amount") + " " + gateway?.maxAmount);
        }
        return result.join(", ");
    }


    if (isMobile) {



        return <MobilePopup opened={open} onBackdropClick={() => setOpen(false)}>
            <MobilePage>
                <MobileNavbar title={Lang.key('select_payment_method')}

                    right={<MobileLink onClick={() => setOpen(false)}><XIcon /></MobileLink>}
                />


                <div className='m-4'>
                    <Label>{Lang.key('amount')}</Label>
                    <Input value={amount} onChange={(e) => {

                        if (isNaN(Number(e.target.value))) {
                            return;
                        }




                        setAmount(_.toNumber(e.target.value))

                    }} type="number" />
                </div>

                {!!selectedGateway && <div className='text-xs text-gray-500 m-4'>
                    {getLimitsString(selectedGateway)}
                </div>}

                <div className='m-4'>
                    <RadioGroup value={selectedGateway?.key ?? ''} onValueChange={(value) => setSelectedGateway(gateways.find((gateway) => gateway.key === value) ?? null)}>
                        {gateways.map((gateway) => {
                            return <div className="flex items-center gap-3">
                                <RadioGroupItem value={gateway.key ?? ''} id={gateway.key ?? ''} />
                                <Label htmlFor={gateway.key ?? ''}>{gateway.title ?? ''}</Label>
                            </div>
                        })}
                    </RadioGroup>

                </div>
                <MobileFab
                    onClick={onPayNow}
                    className="fixed left-1/2 bottom-safe-4 transform -translate-x-1/2 z-20"
                    icon={<Check />}
                    text={Lang.key('pay_now')}
                    textPosition="after"
                />

            </MobilePage>
        </MobilePopup>
    }


    return (
        <Dialog
            open={open}
            onOpenChange={(open) => setOpen(open)}

        >

            <DialogContent>
                <DialogHeader>
                    <DialogTitle>
                        {Lang.key('select_payment_method')}
                    </DialogTitle>
                </DialogHeader>

                <div>
                    <Label>{Lang.key('amount')}</Label>
                    <Input value={amount} onChange={(e) => {

                        if (isNaN(Number(e.target.value))) {
                            return;
                        }




                        setAmount(_.toNumber(e.target.value))

                    }} type="number" />
                </div>
                {!!selectedGateway && <div className='text-sm text-gray-500'>
                    {getLimitsString(selectedGateway)}
                </div>}

                <RadioGroup value={selectedGateway?.key ?? ''} onValueChange={(value) => setSelectedGateway(gateways.find((gateway) => gateway.key === value) ?? null)}>
                    {gateways.map((gateway) => {
                        return <div className="flex items-center gap-3">
                            <RadioGroupItem value={gateway.key ?? ''} id={gateway.key ?? ''} />
                            <Label htmlFor={gateway.key ?? ''}>{gateway.title ?? ''}</Label>
                        </div>
                    })}
                </RadioGroup>




                <DialogFooter>
                    <Button
                        disabled={!selectedGateway || !amount || loading}

                        onClick={onPayNow}>{Lang.key('pay_now')}</Button>
                    <Button onClick={() => setOpen(false)} variant="outline">{Lang.key('close')}</Button>
                </DialogFooter>

            </DialogContent>
        </Dialog>






    );
});

export default PaymentDialog;
