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

import _ from 'lodash';
import {
  ChevronsUpDown,
  Link2,
} from 'lucide-react';

import DisplayValue from '@/components/DisplayValue';
import {
  idSearchCommandRef,
} from '@/components/IDsSearchCommand/IDSearchCommand';
import { Button } from '@/components/ui/button';
import { useAppConfig } from '@/contexts/AppConfigContext';
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 IDData = (props: ItemDataProps) => {


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

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





  const { color, openDialog } = useAppConfig()

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


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



    return <div>
      <DataLabel {...props} />
      <Button


        variant="secondary" className='w-full flex items-center justify-between' onClick={() => {
          if (localValue) {

            if (props.structure?.collection && localValue) {
              openDialog({
                collection: props.structure?.collection ?? "",
                _id: localValue ?? "",
                modalKey: `view_${props.structure?.collection}_${localValue}`

              })
            }


          }
        }}>
        {localValue ? <DisplayValue
          value={localValue}
          collection={props.structure?.collection ?? ""}


        /> : Lang.key('no_data_short')}
        <Link2 />

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




  }


  return <div className='w-full '>
    <DataLabel {...props} />

    <Button
      variant="outline"
      role="combobox"
      className="w-full justify-between"
      onClick={() => {
        idSearchCommandRef.current?.open({
          collection: props.structure?.collection ?? "",
          onSelect: (item) => {
            setLocalValue(item);
          }
        });

      }}
    >
      {!!localValue ? <DisplayValue value={localValue} collection={props.structure?.collection ?? ""} /> : Lang.key('select_value')}
      <ChevronsUpDown className="opacity-50" />
    </Button>
    <DataDescription {...props} />
  </div>




};

export default IDData;
