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

import dayjs from 'dayjs';
import ReactECharts from 'echarts-for-react';
import {
    Edit,
    Move,
    Trash2,
} from 'lucide-react';

import { rpc } from '@/api/request';
import {
    BiBlockType,
    BiBlockValueType,
} from '@/api/types';
import { Lang } from '@/lang/Lang';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

import { UNIT_HEIGHT } from '../BIView';

interface BIBlockViewProps {
    item: BiBlockType;
    colSpan: number;
    rowSpan: number;
    onDelete?: (block: BiBlockType) => void;
    onEdit?: (block: BiBlockType) => void;
}

const BIBlockView = ({ item, colSpan, rowSpan, onDelete, onEdit }: BIBlockViewProps) => {


    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({
        id: item.uuid ?? '',
    });

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
        gridColumn: `span ${colSpan}`,
        gridRow: `span ${rowSpan}`,
        opacity: isDragging ? 0.5 : 1,


    };

    const [valuesData, setValuesData] = useState<BiBlockValueType | null>(null);

    useEffect(() => {

        rpc.calculateBiBlock(item).then((res) => {
            setValuesData(res?.result ?? null);
        }).catch((err) => {
            console.error('Error calculating bi block:', err);
            setValuesData(null);
        });


    }, [item.aggregateType, item.groupByField, item.valueField, item.filter, item.groupTransform, item.source]);

    const sortedForAbc = useMemo(() => {
        if (item.type !== 'abc' && item.type !== 'xyz') return [];
        const vals = valuesData?.values ?? [];
        return [...vals].sort((a, b) => {
            const va = typeof a.value === 'number' ? a.value : 0;
            const vb = typeof b.value === 'number' ? b.value : 0;
            return vb - va;
        });
    }, [item.type, valuesData?.values]);

    return (
        <div
            ref={setNodeRef}
            style={style}
        >
            <div className='pt-0 border border-gray-200 rounded-md'
                style={{
                    height: UNIT_HEIGHT * rowSpan,
                }}
            >


                <div

                >

                    {item.type == "chart" && <ReactECharts
                        style={{
                            height: UNIT_HEIGHT * rowSpan - 37,
                        }}

                        option={{
                            darkMode: false ? true : false,




                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'shadow'
                                }
                            },

                            grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '3%',
                                containLabel: true
                            },

                            xAxis: {
                                type: 'category',
                                data: valuesData?.values?.map((item) => {

                                    if (valuesData.keyTransform == "hour") {
                                        return dayjs.unix(item.key!).format("DD.MM HH:00");
                                    }


                                    if (valuesData.keyTransform == "day") {
                                        return dayjs.unix(item.key!).format("DD.MM.YYYY");
                                    }

                                    if (valuesData.keyTransform == "week") {


                                        let _date = dayjs.unix(item.key!);
                                        //Определеяем первый день недели с понедельника
                                        let _firstDayOfWeek = _date.startOf("week");
                                        //Определеяем последний день недели с воскресенья
                                        let _lastDayOfWeek = _date.endOf("week");
                                        //Формируем строку с датами
                                        let _dateString = _firstDayOfWeek.format("DD.MM.YYYY") + " - " + _lastDayOfWeek.format("DD.MM.YYYY");
                                        return _dateString;

                                    }

                                    if (valuesData.keyTransform == "month") {
                                        return dayjs.unix(item.key!).format("MMM YYYY");
                                    }

                                    if (valuesData.keyTransform == "year") {
                                        return dayjs.unix(item.key!).format("YYYY");

                                    }

                                    return item.key;



                                }),
                            },
                            yAxis: {
                                type: 'value',
                            },
                            series: [
                                {
                                    data: valuesData?.values?.map((item) => item.value) ?? [],
                                    type: 'line',
                                    smooth: true,
                                },
                            ],
                        }}


                    />}

                    {item.type == "pie" &&
                        <ReactECharts
                            style={{
                                height: UNIT_HEIGHT * rowSpan - 37,
                            }}

                            option={{
                                //  color: derivedColors(10),
                                // darkMode: isDarkTheme ? true : false,

                                tooltip: {
                                    trigger: 'item'
                                },
                                legend: {
                                    top: '5%',
                                    left: 'center'
                                },

                                grid: {
                                    left: '3%',
                                    right: '4%',
                                    bottom: '3%',
                                    containLabel: true
                                },
                                series: [
                                    {
                                        name: item?.title ?? "",
                                        type: 'pie',
                                        radius: ['40%', '70%'],
                                        center: ['50%', '70%'],
                                        // adjust the start and end angle
                                        startAngle: 180,
                                        endAngle: 360,

                                        data: valuesData?.values?.map((item) => {




                                            return {
                                                value: item.value,
                                                name: item.key
                                            }

                                        }),
                                        emphasis: {
                                            itemStyle: {
                                                shadowBlur: 10,
                                                shadowOffsetX: 0,
                                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                                            }
                                        }
                                    },

                                ]
                            }}
                        />}


                    {item.type == "square" && <div
                        className='flex    flex-col p-4 justify-center'
                        style={{
                            height: UNIT_HEIGHT * rowSpan - 37,
                        }}
                    >
                        <div className='text-3xl font-bold '>

                            {valuesData?.values?.[0]?.value ?? " - "}
                        </div>
                        <p className='text-sm text-gray-500'>{item?.title ?? "123123"}</p>
                    </div>}

                    {item.type == "table" && <div
                        className='overflow-auto p-2'
                        style={{ height: UNIT_HEIGHT * rowSpan - 37 }}
                    >
                        <table className='w-full text-sm'>
                            <thead>
                                <tr className='border-b'>
                                    <th className='text-left py-1 px-2'>{Lang.key('bi_table_column_name')}</th>
                                    <th className='text-right py-1 px-2'>{Lang.key('bi_table_column_value')}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {valuesData?.values?.map((row, i) => (
                                    <tr key={i} className='border-b border-gray-100'>
                                        <td className='py-1 px-2'>{row.key != null ? String(row.key) : '—'}</td>
                                        <td className='py-1 px-2 text-right'>{row.value != null ? String(row.value) : '—'}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>}

                    {item.type == "funnel" && <ReactECharts
                        style={{ height: UNIT_HEIGHT * rowSpan - 37 }}
                        option={{
                            tooltip: { trigger: 'item' },
                            series: [{
                                name: item?.title ?? '',
                                type: 'funnel',
                                left: '10%',
                                width: '80%',
                                data: valuesData?.values?.map((v) => ({ value: v.value, name: v.key != null ? String(v.key) : '' })) ?? [],
                            }]
                        }}
                    />}

                    {(item.type == "abc" || item.type == "xyz") && <div
                        className='overflow-auto p-2'
                        style={{ height: UNIT_HEIGHT * rowSpan - 37 }}
                    >
                        <table className='w-full text-sm'>
                            <thead>
                                <tr className='border-b'>
                                    <th className='text-left py-1 px-2'>#</th>
                                    <th className='text-left py-1 px-2'>{Lang.key('bi_table_column_name')}</th>
                                    <th className='text-right py-1 px-2'>{Lang.key('bi_table_column_value')}</th>
                                    {item.type == "abc" && <th className='text-center py-1 px-2'>{Lang.key('bi_table_column_abc')}</th>}
                                </tr>
                            </thead>
                            <tbody>
                                {sortedForAbc.map((row, i) => {
                                    const n = sortedForAbc.length;
                                    const cls = item.type === 'abc'
                                        ? (i < Math.ceil(n * 0.2) ? 'A' : i < Math.ceil(n * 0.5) ? 'B' : 'C')
                                        : null;
                                    return (
                                        <tr key={i} className='border-b border-gray-100'>
                                            <td className='py-1 px-2 text-gray-500'>{i + 1}</td>
                                            <td className='py-1 px-2'>{row.key != null ? String(row.key) : '—'}</td>
                                            <td className='py-1 px-2 text-right'>{row.value != null ? String(row.value) : '—'}</td>
                                            {item.type == "abc" && (
                                                <td className='py-1 px-2 text-center font-medium'>{cls}</td>
                                            )}
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>}



                </div>

                <div className='border-t border-gray-200 px-2 py-2 flex items-center justify-between'>
                    {item.type == "square" ? <div /> : <p className='text-sm text-gray-500'>{item?.title ?? "123123"}</p>}
                    <div className='flex items-center gap-2'>
                        <div
                            {...attributes}
                            {...listeners}
                            className='cursor-grab active:cursor-grabbing opacity-50 hover:opacity-100'
                        >
                            <Move className='size-4 ' />
                        </div>
                        <div
                            onClick={() => onEdit?.(item)}
                            className='cursor-pointer opacity-50 hover:opacity-100'>
                            <Edit className='size-4 ' />
                        </div>
                        <div

                            onClick={() => onDelete?.(item)}
                            className='cursor-pointer opacity-50 hover:opacity-100'>
                            <Trash2 className='size-4 ' />
                        </div>

                    </div>
                </div>



            </div>
        </div>
    );
}


export default BIBlockView;