import React, { useEffect, useState } from 'react';
import {
  MdDateRange,
  MdKeyboardArrowLeft,
  MdKeyboardArrowRight,
} from 'react-icons/md';
import {
  CalendarBody,
  CalendarContainer,
  CalendarDayCell,
  CalendarHeader,
  CalendarIcon,
  DateInput,
  DateInputContainer,
} from './styles/input';

/**
 * @param {{
 *  size: string,
 *  value: string | number,
 *  onChange: Function,
 *  selected: string,
 * }} props - properties of Header Component
 *
 */

const Calender = ({ size, value, color, active, icon, onChange }) => {
  const [showCalendar, setShowCalendar] = useState(false);
  const [selectedDate, setSelectedDate] = useState(value);
  const handleDateSelect = (date) => {
    setSelectedDate(date);
    onChange(date);
    setShowCalendar(false);
  };
  const monthNames = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
  ];
  const weekdays = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
  const renderCalendar = () => {
    const today = new Date();
    const year = selectedDate
      ? selectedDate.getFullYear()
      : today.getFullYear();
    const month = selectedDate ? selectedDate.getMonth() : today.getMonth();
    const firstDayOfMonth = new Date(year, month, 1);
    const lastDayOfMonth = new Date(year, month + 1, 0);
    const daysInMonth = lastDayOfMonth.getDate();
    const startDayOfWeek = firstDayOfMonth.getDay();
    const calendarDays = [];
    for (let i = 0; i < startDayOfWeek; i++) {
      calendarDays.push(null);
    }
    for (let i = 1; i <= daysInMonth; i++) {
      calendarDays.push(new Date(year, month, i));
    }
    const handlePrevMonthClick = () => {
      setSelectedDate(new Date(year, month - 1, 1));
    };
    const handleNextMonthClick = () => {
      setSelectedDate(new Date(year, month + 1, 1));
    };
    return (
      <CalendarContainer>
        <CalendarHeader>
          <div>
            {monthNames[month]} {year}
          </div>
          <div className="buttons">
            <button onClick={handlePrevMonthClick}>
              <MdKeyboardArrowLeft />
            </button>
            <button onClick={handleNextMonthClick}>
              <MdKeyboardArrowRight />
            </button>
          </div>
        </CalendarHeader>
        <CalendarBody>
          {weekdays.map((day) => (
            <CalendarDayCell className="weekdays" key={day}>
              {day}
            </CalendarDayCell>
          ))}
          {calendarDays.map((date) =>
            date ? (
              <CalendarDayCell
                key={date}
                onClick={() => handleDateSelect(date)}
                color={color}
                selected={
                  selectedDate &&
                  date.toDateString() === selectedDate.toDateString()
                }
              >
                {date.getDate()}
              </CalendarDayCell>
            ) : (
              <CalendarDayCell
                color={color}
                key={Math.random()}
              ></CalendarDayCell>
            ),
          )}
        </CalendarBody>
      </CalendarContainer>
    );
  };
  const handleKeyPress = (e) => {
    if (e.key === 'ArrowLeft') {
      setSelectedDate(
        new Date(
          selectedDate.getFullYear(),
          selectedDate.getMonth(),
          selectedDate.getDate() - 1,
        ),
      );
    } else if (e.key === 'ArrowRight') {
      setSelectedDate(
        new Date(
          selectedDate.getFullYear(),
          selectedDate.getMonth(),
          selectedDate.getDate() + 1,
        ),
      );
    } else if (e.key === 'ArrowUp') {
      setSelectedDate(
        new Date(
          selectedDate.getFullYear(),
          selectedDate.getMonth(),
          selectedDate.getDate() - 7,
        ),
      );
    } else if (e.key === 'ArrowDown') {
      setSelectedDate(
        new Date(
          selectedDate.getFullYear(),
          selectedDate.getMonth(),
          selectedDate.getDate() + 7,
        ),
      );
    }
  };
  useEffect(() => {
    document.addEventListener('keydown', handleKeyPress);
    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, [handleKeyPress]);
  return (
    <DateInputContainer size={size}>
      <DateInput
        size={size}
        value={
          selectedDate
            ? `${selectedDate.getDate()} ${monthNames[selectedDate.getMonth()].slice(0, 3)} ${selectedDate.getFullYear()}`
            : ''
        }
        color={color}
        active={active}
        onFocus={() => setShowCalendar(true)}
        onBlur={() => setShowCalendar(false)}
        onKeyDown={handleKeyPress} // add this
      />

      <CalendarIcon
        color={color}
        onClick={() => setShowCalendar(!showCalendar)}
      >
        {icon ? icon : <MdDateRange />}
      </CalendarIcon>
      {showCalendar && renderCalendar()}
    </DateInputContainer>
  );
};
export default Calender;
