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

import dayjs from 'dayjs';
import { get } from 'lodash';
import {
    ArrowLeftIcon,
    CircleMinus,
    CirclePlus,
    CreditCardIcon,
    PlusCircleIcon,
    Save,
    Table2,
    User2Icon,
    XIcon,
} from 'lucide-react';
import { RiLockPasswordFill } from 'react-icons/ri';

import { rpc } from '@/api/request';
import {
    BalanceFPType,
    BalancePaymentType,
} from '@/api/types';
import CollectionFields from '@/components/CollectionFields/CollectionFields';
import { confirmAlertRef } from '@/components/ConfirmAlert';
import { exportDialogRef } from '@/components/ExportDialog';
import MenuItem from '@/components/MenuItem';
import { paymentDialogRef } from '@/components/PaymentDialog';
import { toast } from '@/components/ToastRoot';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
} from '@/components/ui/dialog';
import {
    Grid,
    GridCol,
    GridRow,
} from '@/components/ui/grid';
import {
    Item,
    ItemActions,
    ItemContent,
    ItemMedia,
    ItemTitle,
} from '@/components/ui/item';
import {
    MobileCard,
    MobileFab,
    MobileLink,
    MobileList,
    MobileListItem,
    MobileNavbar,
    MobilePage,
    MobilePopup,
} from '@/components/ui/mobile';
import {
    Table,
    TableBody,
    TableCaption,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    Tabs,
    TabsContent,
    TabsList,
    TabsTrigger,
} from '@/components/ui/tabs';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';

import { useMainPage } from '../../contexts/MainPageContext';
import ChangePasswordDialog from './components/ChangePasswordDialog';

type ProfileDialogRefType = {
    open: () => void;
    close: () => void;
}

export const profileDialogRef = createRef<ProfileDialogRefType>();

