import { useRef, useState } from 'react';

import { IconButton, Stack, Typography, useTheme } from '@mui/material';
import { IconCalendarDue, IconX } from '@tabler/icons-react';

import { getBorderColor } from '../../utils';
import DatePickersV6Provider from '../DatePickersV6Provider';

import CustomRangeSelector from './components/CustomRangeSelector';
import { type CustomRangePickerProps } from './types';

const CustomRangeDatePicker = (props: CustomRangePickerProps) => {
  const {
    value,
    onChange,
    sx,
    dateFormatter,
    enableClear,
    minDate,
    maxDate,
    minMaxDatesDifference,
    datePlaceholder,
    disabled,
    error,
    slotProps: {
      clearButtonAriaLabel = 'Clear date range',
      openPickerButtonAriaLabel = 'Open date range picker',
      ...restSlotProps
    },
  } = props;
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const inputContainerRef = useRef<HTMLDivElement>(null);
  const theme = useTheme();

  const { fromDate, toDate } = value;

  const handleOpen = () => {
    if (disabled) return;
    setAnchorEl(inputContainerRef.current);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleClear = () => {
    onChange({ fromDate: null, toDate: null });
  };

  const formattedFromDate = fromDate
    ? dateFormatter(fromDate)
    : datePlaceholder;
  const formattedToDate = toDate ? dateFormatter(toDate) : datePlaceholder;
  const showClearButton = enableClear && fromDate && toDate;

  return (
    <DatePickersV6Provider>
      <Stack
        ref={inputContainerRef}
        sx={{
          alignItems: 'center',
          backgroundColor: disabled
            ? theme.palette.new.background.elements.disabled
            : theme.palette.new.background.elements.default,
          border: `1px solid ${getBorderColor(theme, false, error, false, !!(fromDate || toDate))}`,
          borderRadius: 1,
          flexDirection: 'row',
          gap: 1,
          justifyContent: 'space-between',
          p: 1,
          transition: 'border 125ms ease',
          ...sx,
        }}
      >
        <Typography
          variant="globalS"
          sx={{
            cursor: 'pointer',
            '&:hover': {
              textDecoration: 'underline',
            },
            ...(disabled && {
              cursor: 'not-allowed',
              color: ({ palette }) => palette.text?.disabled,
              '&:hover': {
                textDecoration: 'none',
              },
            }),
          }}
          onClick={handleOpen}
        >
          {formattedFromDate} - {formattedToDate}
        </Typography>
        <Stack sx={{ flexDirection: 'row', gap: 1 }}>
          {/* Static date picker does not support clear button */}
          {showClearButton && (
            <IconButton
              onClick={handleClear}
              aria-label={clearButtonAriaLabel}
            >
              <IconX />
            </IconButton>
          )}
          <IconButton
            onClick={handleOpen}
            aria-label={openPickerButtonAriaLabel}
            aria-haspopup="dialog"
            aria-expanded={!!anchorEl}
          >
            <IconCalendarDue />
          </IconButton>
        </Stack>
        <CustomRangeSelector
          anchorElement={anchorEl}
          handleClose={handleClose}
          value={value}
          onChange={onChange}
          minDate={minDate}
          maxDate={maxDate}
          minMaxDatesDifference={minMaxDatesDifference}
          disabled={disabled}
          slotProps={restSlotProps}
        />
      </Stack>
    </DatePickersV6Provider>
  );
};

export default CustomRangeDatePicker;
