import {
  useEffect,
  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 { readExcelFileModalRef } from '@/components/ReadExcelFileModal';
import { toast } from '@/components/ToastRoot';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';
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';

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



    const [localValue, setLocalValue] = useState(props.getValue() ?? []);



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


    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>


            {!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 [forceUpdate, setForceUpdate] = useState(false);

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

    useEffect(() => {

        if (forceUpdate) {

            setForceUpdate(false);

        }

    }, [forceUpdate])

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






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


    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 { color } = useAppConfig();

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

                <>
                    {_.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"

                                        >
                                            <MdDeleteOutline size={18} />
                                        </Button>



                                        <Button
                                            variant="secondary"
                                            onClick={() => {
                                                onCopy(index);
                                            }}
                                            size="icon-sm"
                                        >
                                            <LuCopyPlus size={18} />
                                        </Button>


                                        <Button
                                            variant="secondary"
                                            onClick={() => {
                                                onUp(index);
                                            }}
                                            size="icon-sm"
                                        >
                                            <ArrowUp size={18} />
                                        </Button>
                                        <Button
                                            variant="secondary"
                                            onClick={() => {
                                                onDown(index);
                                            }}
                                            size="icon-sm"
                                        >
                                            <ArrowDown size={18} />
                                        </Button>



                                    </div>}
                                </div>


                            </div>
                        );
                    })}

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

            </ColCSS>




        </div>

    );


};


