import { useState, useRef } from 'react';
import {
  Box,
  TextField,
  InputAdornment,
  IconButton,
  ClickAwayListener,
  Portal,
} from '@mui/material';
import { CalendarIcon } from '../../common/icons/icons';
import { Calendar } from './Calendar';
import { formatDate } from '../../../utils/formatDate';

export const CalendarInput = ({ value, onChange, isTaskMode = false }) => {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef(null);
  const [anchorPosition, setAnchorPosition] = useState(null);

  const handleOpen = () => {
    if (containerRef.current) {
      const rect = containerRef.current.getBoundingClientRect();
      setAnchorPosition({
        top: rect.bottom,
        left: rect.left,
        width: rect.width,
      });
      setIsOpen(true);
    }
  };

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

  return (
    <>
      <Box sx={{ position: 'relative' }} ref={containerRef}>
        <TextField
          value={value ? formatDate(value) : ''}
          onClick={handleOpen}
          slotProps={{
            input: {
              readOnly: true,
              startAdornment: (
                <InputAdornment
                  position="start"
                  sx={{
                    backgroundColor: '#DCFCE7',
                    margin: 0,
                    paddingLeft: '0.75rem',
                    paddingRight: '0.5rem',
                    marginLeft: '-14px',
                    marginRight: '8px',
                    borderTopLeftRadius: '0.5rem',
                    borderBottomLeftRadius: '0.5rem',
                    borderRight: '1px solid var(--Stroke, rgba(0, 0, 0, 0.1))',
                    cursor: 'pointer',
                  }}
                  onClick={handleOpen}
                >
                  <IconButton
                    size="small"
                    edge="start"
                    sx={{
                      ml: -0.5,
                      padding: '0.25rem',
                    }}
                  >
                    <CalendarIcon />
                  </IconButton>
                </InputAdornment>
              ),
            },
          }}
          size="small"
          fullWidth
          placeholder=""
          sx={{
            '& .MuiOutlinedInput-root': {
              cursor: 'pointer',
              '& fieldset': {
                borderColor: 'var(--Stroke, rgba(0, 0, 0, 0.1))',
                borderRadius: '0.5rem',
              },
            },
            '& .MuiInputBase-root': {
              display: 'flex',
              alignItems: 'stretch',
            },
            '& .MuiInputAdornment-root': {
              maxHeight: 'none',
            },
          }}
        />
      </Box>

      {isOpen && anchorPosition && (
        <Portal>
          <ClickAwayListener onClickAway={handleClose}>
            <Box
              sx={{
                position: 'fixed',
                top: anchorPosition.top + 8,
                left: anchorPosition.left,
                zIndex: 9999,
              }}
            >
              <Calendar
                value={value}
                onChange={onChange}
                onClose={handleClose}
              />
            </Box>
          </ClickAwayListener>
        </Portal>
      )}
    </>
  );
};
