import { useState } from 'react';

import {
    VizRFMCalulatedRangesType,
    VizRFMType,
} from '@/api/types';
import { Button } from '@/components/ui/button';
import { ButtonGroup } from '@/components/ui/button-group';
import {
    Tooltip,
    TooltipContent,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import { Lang } from '@/lang/Lang';
import { cn } from '@/lib/utils';

const numberItemClass = (number?: number | null) => {
    if (!number) return 'border-border/60 bg-muted/20 text-muted-foreground';
    if (number == 1) return 'border-destructive/40 bg-destructive/5 text-destructive';
    if (number == 2) return 'border-chart-2/40 bg-chart-2/5 text-chart-2';
    if (number == 3) return 'border-emerald-500/40 bg-emerald-500/5 text-emerald-600 dark:text-emerald-400';
    return 'border-border/60 bg-muted/20 text-muted-foreground';
};

const VizRFMItem = ({ items, ranges }: { items: VizRFMType[], ranges: VizRFMCalulatedRangesType }) => {

    const getSegmentTitle = (segment?: string) => {
        if (!segment) return '';
        return Lang.key(`viz_rfm_seg_${segment}_name`);
    }
    const getSegmentRecommendation = (segment?: string) => {
        if (!segment) return '';
        return Lang.key(`viz_rfm_seg_${segment}_rec`);
    }

    const getRTitle = (r?: number) => {

        if (!r) return '';

        if (r == 1) return Lang.key('viz_rfm_r_1');
        if (r == 2) return Lang.key('viz_rfm_r_2');
        if (r == 3) return Lang.key('viz_rfm_r_3');

        return '';


    }
    const getFTitle = (f?: number) => {
        if (!f) return '';
        if (f == 1) return Lang.key('viz_rfm_f_1');
        if (f == 2) return Lang.key('viz_rfm_f_2');
        if (f == 3) return Lang.key('viz_rfm_f_3');
        return '';
    }
    const getMTitle = (m?: number) => {
        if (!m) return '';
        if (m == 1) return Lang.key('viz_rfm_m_1');
        if (m == 2) return Lang.key('viz_rfm_m_2');
        if (m == 3) return Lang.key('viz_rfm_m_3');
        return '';
    }

    const [activeSegment, setActiveSegment] = useState<"leaving" | "sleeping" | "active">("active");

    const totalCount = items.reduce((acc, item) => acc + (item.count ?? 0), 0);


    const NumberItem = ({ number }: { number?: number | null }) => (
        <div className={cn(
            'min-w-7 rounded-md border px-2 py-0.5 text-center text-sm font-medium tabular-nums',
            numberItemClass(number),
        )}>
            {number ?? '-'}
        </div>
    );

    return (<>
        <div className='mb-4 flex w-full items-center justify-center'>
            <ButtonGroup >
                <Button size="sm" variant={activeSegment === "leaving" ? "default" : "outline"} onClick={() => setActiveSegment("leaving")}>{Lang.key('viz_rfm_tab_leaving')}</Button>
                <Button size="sm" variant={activeSegment === "sleeping" ? "default" : "outline"} onClick={() => setActiveSegment("sleeping")}>{Lang.key('viz_rfm_tab_sleeping')}</Button>
                <Button size="sm" variant={activeSegment === "active" ? "default" : "outline"} onClick={() => setActiveSegment("active")}>{Lang.key('viz_rfm_tab_active')}</Button>

            </ButtonGroup>
        </div>

        <div className='grid grid-cols-3 gap-4'>
            {items.map((item) => {

                if (activeSegment === "leaving" && item.r != 1) return null;
                if (activeSegment === "sleeping" && item.r != 2) return null;
                if (activeSegment === "active" && item.r != 3) return null;

                const percent = !!item.count && totalCount ? Math.round((item.count ?? 0) * 100 / totalCount) : 0;

                return <div
                    style={{
                        opacity: item.count ? 1 : 0.4,
                    }}
                    key={item.segment}
                    className='rounded-lg border border-border/60 bg-muted/10 p-3 transition-colors hover:bg-muted/20'>
                    <div className='my-1 flex items-center justify-center gap-2 text-center text-xl font-medium'>

                        <Tooltip>
                            <TooltipTrigger >
                                <NumberItem number={item.r} />
                            </TooltipTrigger>
                            <TooltipContent>
                                <p>{getRTitle(item.r)}</p>
                            </TooltipContent>
                        </Tooltip>
                        <Tooltip>
                            <TooltipTrigger >
                                <NumberItem number={item.f} />
                            </TooltipTrigger>
                            <TooltipContent>
                                <p>{getFTitle(item.f)}</p>
                            </TooltipContent>
                        </Tooltip>
                        <Tooltip>
                            <TooltipTrigger >
                                <NumberItem number={item.m} />
                            </TooltipTrigger>
                            <TooltipContent>
                                <p>{getMTitle(item.m)}</p>
                            </TooltipContent>
                        </Tooltip>

                    </div>
                    <div className='text-center text-xs font-medium text-muted-foreground'>{getSegmentTitle(item.segment)}</div>

                    <div className='text-center text-2xl font-semibold tabular-nums'>{percent}%</div>
                    <div className='mx-auto mt-2 h-1 w-full max-w-[80%] overflow-hidden rounded-full bg-muted'>
                        <div
                            className='h-full rounded-full bg-primary/60 transition-all'
                            style={{ width: `${percent}%` }}
                        />
                    </div>
                    <span className='mt-2 block text-center text-xs font-medium text-muted-foreground'>
                        {Lang.key('viz_rfm_count_label')} {item.count?.toLocaleString()}
                    </span>

                    <Tooltip>
                        <TooltipTrigger asChild>
                            <div className='cursor-pointer text-center text-xs font-medium text-primary'>{Lang.key('viz_rfm_recommendation')}</div>
                        </TooltipTrigger>
                        <TooltipContent>
                            <p className='max-w-96 text-center'>{getSegmentRecommendation(item.segment)}</p>
                        </TooltipContent>
                    </Tooltip>


                </div>
            })}

        </div>
        <div className='mt-4 px-4 text-center text-xs text-muted-foreground'>
            {Lang.key('viz_rfm_bounds_intro')} {Lang.key('viz_rfm_axis_r')} {ranges?.r?.min?.toLocaleString()} - {ranges?.r?.max?.toLocaleString()}
            {Lang.key('viz_rfm_bounds_sep')}{Lang.key('viz_rfm_axis_f')} {ranges?.f?.min?.toLocaleString()} - {ranges?.f?.max?.toLocaleString()}
            {Lang.key('viz_rfm_bounds_sep')}{Lang.key('viz_rfm_axis_m')} {ranges?.m?.min?.toLocaleString()} - {ranges?.m?.max?.toLocaleString()}
        </div>

        <div className='mt-1 px-4 text-center text-xs text-muted-foreground'>{Lang.key('viz_rfm_legend')}</div>
    </>
    )
}

export default VizRFMItem;
