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

import dayjs from 'dayjs';
import { get } from 'lodash';
import {
    ArrowDownLeft,
    ArrowUpRight,
    CircleMinus,
    CirclePlus,
    FileSpreadsheet,
    Plus,
    Wallet,
    XIcon,
} from 'lucide-react';

import { rpc } from '@/api/request';
import {
    BalanceFPType,
    BalancePaymentType,
} from '@/api/types';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Empty,
    EmptyDescription,
    EmptyHeader,
    EmptyMedia,
    EmptyTitle,
} from '@/components/ui/empty';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
    MobileCard,
    MobileLink,
    MobileList,
    MobileListItem,
    MobileNavbar,
    MobilePage,
    MobilePopup,
} from '@/components/ui/mobile';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    Tabs,
    TabsContent,
    TabsList,
    TabsTrigger,
} from '@/components/ui/tabs';
import { confirmAlertRef } from '@/componentsRoot/ConfirmAlert';
import { exportDialogRef } from '@/componentsRoot/ExportDialog';
import { paymentDialogRef } from '@/componentsRoot/PaymentDialog';
import { toast } from '@/componentsRoot/ToastRoot';
import { Lang } from '@/lang/Lang';
import { cn } from '@/lib/utils';
import useAppConfigStore from '@/stores/appConfig';
import { useMainPage } from '@/stores/mainPage';

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

