import React, { useRef } from 'react';
import { TextField, FormControl, FormHelperText } from '@mui/material';
import dayjs from 'dayjs';
import { useCreation } from 'ahooks';

interface DateTimeInputProps {
  value: Date;
  onChange: (value: Date) => void;
  error?: boolean;
  helperText?: string;
  label?: string;
  timezone?: string;
}

export default function DateTimeInput({
  value,
  onChange,
  error = undefined,
  helperText = undefined,
  label = undefined,
  timezone = undefined,
}: DateTimeInputProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const minDateTime = dayjs().format('YYYY-MM-DDTHH:mm');

  const formatValue = useCreation(() => {
    let date = dayjs();
    if (value) {
      date = timezone ? dayjs(value).tz(timezone) : dayjs(value);
    }

    return date.format('YYYY-MM-DD HH:mm');
  }, [value, timezone]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    onChange(new Date(e.target.value));
  };

  // 处理点击事件
  const handleClick = () => {
    // 通过编程方式触发原生日期选择器
    inputRef.current?.showPicker();
  };

  return (
    <FormControl fullWidth error={error}>
      <TextField
        inputRef={inputRef}
        type="datetime-local"
        value={formatValue}
        onChange={handleChange}
        label={label}
        error={error}
        onClick={handleClick}
        sx={{
          '& .MuiInputBase-root': {
            cursor: 'pointer',
          },
          '& .MuiOutlinedInput-notchedOutline': {
            cursor: 'pointer',
          },
        }}
        slotProps={{
          htmlInput: {
            min: minDateTime,
            style: { cursor: 'pointer' },
          },

          inputLabel: {
            shrink: true,
          },
        }}
      />
      {helperText && <FormHelperText>{helperText}</FormHelperText>}
    </FormControl>
  );
}
