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

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

import DisplayValue from '@/components/DisplayValue';
import { Button } from '@/components/ui/button';
import {
  idSearchCommandRef,
} from '@/componentsRoot/IDsSearchCommand/IDSearchCommand';
import { Lang } from '@/lang/Lang';
import { useAppConfig } from '@/stores/appConfig';

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 overflow-hidden' 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 ?? ""}
          className='cursor-pointer'

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