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

import dayjs from 'dayjs';

import { Button } from '@/components/ui/button';
import {
  TimePicker,
  TimePickerContent,
  TimePickerHour,
  TimePickerInput,
  TimePickerInputGroup,
  TimePickerMinute,
  TimePickerPeriod,
  TimePickerSeparator,
  TimePickerTrigger,
} from '@/components/ui/time-picker';
import { Lang } from '@/lang/Lang';
import { copyTextToClipboard } from '@/utils/helpers';

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

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



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

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



  const onChangeTime = (
    date: dayjs.Dayjs | null,
    dateString: string | string[]
  ) => {
    let val = date ? { h: date.hour(), m: date.minute() } : null;

    setLocalValue(val);
  };



  if (props.onlyShow || !props.structure.editable) {
    return <div>
      <DataLabel {...props} />
      <Button
        onClick={() => {
          if (localValue) {
            copyTextToClipboard(`${localValue?.h ?? ''}:${localValue?.m ?? ''}`);
          }
        }}
        variant="secondary" className='w-full flex items-center justify-between'>
        {localValue ? `${localValue?.h ?? ''}:{localValue?.m ?? ''}` : Lang.key('no_data_short')}
      </Button>
      <DataDescription {...props} />
    </div>



  }



  return (
    <>

      <DataLabel {...props} />
      <TimePicker className="w-full" openOnFocus
        value={localValue?.h !== undefined && localValue?.m !== undefined ? `${localValue?.h}:${localValue?.m}` : ""}
        onValueChange={(value) => {
          setLocalValue({ h: Number(value.split(':')[0]), m: Number(value.split(':')[1]) });
        }}
      >

        <TimePickerInputGroup>
          <TimePickerInput
            placeholder="00"
            segment="hour" />
          <TimePickerSeparator

          />
          <TimePickerInput
            placeholder="00"

            segment="minute" />

          <TimePickerTrigger />
        </TimePickerInputGroup>
        <TimePickerContent>
          <TimePickerHour />
          <TimePickerMinute />
          <TimePickerPeriod />
        </TimePickerContent>
      </TimePicker>
      <DataDescription {...props} />
    </>
  );
};


