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

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

import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { MobileChip } from '@/components/ui/mobile';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  ToggleGroup,
  ToggleGroupItem,
} from '@/components/ui/toggle-group';
import { IS_DEV } from '@/config';
import { Lang } from '@/lang/Lang';
import { LL } from '@/lang/LL';
import { cn } from '@/lib/utils';
import useAppConfigStore from '@/stores/appConfig';

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

export type ItemType = {
  label: string;
  value: string;
};

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


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

  const values = useMemo(() => {
    return props.structure?.values;
  }, [props.structure]);



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




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

    return <div>
      <DataLabel {...props} />
      <Button variant="secondary" className='w-full flex items-center justify-between'>
        {localValue && localValue.length > 0 ? _.map(localValue, (val) => {
          return <Badge key={val}><LL value={values?.[val] ?? ''} /></Badge>
        }) : Lang.key('no_data_short')}
      </Button>
      {IS_DEV && <div className='text-[10px] text-muted-foreground px-1 my-1 text-red-300'>{JSON.stringify(props.getValue())}</div>}

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




  }



  if (((isMobile && _.size(values) < 4) || (!isMobile && _.size(values) < 10))) {
    return <div className='w-full '>

      <DataLabel {...props} />

      {isMobile ? <div>

        {_.map(props.structure.itemType?.values, (value, key) => {
          const isSelected = localValue.includes(key);
          return (
            <MobileChip

              style={{
                opacity: isSelected ? 1 : 0.5,
              }}
              outline={isSelected}
              media={
                isSelected ? <div className='flex items-center justify-center pl-2'>
                  <Check className='size-4' />
                </div> : null
              }

              className='m-0.5' key={key} onClick={() => {
                setLocalValue((prev) =>
                  prev.includes(key)
                    ? prev.filter((item) => item !== key)
                    : [...prev, key]
                );
              }}>
              <LL value={value} />
            </MobileChip>
          )
        })}


      </div> :
        <ToggleGroup
          wrap
          type="multiple" variant="outline" spacing={2} size="xs" value={localValue} onValueChange={(value) => { setLocalValue(value) }}>

          {_.map(props.structure.itemType?.values, (value, key) => {
            return (
              <ToggleGroupItem

                value={key}
                data-selected={localValue.includes(key) ? "true" : "false"}
              >
                <LL value={value} />
              </ToggleGroupItem>
            )
          })}



        </ToggleGroup>}

      <DataDescription {...props} />

    </div>
  }



  const [open, setOpen] = useState(false);


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

    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger className='w-full' >
        <Button
          variant="outline"
          role="combobox"
          className="w-full justify-between h-auto"
        >

          <div className='flex flex-wrap gap-2'> {localValue && localValue.length > 0 ? _.map(localValue, (val) => {
            return <Badge key={val}><LL value={values?.[val] ?? ''} /></Badge>
          }) : Lang.key('select_value')}
          </div>
          <ChevronsUpDown className="opacity-50" />

        </Button>
      </PopoverTrigger>
      <PopoverContent
        className="p-0 w-[var(--radix-popover-trigger-width)]"
      >
        <div
          className="p-1"
          style={{
            maxHeight: '400px',
            overflowY: 'auto',
            overflowX: 'hidden',
            WebkitOverflowScrolling: 'touch'
          }}
          onWheel={(e) => {
            e.stopPropagation();
            const target = e.currentTarget;
            target.scrollTop += e.deltaY;
            e.preventDefault();
          }}
        >
          {_.map(values, (value, key) => (
            <div
              key={key}
              onClick={() => {
                setLocalValue((prev) => {
                  if (prev.includes(key)) {
                    return prev.filter((item: any) => item !== key);
                  } else {
                    return [...prev, key];
                  }
                });
              }}
              className={cn(
                "relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground",
                localValue?.includes(key) && "bg-accent text-accent-foreground"
              )}
            >
              <LL value={value} />
              <Check
                className={cn(
                  "ml-auto h-4 w-4",
                  localValue?.includes(key) ? "opacity-100" : "opacity-0"
                )}
              />
            </div>
          ))}
        </div>
      </PopoverContent>
    </Popover>

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





};
