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 {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Lang,
  LLRender,
} from '@/lang/Lang';
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 { ItemDataProps } from './types';

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


  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={LLRender(props.structure.title ?? '')}
        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} />

      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            id="date"
            className="w-full justify-between font-normal"
          >
            {!!localValue ? dayjs.unix(localValue).format('DD.MM.YYYY') : Lang.key('select_date')}
            <ChevronDownIcon />
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto overflow-hidden p-0" align="start">
          <Calendar
            mode="single"
            value={!!localValue ? localValue : null}
            captionLayout="dropdown"
            onChange={(date) => {
              setLocalValue(date);
              setOpen(false)
            }}
          />
        </PopoverContent>
      </Popover>

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

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





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

      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            id="date-picker"
            className="w-full justify-between font-normal"
          >
            {_.isNumber(localValue) ? dayjs.unix(localValue).format('DD.MM.YYYY HH:mm') : Lang.key('select_date')}
            <ChevronDownIcon />
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto overflow-hidden p-0" align="start">
          <Calendar
            mode="single"
            withTime
            value={_.isNumber(localValue) ? localValue : null}
            captionLayout="dropdown"
            onChange={(date) => {
              setLocalValue(date);
              setOpen(false);
            }}
          />
        </PopoverContent>
      </Popover>

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


  }


};
