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

import dayjs from 'dayjs';
import _ from 'lodash';
import {
  ChevronDownIcon,
  XIcon,
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import {
  MobileNavbar,
  MobilePage,
  MobilePopup,
} from '@/components/ui/mobile';
import { Lang, useLang } from '@/lang/Lang';
import { useLLText } from '@/lang/localizationService';
import useAppConfigStore from '@/stores/appConfig';
import { copyTextToClipboard } from '@/utils/helpers';

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

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

  const lang = useLang();
  const titlePlaceholder = useLLText(props.structure.title ?? '', lang);

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

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


  const { isMobile } = useAppConfigStore();


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

    const formatDuration = (minutes: number) => {
      const absMinutes = Math.abs(minutes);
      const hours = Math.floor(absMinutes / 60);
      const mins = absMinutes % 60;

      const parts: string[] = [];

      if (hours > 0) {
        if (hours === 1) {
          parts.push('1 час');
        } else if (hours < 5) {
          parts.push(`${hours} часа`);
        } else {
          parts.push(`${hours} часов`);
        }
      }

      if (mins > 0) {
        if (mins === 1) {
          parts.push('1 минуту');
        } else if (mins < 5) {
          parts.push(`${mins} минуты`);
        } else {
          parts.push(`${mins} минут`);
        }
      }

      return parts.join(' ');
    };

    const formatDateForPopover = () => {
      const date = dayjs.unix(localValue);
      const now = dayjs();
      const isDateTime = props.structure.type == "unixdatetime";

      // Проверяем, сегодня ли это (сравниваем только дату, без времени)
      const isToday = date.format('YYYY-MM-DD') === now.format('YYYY-MM-DD');

      if (isToday) {
        if (isDateTime) {
          // Для datetime показываем разницу в минутах
          const diffInMinutes = date.diff(now, 'minute');

          if (diffInMinutes === 0) {
            return 'сейчас';
          } else if (diffInMinutes < 0) {
            // Прошедшее время
            return `${formatDuration(diffInMinutes)} назад`;
          } else {
            // Будущее время
            return `через ${formatDuration(diffInMinutes)}`;
          }
        } else {
          // Для обычной даты просто "сегодня"
          return 'сегодня';
        }
      }

      // Вычисляем разницу в днях
      const diffInDays = date.diff(now, 'day');

      if (diffInDays < 0) {
        // Прошедшая дата
        const daysAgo = Math.abs(diffInDays);
        const timeStr = isDateTime ? ` ${date.format('HH:mm')}` : '';
        return `${daysAgo} ${daysAgo === 1 ? 'день' : daysAgo < 5 ? 'дня' : 'дней'} назад${timeStr}`;
      } else {
        // Будущая дата
        const timeStr = isDateTime ? ` ${date.format('HH:mm')}` : '';
        return `через ${diffInDays} ${diffInDays === 1 ? 'день' : diffInDays < 5 ? 'дня' : 'дней'}${timeStr}`;
      }
    };

    const contentOnlyView = (
      <ContentOnlyView
        placeholder={titlePlaceholder}
        copyString={!!localValue ? dayjs.unix(localValue).format(props.structure.type == "unixdate" ? 'DD.MM.YYYY' : 'DD.MM.YYYY HH:mm:ss') : ""}
      >
        {!!localValue ? <div>
          <div>{dayjs.unix(localValue).format('DD.MM.YYYY')}
            {props.structure.type == "unixdatetime" && <span className='text-xs ml-2'>{dayjs.unix(localValue).format('HH:mm')}</span>}</div>
        </div> : ""}
      </ContentOnlyView>
    );


    return <>
      <DataLabel {...props} />
      <Button
        onClick={() => {
          if (localValue) {
            copyTextToClipboard(dayjs.unix(localValue).format(props.structure.type == "unixdate" ? 'DD.MM.YYYY' : 'DD.MM.YYYY HH:mm:ss'));
          }
        }}
        variant="secondary" className='w-full flex items-center justify-between'>

        {!!localValue ? <div>
          <div>{dayjs.unix(localValue).format('DD.MM.YYYY')}
            {props.structure.type == "unixdatetime" && <span className='text-xs ml-2'>{dayjs.unix(localValue).format('HH:mm')}</span>}</div>
        </div> : Lang.key('no_data_short')}
      </Button>
      <DataDescription {...props} />
    </>


    return null;
  }


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

  if (props.structure.type == "unixdate") {

    if (isMobile) {
      return <div>
        <DataLabel {...props} />
        <Button
          variant="secondary" className='w-full flex items-center justify-between' onClick={() => {
            setOpen(true);
          }}>
          {!!localValue ? dayjs.unix(localValue).format('DD.MM.YYYY') : Lang.key('select_date')}
          <ChevronDownIcon />
        </Button>
        <MobilePopup opened={open} onBackdropClick={() => setOpen(false)}>
          <MobilePage>
            <MobileNavbar
              title={Lang.key('select_date')}
              right={<Button onClick={() => setOpen(false)}><XIcon /></Button>}
            />
            <Calendar
              className='w-full'
              mode="single"
              value={!!localValue ? localValue : null}
              captionLayout="dropdown"
              onChange={(date) => {
                setLocalValue(date);
                setOpen(false)
              }}
            />
          </MobilePage>
        </MobilePopup>
      </div>
    }
    return <div>
      <DataLabel {...props} />
      <DateEditableField
        withTime={false}
        value={localValue}
        onChange={setLocalValue}
        placeholder="DD.MM.YYYY"
      />
      <DataDescription {...props} />
    </div>
  }

  if (props.structure.type == "unixdatetime") {
    if (isMobile) {
      return <div>
        <DataLabel {...props} />
        <Button
          variant="secondary" className='w-full flex items-center justify-between' onClick={() => {
            setOpen(true);
          }}>
          {_.isNumber(localValue) ? dayjs.unix(localValue).format('DD.MM.YYYY HH:mm') : Lang.key('select_date')}
          <ChevronDownIcon />
        </Button>
        <MobilePopup opened={open} onBackdropClick={() => setOpen(false)}>
          <MobilePage>
            <MobileNavbar
              title={Lang.key('select_date')}
              right={<Button onClick={() => setOpen(false)}><XIcon /></Button>}
            />
            <div className="pb-safe">
              <Calendar
                className='w-full'
                mode="single"
                withTime
                value={_.isNumber(localValue) ? localValue : null}
                captionLayout="dropdown"
                onChange={(date) => {
                  setLocalValue(date);
                  setOpen(false);
                }}
              />
            </div>
          </MobilePage>
        </MobilePopup>
      </div>
    }
    return <div>
      <DataLabel {...props} />
      <DateEditableField
        withTime
        value={_.isNumber(localValue) ? localValue : null}
        onChange={setLocalValue}
        placeholder="DD.MM.YYYY HH:mm"
      />
      <DataDescription {...props} />
    </div>
  }


};
