import {
    useEffect,
    useState,
} from 'react';

import { RefreshCw } from 'lucide-react';

import { rpc } from '@/api/request';
import {
    StructureType,
    VizDataType,
} from '@/api/types';
import { ColCSS } from '@/components/CollectionFields/components/GridCss';
import ShortViewLL from '@/components/ShortViewLL';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardAction,
    CardContent,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Lang } from '@/lang/Lang';
import { cn } from '@/lib/utils';

import VizBarChartItem from './Items/VizBarChartItem';
import VizCardItem from './Items/VizCardItem';
import VizLineChartItem from './Items/VizLineChartItem';
import VizPieChartItem from './Items/VizPieChartItem';
import VizRadarChartItem from './Items/VizRadarChartItem';
import VizRFMItem from './Items/VizRFMItem';

type VizItemProps = {
    structure: StructureType | null,
    search: string | null,
    collection: string,
    filter: any,
    pipeline: any,
}

const VizItem = (props: VizItemProps) => {

    const { structure, search, collection, filter, pipeline } = props;

    if (!structure) return <></>;

    if (structure.type != 'viz' || !structure.inAdmin) {
        return <></>
    }

    const [data, setData] = useState<VizDataType | null>(null);

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

    useEffect(() => {

        setLoading(true);
        rpc.dataViz({
            collection: collection,
            viz: structure.key!,
            search: !!search ? search : undefined,
            filter: filter,
            pipeline: pipeline,
        })
            .then((data) => {
                setData(data.result ?? null);
            })
            .catch((error) => {
                console.log('error', error);
            })
            .finally(() => {
                setLoading(false);
            });
    }, [collection, structure.key, search, filter, pipeline]);



    const [refresh, setRefresh] = useState<boolean>(false);


    const isKpiCard = !!data?.vizCard;

    return <ColCSS col={structure.col ?? 24} row={structure.row}>
        <Card className="h-full gap-0 overflow-hidden rounded-xl border-border/60 p-0 shadow-sm ring-1 ring-black/[0.03] dark:ring-white/[0.05]">
            <CardHeader className="grid-rows-1 items-center gap-0 border-b border-border/50 bg-muted/20 px-4 py-2 !pb-2">
                <CardTitle className="min-w-0 text-[11px] font-medium uppercase leading-none tracking-wider text-muted-foreground">
                    <ShortViewLL
                        value={structure.title ?? ''}
                        truncateByWidth
                    />
                </CardTitle>
                <CardAction className="row-span-1 self-center">
                    <Button
                        size="icon-sm"
                        variant="ghost"
                        className="size-7 opacity-60 hover:opacity-100"
                        tooltip={Lang.key('refresh_viz')}
                        aria-label={Lang.key('refresh_viz')}
                        onClick={() => {
                            setRefresh(true);
                            rpc.dataViz({
                                collection: collection,
                                viz: structure.key!,
                            }).then((data) => {
                                setData(data.result ?? null);
                            }).finally(() => {
                                setRefresh(false);
                            });
                        }}>
                        <RefreshCw className={cn('size-3', refresh && 'animate-spin text-muted-foreground')} />
                    </Button>
                </CardAction>
            </CardHeader>
            <CardContent className="px-5 pb-5 pt-4">
                {loading && (
                    <Skeleton className={cn(
                        'w-full rounded-lg bg-muted/40 h-16',
                    )} />
                )}
                {!loading && data?.vizCard && <VizCardItem item={data.vizCard} />}
                {!loading && data?.vizLineChart && <VizLineChartItem items={data.vizLineChart.items ?? []} />}
                {!loading && data?.vizBarChart && <VizBarChartItem items={data.vizBarChart.items ?? []} />}
                {!loading && data?.vizPieChart && <VizPieChartItem items={data.vizPieChart.items ?? []} />}
                {!loading && data?.vizRadarChart && <VizRadarChartItem items={data.vizRadarChart.items ?? []} />}
                {!loading && data?.vizRFM && <VizRFMItem ranges={data.vizRFM.ranges ?? {}} items={data.vizRFM.items ?? []} />}
            </CardContent>
        </Card>
    </ColCSS >
}

export default VizItem;
