/* eslint-disable @typescript-eslint/indent */
import { useState, useRef } from 'react';
import {
  TextField,
  Stack,
  Typography,
  useMediaQuery,
  useTheme,
  Popover,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  IconButton,
} from '@mui/material';
import { DateRange, Close, Clear } from '@mui/icons-material';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import FormLabel from './label';
import { formatToDate } from '../libs/util';

export interface DateRangeValue {
  start: number | undefined;
  end: number | undefined;
}

export interface DateRangePickerProps {
  value: DateRangeValue;
  onChange: (value: DateRangeValue) => void;
  label?: string;
  size?: 'small' | 'medium';
  fullWidth?: boolean;
  disabled?: boolean;
}

interface DatePickerContentProps {
  tempValue: { startDate: string; endDate: string };
  setTempValue: (
    value:
      | { startDate: string; endDate: string }
      | ((prev: { startDate: string; endDate: string }) => { startDate: string; endDate: string })
  ) => void;
  handleCancel: () => void;
  handleApply: () => void;
  handleClear: () => void;
}

// 日期选择器内容组件
function DatePickerContent({
  tempValue,
  setTempValue,
  handleCancel,
  handleApply,
  handleClear,
}: DatePickerContentProps) {
  const { t } = useLocaleContext();
  return (
    <Box sx={{ p: 2, minWidth: 320 }}>
      <Stack spacing={2}>
        <Box>
          <FormLabel>{t('common.startDate')}</FormLabel>
          <TextField
            type="date"
            value={tempValue.startDate}
            onChange={(e) => setTempValue((prev) => ({ ...prev, startDate: e.target.value }))}
            size="small"
            fullWidth
            slotProps={{
              inputLabel: { shrink: true },
            }}
          />
        </Box>
        <Box>
          <FormLabel>{t('common.endDate')}</FormLabel>
          <TextField
            type="date"
            value={tempValue.endDate}
            onChange={(e) => setTempValue((prev) => ({ ...prev, endDate: e.target.value }))}
            size="small"
            fullWidth
            slotProps={{
              inputLabel: { shrink: true },
            }}
          />
        </Box>

        <Stack
          direction="row"
          spacing={1}
          sx={{
            justifyContent: 'space-between',
          }}>
          <Button variant="text" onClick={handleClear} size="small" color="secondary" sx={{ px: 0.5, minWidth: 0 }}>
            {t('common.clear')}
          </Button>
          <Stack direction="row" spacing={1}>
            <Button variant="outlined" onClick={handleCancel} size="small">
              {t('common.cancel')}
            </Button>
            <Button variant="contained" onClick={handleApply} size="small">
              {t('common.confirm')}
            </Button>
          </Stack>
        </Stack>
      </Stack>
    </Box>
  );
}

const DateFormat = 'YYYY-MM-DD';

