import {
    useEffect,
    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 { 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]);

    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>}



                </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;