export const ProfileDialog = forwardRef<ProfileDialogRefType, {}>((_, ref) => {
    const [open, setOpen] = useState(false);


    const { profile, saveProfile } = useMainPage();

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

            valuesRef.current = profile?.data;


            setOpen(true);
        },
        close: () => setOpen(false),
    }));

    const valuesRef = React.useRef<any>({});

    const onSave = () => {
        saveProfile(valuesRef.current).then(() => {
            setOpen(false);
        });
    }

    const onSaveNewPassword = (password: string) => {

        saveProfile({
            password: password
        }).then(() => {
            toast.success(Lang.key('new_password_saved_successfully'));
            setPassEditModal(false);
        }).catch((error) => {
            toast.error(Lang.key('error_saving_new_password'));
        });
    }
    const [passEditModal, setPassEditModal] = useState<boolean>(false);


    const [selectMenu, setSelectMenu] = useState<string | null>(null);



    useEffect(() => {
        if (open && !isMobile && !selectMenu) {
            setSelectMenu("profile");
        }
    }, [open])

    const [balanceOperations, setBalanceOperations] = useState<BalancePaymentType[]>([]);

    useEffect(() => {

        if (open) {

            rpc.lastBalanceOperations().then((data) => {
                setBalanceOperations(data.result ?? []);

            });

        }

    }, [open])

    const getBalanceValue = (path?: string) => {

        if (!profile?.data) return 0;
        if (!path) return 0;
        return get(profile.data, path) ?? 0;
    }

    const PaymentTable = ({ type }: { type: "spend" | "earn" | "all" }) => {


        const data = balanceOperations.filter((invoice) => type == "all" ? true : (invoice.amount ?? 0) > 0 ? type == "earn" : type == "spend");

        return <Table className='w-full'>

            {data.length == 0 && <TableCaption>{Lang.key("not_found_payment")}</TableCaption>}
            <TableHeader>
                <TableRow>
                    <TableHead>{Lang.key('date')}</TableHead>
                    <TableHead>{Lang.key("payment_type")}</TableHead>
                    <TableHead>{Lang.key("payment_description")}</TableHead>
                    <TableHead className="text-right">{Lang.key("payment_amount")}</TableHead>
                    <TableHead className="text-right">{Lang.key("payment_currency")}</TableHead>
                </TableRow>
            </TableHeader>
            <TableBody>
                {data.map((invoice) => (
                    <TableRow key={invoice._id}>
                        <TableCell className="font-medium">
                            {!!invoice.created_at && dayjs.unix(invoice.created_at).format('DD.MM.YYYY HH:mm')}
                        </TableCell>
                        <TableCell>{(invoice.amount ?? 0) > 0 ? Lang.key("payment_earn") : Lang.key("payment_spend")}</TableCell>
                        <TableCell>
                            <div className="text-xs text-gray-500 break-words whitespace-normal">{invoice.description}</div>

                        </TableCell>
                        <TableCell className="text-right">{invoice.amount}</TableCell>
                        <TableCell className="text-right">{invoice.currency}</TableCell>
                    </TableRow>
                ))}
            </TableBody>

        </Table>


    }

    const exportReport = (balance: BalanceFPType) => {
        if (!balance.field?.currency) return;

        let loading = toast.loading(Lang.key('exporting_report'));
        rpc.makeStatementExport({
            currency: balance.field?.currency ?? '',
        }).then((data) => {
            toast.success(Lang.key('report_exported_successfully'));
            exportDialogRef.current?.open();
        }).catch((error) => {
            exportDialogRef.current?.open();
        }).finally(() => {
            toast.dismiss(loading);
        });
    }

    const onTopUpBalance = (balance: BalanceFPType) => {

        if (!balance.field?.gateways?.length) {

            confirmAlertRef.current?.open({
                title: Lang.key('no_gateways_available'),
                description: Lang.key('no_gateways_available_description'),
                buttons: [
                    { label: Lang.key('close'), onClick: () => { } },
                ]
            });

        } else {
            paymentDialogRef.current?.open({
                gateways: balance.field?.gateways ?? [],
            });
        }

    }

    const { isMobile } = useAppConfig();

    if (isMobile) {
        return <MobilePopup
            opened={open}
            onBackdropClick={() => setOpen(false)}
        >
            <MobilePage className="flex flex-col">
                <MobileNavbar
                    left={!!selectMenu && <MobileLink onClick={() => {
                        setSelectMenu(null);
                    }}><ArrowLeftIcon /></MobileLink>}
                    title={Lang.key('profile')}
                    right={<MobileLink onClick={() => setOpen(false)}><XIcon /></MobileLink>}
                />


                {!selectMenu && <MobileList outline>
                    <MobileListItem
                        onClick={() => {
                            setSelectMenu("profile");
                        }}
                        link
                        media={<User2Icon />}

                        title={Lang.key('profile')}
                    ></MobileListItem>
                    {profile?.changePassword && <MobileListItem
                        onClick={() => {
                            setPassEditModal(true);
                        }}
                        link
                        media={<RiLockPasswordFill />}
                        title={Lang.key('change_password')}
                    ></MobileListItem>}
                    {!!profile?.balances?.length && <MobileListItem
                        onClick={() => {
                            setSelectMenu("payment");
                        }}
                        link
                        media={<CreditCardIcon />}
                        title={Lang.key('payment_and_balance')}
                    ></MobileListItem>}
                </MobileList>}

                <div>

                    {selectMenu == "profile" && <>


                        {profile?.structure && <CollectionFields
                            structure={profile?.structure}
                            valuesRef={valuesRef}
                        />}

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



                    </>}

                    {selectMenu == "payment" && <div>

                        <div>
                            {profile?.balances?.map((e) => {
                                return <MobileCard outline


                                >

                                    <div className='flex items-center justify-between'>

                                        <div className='flex items-center gap-2 w-full'>
                                            <div
                                                className='w-10 h-10 rounded-full bg-gray-300 flex items-center justify-center'
                                            >
                                                <div className='text-2xl font-bold text-gray-500'>{e.field?.currencySymbol}</div>
                                            </div>

                                            <div className='text-lg font-medium'>{getBalanceValue(e?.path)}</div>
                                        </div>

                                        <Button onClick={() => {
                                            onTopUpBalance(e);
                                        }}>
                                            <PlusCircleIcon />
                                        </Button>

                                    </div>


                                </MobileCard>
                            })}
                        </div>


                        <div className='px-4'>

                            <div className='text-lg font-medium mt-4'>{Lang.key('payment_history')}</div>
                            <div className='text-xs text-gray-500'>{Lang.key('payment_history_description_one')}</div>
                            <div className='text-xs text-gray-500'>{Lang.key('payment_history_description_two')}</div>

                        </div>
                        <MobileList outline>
                            {balanceOperations.map((e) => {
                                return <MobileListItem key={e._id}
                                    dividers
                                    media={!!e.amount ? e.amount > 0 ? <CirclePlus /> : <CircleMinus /> : undefined}
                                    header={e.description}
                                    title={e.amount}
                                    after={e.currency}
                                    footer={e.created_at ? dayjs.unix(e.created_at).format('DD.MM.YYYY HH:mm') : ''}

                                >

                                </MobileListItem>
                            })}


                        </MobileList>


                    </div>}

                </div>



            </MobilePage>
            <ChangePasswordDialog open={passEditModal} onClose={() => setPassEditModal(false)} onSaveNewPassword={onSaveNewPassword} />
        </MobilePopup>
    }

    return (<>
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent className="!w-[80vw] !max-w-[80vw] sm:!max-w-[80vw] h-[80vh] overflow-hidden !p-0" >
                <Grid className='h-full w-full !w-[80vw] !max-w-[80vw] sm:!max-w-[80vw] h-[80vh]'>
                    <GridCol width="300px" className=' py-2 px-1 border-r'>


                        <GridRow className='px-2 py-4 flex flex-col '>

                            <MenuItem

                                active={selectMenu == "profile"}
                                onClick={() => {

                                    setSelectMenu("profile");

                                }}
                                label={Lang.key('profile')}
                                media={<User2Icon className='size-4' />}
                            />

                            {profile?.changePassword && <MenuItem


                                onClick={() => {

                                    setPassEditModal(true)

                                }}
                                label={Lang.key('change_password')}
                                media={<RiLockPasswordFill className='size-4' />}
                            />}

                            {!!profile?.balances?.length && <MenuItem

                                active={selectMenu == "payment"}
                                onClick={() => {

                                    setSelectMenu("payment")

                                }}
                                label={Lang.key('payment_and_balance')}
                                media={<CreditCardIcon className='size-4' />}
                            />}

                        </GridRow>


                    </GridCol>
                    {selectMenu == "profile" && <GridCol >
                        <GridRow className='flex flex-col'>


                            {profile?.structure && <CollectionFields
                                structure={profile?.structure}
                                valuesRef={valuesRef}
                            />}

                            <div className='px-4 flex justify-end mb-4'>
                                <Button onClick={onSave}>
                                    {Lang.key("save")}
                                </Button>
                            </div>

                        </GridRow>
                    </GridCol>}

                    {selectMenu == "payment" && <GridCol className='mt-6 px-4 ' >
                        <GridRow className='flex flex-col'>

                            <div>
                                {profile?.balances?.map((e) => {
                                    return <Item variant="outline" size="sm" asChild>
                                        <a href="#">
                                            <ItemMedia>
                                                <div
                                                    className='w-10 h-10 rounded-full bg-gray-300 flex items-center justify-center'
                                                >
                                                    <div className='text-2xl font-bold text-gray-500'>{e.field?.currencySymbol}</div>
                                                </div>
                                            </ItemMedia>
                                            <ItemContent>
                                                <ItemTitle className='text-lg font-medium'>{getBalanceValue(e?.path)}</ItemTitle>
                                            </ItemContent>
                                            <ItemActions>
                                                <Button
                                                    onClick={() => {
                                                        onTopUpBalance(e);
                                                    }}
                                                    variant="outline" size="sm">
                                                    <PlusCircleIcon /> {Lang.key("top_up_balance")}
                                                </Button>
                                                <Button

                                                    onClick={() => {
                                                        exportReport(e);
                                                    }}

                                                    variant="outline" size="sm">
                                                    <Table2 />  {Lang.key("export_report")}
                                                </Button>
                                            </ItemActions>
                                        </a>
                                    </Item>
                                })}
                            </div>



                            <div className='text-lg font-medium mt-4'>{Lang.key('payment_history')}</div>
                            <div className='text-xs text-gray-500'>{Lang.key('payment_history_description_one')}</div>
                            <div className='text-xs text-gray-500'>{Lang.key('payment_history_description_two')}</div>

                            <div className='mt-4 '>

                                <Tabs defaultValue="spend">
                                    <TabsList>
                                        <TabsTrigger value="spend">{Lang.key('spend_balance')}</TabsTrigger>
                                        <TabsTrigger value="earn">{Lang.key('earn_balance')}</TabsTrigger>
                                        <TabsTrigger value="all">{Lang.key('all_operations')}</TabsTrigger>
                                    </TabsList>
                                    <TabsContent value="spend">
                                        <PaymentTable type="spend" />
                                    </TabsContent>
                                    <TabsContent value="earn">
                                        <PaymentTable type="earn" />
                                    </TabsContent>
                                    <TabsContent value="all">
                                        <PaymentTable type="all" />
                                    </TabsContent>
                                </Tabs>
                            </div>

                        </GridRow>
                    </GridCol>}
                </Grid>








            </DialogContent>
        </Dialog>

        <ChangePasswordDialog open={passEditModal} onClose={() => setPassEditModal(false)} onSaveNewPassword={onSaveNewPassword} />

    </>


    )
});