import React, { memo, useState } from 'react';
import { ConfigProvider, DatePicker } from 'antd5';
import { useIntl } from 'umi';
import dayjs from 'dayjs';
import { dateTimeRangeProps, dateTimeProps } from '../utils';
import type { Dayjs } from 'dayjs';
const { RangePicker } = DatePicker;
type TypeProps = {
  /**
   * @description value时间戳
   */
  allowClear?: boolean;
  value?: number[] | number;
  onChange?: (value: number[] | number) => void;
  showTime?: boolean;
  children?: React.ReactNode;
};
const usePickerConfig = ({ showTime, isRange }: TypeProps & { isRange?: boolean }) => {
  const { formatMessage } = useIntl();
  const propsGetter = isRange ? dateTimeRangeProps : dateTimeProps;
  const presets = showTime
    ? propsGetter(formatMessage).presets
    : propsGetter(formatMessage).presets.slice(4);
  return { presets };
};

const BasePicker = memo<TypeProps & { isRange?: boolean }>(
  ({ value, allowClear, onChange, showTime, isRange }) => {
    const { formatMessage } = useIntl();
    const [time, setTime] = useState<Dayjs[] | null[] | Dayjs | null>(
      isRange
        ? Array.isArray(value) && value?.length == 2
          ? [dayjs.unix(value[0]), dayjs.unix(value[1])]
          : [null, null]
        : typeof value === 'number'
        ? dayjs.unix(value)
        : null,
    );

    const handleChange = (e: Dayjs[] | Dayjs) => {
      const unixTime = isRange
        ? (e as Dayjs[])?.map((item) => item?.unix())
        : e && (e as Dayjs)?.unix();
      onChange?.(unixTime);
      setTime(e);
    };

    const { presets } = usePickerConfig({ showTime, isRange });
    const PickerComponent: any = isRange ? RangePicker : DatePicker;
    return (
      <PickerComponent
        allowClear={allowClear}
        placeholder={
          isRange
            ? [
                formatMessage({ id: 'base.common.time.start' }),
                formatMessage({ id: 'base.common.time.end' }),
              ]
            : formatMessage({ id: 'base.common.time.select' })
        }
        value={time}
        showTime={showTime}
        onChange={handleChange}
        presets={presets}
      />
    );
  },
);

// RangePicker组件
const RangeTimePicker = ({ value, allowClear, onChange, showTime }: TypeProps) => (
  <ConfigProvider
    theme={{
      token: {
        colorPrimary: '#F16622',
        colorLink: '#F16622',
      },
    }}
  >
    <BasePicker
      allowClear={allowClear}
      value={value}
      onChange={onChange}
      showTime={showTime}
      isRange={true}
    />
  </ConfigProvider>
);

// TimePicker组件
const TimePicker = ({ value, allowClear, onChange, showTime }: TypeProps) => (
  <ConfigProvider
    theme={{
      token: {
        colorPrimary: '#F16622',
        colorLink: '#F16622',
      },
    }}
  >
    <BasePicker value={value} onChange={onChange} allowClear={allowClear} showTime={showTime} />
  </ConfigProvider>
);

export default { RangeTimePicker, TimePicker };