export const balanceAndPaymentDialogRef = createRef<BalanceAndPaymentDialogRefType>();

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


    const { profile } = useMainPage();

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




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


    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 filterOperations = (type: 'spend' | 'earn' | 'all') =>
        balanceOperations.filter((invoice) =>
            type === 'all'
                ? true
                : (invoice.amount ?? 0) > 0
                    ? type === 'earn'
                    : type === 'spend'
        );

    const operationCounts = {
        spend: filterOperations('spend').length,
        earn: filterOperations('earn').length,
        all: balanceOperations.length,
    };

    const formatOperationAmount = (amount?: number) => {
        const value = amount ?? 0;
        if (value > 0) return `+${value}`;
        return `${value}`;
    };

    const BalanceItem = ({ balance }: { balance: BalanceFPType }) => {
        const value = getBalanceValue(balance.path);
        const label = balance.field?.title ?? balance.field?.currency ?? '';
        const isNegative = Number(value) < 0;

        return (
            <div className="flex min-w-[280px] flex-1 flex-col gap-2 rounded-lg border bg-muted/20 px-3 py-2.5">
                <div className="flex items-center gap-3">
                    <div
                        className={cn(
                            'flex size-9 shrink-0 items-center justify-center rounded-full',
                            'bg-gradient-to-br from-primary/20 via-primary/10 to-primary/5',
                            'text-sm font-semibold leading-none text-primary',
                            'ring-1 ring-primary/20 shadow-sm'
                        )}
                    >
                        <span className="translate-y-px">
                            {balance.field?.currencySymbol
                                ?? balance.field?.currency?.slice(0, 1).toUpperCase()
                                ?? '—'}
                        </span>
                     </div>
                    <div className="min-w-0 flex-1">
                        <p className="truncate text-xs text-muted-foreground">{label}</p>
                        <p className={cn('truncate text-base font-semibold tabular-nums leading-tight', isNegative && 'text-destructive')}>
                            {value}
                            {balance.field?.currency && (
                                <span className="ml-1 text-xs font-normal text-muted-foreground">
                                    {balance.field.currency}
                                </span>
                            )}
                        </p>
                    </div>
                </div>
                <div className="flex flex-wrap gap-1.5">
                    <Button size="sm" variant="outline" onClick={() => onTopUpBalance(balance)}>
                        <Plus className="size-3.5" />
                        {Lang.key('top_up_balance')}
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => exportReport(balance)}>
                        <FileSpreadsheet className="size-3.5" />
                        {Lang.key('export_report')}
                    </Button>
                </div>
            </div>
        );
    };

    const PaymentTable = ({ type }: { type: 'spend' | 'earn' | 'all' }) => {
        const data = filterOperations(type);

        if (data.length === 0) {
            return (
                <Empty className="border-0 py-12">
                    <EmptyHeader>
                        <EmptyMedia variant="icon">
                            <Wallet />
                        </EmptyMedia>
                        <EmptyTitle>{Lang.key('not_found_payment')}</EmptyTitle>
                        <EmptyDescription>
                            {Lang.key('payment_history_description_one')}
                        </EmptyDescription>
                    </EmptyHeader>
                </Empty>
            );
        }

        return (
            <Table>
                <TableHeader className="sticky top-0 z-10 bg-background/95 backdrop-blur-sm">
                    <TableRow>
                        <TableHead className="w-[170px]">{Lang.key('date')}</TableHead>
                        <TableHead className="w-[140px]">{Lang.key('payment_type')}</TableHead>
                        <TableHead>{Lang.key('payment_description')}</TableHead>
                        <TableHead className="text-right">{Lang.key('payment_amount')}</TableHead>
                        <TableHead className="w-[90px] text-right">{Lang.key('payment_currency')}</TableHead>
                    </TableRow>
                </TableHeader>
                <TableBody>
                    {data.map((invoice) => {
                        const isEarn = (invoice.amount ?? 0) > 0;

                        return (
                            <TableRow key={invoice._id} className="hover:bg-muted/30">
                                <TableCell className="text-muted-foreground whitespace-nowrap">
                                    {!!invoice.created_at && dayjs.unix(invoice.created_at).format('DD.MM.YYYY HH:mm')}
                                </TableCell>
                                <TableCell>
                                    <Badge
                                        variant="outline"
                                        className={cn(
                                            'gap-1 font-normal',
                                            isEarn
                                                ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400'
                                                : 'border-orange-500/30 bg-orange-500/10 text-orange-700 dark:text-orange-400'
                                        )}
                                    >
                                        {isEarn ? (
                                            <ArrowUpRight className="size-3" />
                                        ) : (
                                            <ArrowDownLeft className="size-3" />
                                        )}
                                        {isEarn ? Lang.key('payment_earn') : Lang.key('payment_spend')}
                                    </Badge>
                                </TableCell>
                                <TableCell>
                                    <p className="text-sm leading-snug break-words whitespace-normal">
                                        {invoice.description || '—'}
                                    </p>
                                </TableCell>
                                <TableCell
                                    className={cn(
                                        'text-right font-medium tabular-nums',
                                        isEarn ? 'text-emerald-600 dark:text-emerald-400' : 'text-foreground'
                                    )}
                                >
                                    {formatOperationAmount(invoice.amount)}
                                </TableCell>
                                <TableCell className="text-right text-muted-foreground">
                                    {invoice.currency}
                                </TableCell>
                            </TableRow>
                        );
                    })}
                </TableBody>
            </Table>
        );
    };

    const TabCount = ({ count }: { count: number }) =>
        count > 0 ? (
            <span className="ml-1.5 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground tabular-nums">
                {count}
            </span>
        ) : null;

    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 } = useAppConfigStore();

    if (isMobile) {
        return <MobilePopup
            opened={open}
            onBackdropClick={() => setOpen(false)}
        >
            <MobilePage className="flex flex-col">
                <MobileNavbar

                    title={Lang.key('payment_and_balance')}
                    right={<MobileLink onClick={() => setOpen(false)}><XIcon /></MobileLink>}
                />




                <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);
                                    }}>
                                        <Plus />
                                    </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>




            </MobilePage>
        </MobilePopup>
    }

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent className="flex h-[80vh] w-[80vw] max-w-[80vw] flex-col gap-0 overflow-hidden p-0 sm:max-w-[80vw]">
                <DialogHeader className="shrink-0 border-b px-5 py-3">
                    <div className="flex items-center gap-2.5">
                        <Wallet className="size-4 text-muted-foreground" />
                        <div>
                            <DialogTitle className="text-base">{Lang.key('payment_and_balance')}</DialogTitle>
                            <DialogDescription className="text-xs">
                                {Lang.key('payment_history_description_one')}
                            </DialogDescription>
                        </div>
                    </div>
                </DialogHeader>

                <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
                    <div className="flex shrink-0 flex-wrap gap-3 border-b px-5 py-3">
                        {profile?.balances?.map((balance) => (
                            <BalanceItem key={balance.path ?? balance.field?.key} balance={balance} />
                        ))}
                    </div>

                    <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
                        <div className="flex shrink-0 items-center justify-between gap-4 border-b px-5 py-2.5">
                            <div>
                                <h3 className="text-sm font-medium">{Lang.key('payment_history')}</h3>
                                <p className="text-xs text-muted-foreground">
                                    {Lang.key('payment_history_description_two')}
                                </p>
                            </div>
                        </div>

                        <Tabs defaultValue="all" className="flex min-h-0 flex-1 flex-col gap-0">
                            <TabsList className="mx-5 mt-3 mb-0 h-auto w-fit shrink-0 flex-wrap gap-1 bg-muted/60 p-1">
                                <TabsTrigger value="all" className="gap-0 px-3">
                                    {Lang.key('all_operations')}
                                    <TabCount count={operationCounts.all} />
                                </TabsTrigger>
                                <TabsTrigger value="earn" className="gap-0 px-3">
                                    {Lang.key('earn_balance')}
                                    <TabCount count={operationCounts.earn} />
                                </TabsTrigger>
                                <TabsTrigger value="spend" className="gap-0 px-3">
                                    {Lang.key('spend_balance')}
                                    <TabCount count={operationCounts.spend} />
                                </TabsTrigger>
                            </TabsList>

                            <div className="min-h-0 flex-1 overflow-hidden px-5 py-3">
                                {(['all', 'earn', 'spend'] as const).map((tab) => (
                                    <TabsContent
                                        key={tab}
                                        value={tab}
                                        className="m-0 flex h-full min-h-0 flex-col overflow-hidden rounded-lg border"
                                    >
                                        <ScrollArea className="h-full">
                                            <PaymentTable type={tab} />
                                        </ScrollArea>
                                    </TabsContent>
                                ))}
                            </div>
                        </Tabs>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );

});