export default function DateRangePicker({
  value,
  onChange,
  label = '',
  size = 'small',
  fullWidth = false,
  disabled = false,
}: DateRangePickerProps) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const [open, setOpen] = useState(false);
  const { t, locale } = useLocaleContext();
  // 内部使用字符串格式的临时值
  const [tempValue, setTempValue] = useState<{ startDate: string; endDate: string }>({
    startDate: value.start ? formatToDate(value.start * 1000, locale, DateFormat) : '',
    endDate: value.end ? formatToDate(value.end * 1000, locale, DateFormat) : '',
  });
  const anchorRef = useRef<HTMLDivElement>(null);

  const formatDisplayValue = (startUnix: number | undefined, endUnix: number | undefined) => {
    if (!startUnix || !endUnix) return t('common.selectTimeRange');
    const start = formatToDate(startUnix * 1000, locale, DateFormat);
    const end = formatToDate(endUnix * 1000, locale, DateFormat);
    return `${start} ~ ${end}`;
  };

  const handleOpen = () => {
    if (disabled) return;
    setTempValue({
      startDate: value.start ? formatToDate(value.start * 1000, locale, DateFormat) : '',
      endDate: value.end ? formatToDate(value.end * 1000, locale, DateFormat) : '',
    });
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const handleApply = () => {
    const unixValue: DateRangeValue = {
      start: tempValue.startDate ? Math.floor(new Date(`${tempValue.startDate}T00:00:00`).getTime() / 1000) : 0,
      end: tempValue.endDate ? Math.floor(new Date(`${tempValue.endDate}T23:59:59`).getTime() / 1000) : 0,
    };
    onChange(unixValue);
    setOpen(false);
  };

  const handleCancel = () => {
    setTempValue({
      startDate: value.start ? formatToDate(value.start * 1000, locale, DateFormat) : '',
      endDate: value.end ? formatToDate(value.end * 1000, locale, DateFormat) : '',
    });
    setOpen(false);
  };

  const handleClear = () => {
    const emptyValue: DateRangeValue = { start: undefined, end: undefined };
    onChange(emptyValue);
    setTempValue({ startDate: '', endDate: '' });
    setOpen(false);
  };

  const hasValue = !!value.start && !!value.end;

  return (
    <>
      <TextField
        ref={anchorRef}
        label={label}
        value={formatDisplayValue(value.start, value.end)}
        size={size}
        fullWidth={fullWidth}
        disabled={disabled}
        sx={{
          '& .MuiInputBase-input': {
            cursor: disabled ? 'default' : 'pointer',
          },
        }}
        onClick={handleOpen}
        placeholder={t('common.selectTimeRange')}
        slotProps={{
          input: {
            readOnly: true,
            startAdornment: <DateRange fontSize="small" sx={{ mr: 1, color: 'text.secondary' }} />,
            endAdornment: hasValue && !disabled && (
              <IconButton
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  handleClear();
                }}
                sx={{
                  color: 'text.secondary',

                  '&:hover': { color: 'text.primary' },
                }}>
                <Clear fontSize="small" />
              </IconButton>
            ),
          },

          inputLabel: { shrink: true },
        }}
      />
      {/* 桌面端使用 Popover */}
      {!isMobile && (
        <Popover
          open={open}
          anchorEl={anchorRef.current}
          onClose={handleClose}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'left',
          }}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'left',
          }}
          sx={{
            '& .MuiPaper-root': {
              boxShadow: theme.shadows[8],
              border: `1px solid ${theme.palette.divider}`,
            },
          }}>
          <DatePickerContent
            tempValue={tempValue}
            setTempValue={setTempValue}
            handleCancel={handleCancel}
            handleApply={handleApply}
            handleClear={handleClear}
          />
        </Popover>
      )}
      {/* 移动端使用 Dialog */}
      {isMobile && (
        <Dialog
          open={open}
          onClose={handleClose}
          fullWidth
          maxWidth="sm"
          PaperProps={{
            sx: {
              m: 1,
              maxHeight: 'calc(100% - 64px)',
            },
          }}>
          <DialogTitle
            sx={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              pb: 1,
            }}>
            <Typography variant="h6">{t('common.selectTimeRange')}</Typography>
            <IconButton edge="end" color="inherit" onClick={handleClose} aria-label="close" size="small">
              <Close />
            </IconButton>
          </DialogTitle>
          <DialogContent sx={{ pb: 1 }}>
            <Stack spacing={2} sx={{ mt: 1 }}>
              <FormLabel>{t('common.startDate')}</FormLabel>
              <TextField
                type="date"
                value={tempValue.startDate}
                onChange={(e) => setTempValue((prev) => ({ ...prev, startDate: e.target.value }))}
                size="small"
                fullWidth
                slotProps={{
                  inputLabel: { shrink: true },
                }}
              />
              <FormLabel>{t('common.endDate')}</FormLabel>
              <TextField
                type="date"
                value={tempValue.endDate}
                onChange={(e) => setTempValue((prev) => ({ ...prev, endDate: e.target.value }))}
                size="small"
                fullWidth
                slotProps={{
                  inputLabel: { shrink: true },
                }}
              />
            </Stack>
          </DialogContent>
          <DialogActions sx={{ px: 3, pb: 2 }}>
            <Button onClick={handleCancel} color="inherit">
              {t('common.cancel')}
            </Button>
            <Button onClick={handleApply} variant="contained">
              {t('common.confirm')}
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  );
}
