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

import _ from 'lodash';

import DisplayValue from '@/components/DisplayValue';
import {
  idsSearchCommandRef,
} from '@/componentsRoot/IDsSearchCommand/IDsSearchCommand';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Lang } from '@/lang/Lang';

import OpsItemData from '../OpsItemData';
import DataDescription from './components/DataDescription';
import DataLabel from './components/DataLabel';
import { ItemDataProps } from './types';

export type DetailItemType = {
  object: string;
  _id: string;
  title: string;
};




const IDsData = (props: ItemDataProps) => {



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

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



  if (!props.structure?.collection) {
    return <OpsItemData
      {...props}
    />

  }

  if (props.onlyShow || !props.structure.editable) {


    return <>

      <DataLabel {...props} />

      <Button variant="secondary" className='w-full h-auto'>
        <div className='flex flex-wrap gap-2 w-full'>
          {localValue?.length > 0 ? (
            <>
              {localValue?.map((item: any, index: any) => {
                return <Badge key={item}><DisplayValue value={item} collection={props.structure?.collection ?? ""} /></Badge>
              })}
            </>
          ) : Lang.key('no_data_short')}
        </div>
      </Button>
      <DataDescription {...props} />
    </>

  }






  return (
    <React.Fragment>

      <DataLabel {...props} />

      <Button
        onClick={() => {
          idsSearchCommandRef.current?.open({
            collection: props.structure?.collection ?? "",
            values: localValue,
            onSelect: (item) => {
              setLocalValue(item);
            }
          });
        }}

        variant="outline" className='w-full h-auto'>
        <div className='flex flex-wrap gap-2 w-full'>
          {localValue?.length > 0 ? (
            <>
              {localValue?.map((item: any, index: any) => {
                return <Badge key={item}><DisplayValue value={item} collection={props.structure?.collection ?? ""} /></Badge>
              })}
            </>
          ) : Lang.key('no_data_short')}
        </div>
      </Button>
      <DataDescription {...props} />
    </React.Fragment>
  );
}

export default IDsData;
