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

import _ from 'lodash';
import {
    ArrowDown,
    ArrowUp,
} from 'lucide-react';
import { swap } from 'react-grid-dnd';
import { LuCopyPlus } from 'react-icons/lu';
import { MdDeleteOutline } from 'react-icons/md';
import { Row } from 'read-excel-file';

import { StructureType } from '@/api/types';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { readExcelFileModalRef } from '@/componentsRoot/ReadExcelFileModal';
import { toast } from '@/componentsRoot/ToastRoot';
import { Lang } from '@/lang/Lang';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';
import { hexToRgb } from '@/utils/helpers';

import { ColCSS } from '../../GridCss';
import DataDescription from '../components/DataDescription';
import DataLabel from '../components/DataLabel';
import ItemData from '../ItemData';
import { ItemDataProps } from '../types';
import ArrayImages from './ArrayImages';

export const ArrayData = (props: ItemDataProps) => {

    const { isMobile } = useAppConfigStore();

    const { color } = useAppConfig();
    const [localValue, setLocalValue] = useState(props.getValue() ?? []);
    const [forceUpdate, setForceUpdate] = useState(false);


    useEffect(() => {
        props.setValue(localValue);
    }, [localValue]);
    useEffect(() => {

        if (forceUpdate) {

            setForceUpdate(false);

        }

    }, [forceUpdate])


    const AddButton = ({ firstButton = false }: { firstButton?: boolean }) => {


        return <>
            <Button onClick={onAdd} variant="outline" size="sm">

                {firstButton ? Lang.key('add') : Lang.key('add_to')} {props.structure.title}
            </Button>


            {!isMobile && !props.structure.itemType?.items && <Button

                className='ml-2'
                onClick={() => {

                    readExcelFileModalRef.current?.open({
                        onSelect: (data: Row[]) => {
                            let newValues = data.map((row) => {
                                return row?.[0] ?? null;
                            }).filter((e) => e !== null);
                            setLocalValue((prev: any) => {
                                return [...prev, ...newValues];
                            });
                        }
                    });
                }} variant="outline" size="sm">
                {Lang.key('add_from_excel')}
            </Button>}

        </>
    };





    const onCopy = (index: number) => {

        const item = localValue[index];

        setLocalValue((prev: any) => {
            const newValue = [...prev];
            newValue.splice(index + 1, 0, { ...item, uuid: null });
            return newValue;
        });
        setForceUpdate(true);


    };



    const onDel = (index: number) => {

        setLocalValue((prev: any) => {
            const newValue = [...prev];
            newValue.splice(index, 1);
            return newValue;
        });

        setForceUpdate(true);

        //  let localValueTmp = get(valuesData, path) ?? [];

        //  localValueTmp = localValueTmp.filter((e: any) => e.uuid !== uuid);
        //  detailStore.get(props.storeKey)?.editData(path, localValueTmp);
    };



    const onAdd = () => {
        const item: any = {};

        setLocalValue((prev: any) => {

            return [...prev, null];

        });

    };


    const onDeleteAll = () => {

        setLocalValue([]);

    };

    const DeleteAppButton = () => {




        return (
            <Badge
                variant="destructive"
                onClick={() => {
                    onDeleteAll();
                }}

                className=" cursor-pointer"
            >
                {Lang.key('delete_all')}
            </Badge>
        );
    };



    const isArrayImages = useMemo(() => {
        return props.structure.itemType?.type === 'fileImage' || props.structure.itemType?.type === 'fileImageID' || props.structure.itemType?.type === 'fileImageLink';
    }, [props.structure.itemType]);



    if (!props.structure.itemType) {
        return <></>
    }


    if (isArrayImages) {
        return <ArrayImages
            {...props}
        />
    }


    const getParentValue = (index: number) => {


        return props.getValue()?.[index];
    }



    const onlyShow = props.onlyShow || !props.structure.editable;

    if (forceUpdate) return <div></div>


    if (!localValue || _.size(localValue) == 0) {



        if (!onlyShow) return <>
            <DataLabel {...props} />
            <DataDescription {...props} />

            <AddButton firstButton={true} />

        </>




        return <>
            <DataLabel {...props} />
            <DataDescription {...props} />
            <Button variant="secondary" className='w-full flex items-center justify-between' >
                {Lang.key('no_data_short')}
            </Button>

        </>
    }







    const onUp = (index: number) => {

        if (index <= 0) {
            toast.error(Lang.key('cant_move_up'));
            return;
        }

        setLocalValue((prev: any) => {
            return swap(prev, index, index - 1);
        });

        setForceUpdate(true);
    }

    const onDown = (index: number) => {


        if (index >= localValue.length - 1) {

            toast.error(Lang.key('cant_move_down'));

            return;
        }

        setLocalValue((prev: any) => {
            return swap(prev, index, index + 1);
        });

        setForceUpdate(true);
    }

    return (

        <div



            style={{

                backgroundColor: `rgba(${hexToRgb(color).join(',')},${0.02 * (props.arrayLevel + 1)})`,
                padding: '10px',
                borderRadius: '10px',
            }}
        >

            <div className='mb-2'>
                <div className="flex items-center justify-between">

                    <DataLabel {...props} />



                    <div className="flex items-center gap-2 ">
                        {!onlyShow && <div className="flex items-center gap-2">
                            {_.size(localValue) > 0 && (
                                <>
                                    <DeleteAppButton />

                                </>
                            )}

                        </div>
                        }
                    </div>

                </div>
                <DataDescription {...props} />

            </div>





            <ColCSS col={props.structure?.col ?? 24} row={props.structure?.row}>

                <>
                    {_.map(localValue, (value: any, index: any) => {
                        return (
                            <div
                                key={value?.uuid}

                            //  style={{ display: 'flex', width: '100%' }}
                            >
                                <div
                                    style={
                                        { flex: 1 }
                                    }
                                    className="mb-2 border-b-2 border-gray-200 relative"
                                >


                                    <ItemData
                                        descriptions={props.descriptions}
                                        inline={props.inline}
                                        getDataStructure={props.getDataStructure}
                                        onlyShow={props.onlyShow}
                                        getDataValue={props.getDataValue}
                                        structureLevel={0}
                                        arrayLevel={props?.arrayLevel + 1}
                                        getParentValue={() => getParentValue(index)}
                                        structure={props.structure.itemType as StructureType}
                                        getValue={() => {
                                            return localValue[index];
                                        }}
                                        rootParent={props.parent}
                                        parent={props.structure}
                                        setValue={(value: any) => {
                                            const newValue = [...localValue];
                                            newValue[index] = value;

                                            setLocalValue(newValue);
                                        }}
                                    />



                                    {!onlyShow && <div>


                                        <Button
                                            variant="secondary"
                                            onClick={() => {
                                                onDel(index);
                                            }}
                                            size="icon-sm"
                                            tooltip={Lang.key('delete')}
                                            aria-label={Lang.key('delete')}
                                        >
                                            <MdDeleteOutline size={18} />
                                        </Button>



                                        <Button
                                            variant="secondary"
                                            onClick={() => {
                                                onCopy(index);
                                            }}
                                            size="icon-sm"
                                            tooltip={Lang.key('copy_item')}
                                            aria-label={Lang.key('copy_item')}
                                        >
                                            <LuCopyPlus size={18} />
                                        </Button>


                                        <Button
                                            variant="secondary"
                                            onClick={() => {
                                                onUp(index);
                                            }}
                                            size="icon-sm"
                                            tooltip={Lang.key('move_up')}
                                            aria-label={Lang.key('move_up')}
                                        >
                                            <ArrowUp size={18} />
                                        </Button>
                                        <Button
                                            variant="secondary"
                                            onClick={() => {
                                                onDown(index);
                                            }}
                                            size="icon-sm"
                                            tooltip={Lang.key('move_down')}
                                            aria-label={Lang.key('move_down')}
                                        >
                                            <ArrowDown size={18} />
                                        </Button>



                                    </div>}
                                </div>


                            </div>
                        );
                    })}

                    {!onlyShow && <AddButton />}
                </>

            </ColCSS>




        </div>

    );


};


