import React, { useState, useLayoutEffect } from "react";
import { DayPickerRangeController } from "react-dates";
import ShowMonthYearSelect from "./showMonthYearSelect";
import DateRangePickerFooter from "./dateRangePickerFooter";
import DateRangePickerCustom from "./dateRangePickerCustom";
import { calculatePosition, formatMomentDate } from "./utils";
import moment from "moment";
import Portal from "../Portal";

export default function DateRangePickerDropdown({
  dropDownContainerRef,
  withPortal,
  portalContainer,
  containerRef,
  onDatesChange,
  onFocusChange,
  focusedInput,
  startDate,
  endDate,
  showWeekNumbers,
  selectedRange,
  setStartDateOffset,
  setEndDateOffset,
  selectedDaysNumber,
  handleResetDates,
  handleCancelDates,
  onSecondaryButtonClick,
  tertiaryButtonProps,
  handleApplyDates,
  primaryButtonProps,
  showRangeSelector,
  handleRangeSelectorChange,
  showMonthYearSelect,
  customYears,
  customWeekNumberData,
  suppressClickOnWeekNumber,
  setIsOpen,
  startDateOffset,
  endDateOffset,
  hasInputErrors,
  portalClassName,
  ...args
}) {
  const [position, setPosition] = useState({
    x: 0,
    y: 0,
    offsetHeight: 0,
    offsetWidth: 0,
  });

  const [customPosition, setCustomPosition] = useState({
    left: 0,
    right: "auto",
  });

  useLayoutEffect(() => {
    if (withPortal && containerRef.current) {
      // For portal: use simple positioning relative to input container
      const scrollY = window.scrollY || document.documentElement.scrollTop;
      const {
        x,
        y,
        height: offsetHeight,
        width: offsetWidth,
      } = containerRef.current.getBoundingClientRect();
      calculatePosition({
        containerRef,
        setCustomPosition,
        showRangeSelector,
      });
      setPosition({
        x,
        y: y + scrollY,
        offsetHeight,
        offsetWidth,
        ...customPosition,
      });
    } else if (
      !withPortal &&
      containerRef.current &&
      dropDownContainerRef.current
    ) {
      // For non-portal: use original calculatePosition with overflow handling
      calculatePosition({
        containerRef,
        setCustomPosition,
        showRangeSelector,
      });
    }
  }, [
    containerRef.current,
    dropDownContainerRef.current,
    withPortal,
    showRangeSelector,
  ]);

  const renderDayContents = React.useCallback((momentInstance, modifiers) => {
    let currentWeek = null;
    let currentWeekNumber = null;

    if (customWeekNumberData) {
      if (modifiers.has("first-day-of-week")) {
        currentWeek = customWeekNumberData.find((weekNumberData) => {
          return (
            weekNumberData?.calendar_week_start_date ===
            formatMomentDate(momentInstance)
          );
        });
      }
    } else {
      // Calculate the week number within the month
      const startOfMonth = momentInstance.clone().startOf("month");
      const weekNumber = Math.ceil(
        (momentInstance.date() - 1 + startOfMonth.day()) / 7
      );
      currentWeekNumber = weekNumber;
    }

    return (
      <>
        {/* Add week numbers, adds one button each row */}
        {showWeekNumbers && modifiers.has("first-day-of-week") && (
          <span
            className={`CalendarDayWeekNumber ${
              suppressClickOnWeekNumber ? "suppress-click-on-week-number" : ""
            }`}
          >
            W
            {customWeekNumberData
              ? currentWeek?.calendar_year_week
              : currentWeekNumber + 1}
          </span>
        )}
        <span className="CalendarDayNumber">{momentInstance.format("D")}</span>
      </>
    );
  }, []);

  const onPrevMonthClick = (params) => {
    const isNavButtonFocused =
      document.activeElement?.classList.contains(
        "DayPickerNavigation_leftButton__horizontalDefault"
      );
  
    if (isNavButtonFocused) {
      setTimeout(() => {
        const btn = dropDownContainerRef?.current?.querySelector(
          ".DayPickerNavigation_leftButton__horizontalDefault"
        );
  
        btn?.focus();
      }, 0);
    }
  
    args.onPrevMonthClick?.(params);
  };
  
  const onNextMonthClick = (params) => {
    const isNavButtonFocused =
      document.activeElement?.classList.contains(
        "DayPickerNavigation_rightButton__horizontalDefault"
      );
    if (isNavButtonFocused) {
      setTimeout(() => {
        const btn = dropDownContainerRef?.current?.querySelector(
          ".DayPickerNavigation_rightButton__horizontalDefault"
        );
  
        btn?.focus();
      }, 0);
    }
  
    args.onNextMonthClick?.(params);
  };

  if (withPortal) {
    return (
      <Portal container={portalContainer}>
        <div
          className={`impact-portal-container ${portalClassName}`}
          style={{
            top: position.y || position.top,
            left: position.x || position.left,
            bottom: position.bottom,
            right: position.right,
            width: position.offsetWidth || 0 + "px",
          }}
        >
          <div
            className={`impact-dateRangePicker-dropdown-container ${
              showRangeSelector ? "showRangeSelector" : ""
            }`}
            style={{
              ...customPosition,
            }}
            ref={dropDownContainerRef}
          >
            <div
              className={`dateRangePicker-left-container ${
                showWeekNumbers ? "showWeekNumbers" : ""
              }`}
            >
              <DayPickerRangeController
                {...args}
                onDatesChange={onDatesChange}
                onFocusChange={onFocusChange}
                focusedInput={focusedInput}
                startDate={startDate}
                endDate={endDate}
                hideKeyboardShortcutsPanel={true}
                daySize={26}
                horizontalMonthPadding={showWeekNumbers ? 16 : 12}
                startDateOffset={
                  startDateOffset
                    ? startDateOffset
                    : selectedRange === "custom"
                    ? undefined
                    : setStartDateOffset
                }
                endDateOffset={
                  endDateOffset
                    ? endDateOffset
                    : selectedRange === "custom"
                    ? undefined
                    : setEndDateOffset
                }
                renderDayContents={showWeekNumbers ? renderDayContents : null}
                renderMonthElement={
                  showMonthYearSelect
                    ? ({ month, onMonthSelect, onYearSelect }) => (
                        <ShowMonthYearSelect
                          customYears={customYears}
                          month={month}
                          onMonthSelect={onMonthSelect}
                          onYearSelect={onYearSelect}
                        />
                      )
                    : null
                }
                numberOfMonths={2}
                initialVisibleMonth={() => {
                  if (startDate) return startDate;
                  if (endDate) return endDate;
                  return moment();
                }}
                onPrevMonthClick={onPrevMonthClick}
                onNextMonthClick={onNextMonthClick}
              />
              <DateRangePickerFooter
                selectedDaysNumber={selectedDaysNumber}
                handleResetDates={handleResetDates}
                handleCancelDates={handleCancelDates}
                onSecondaryButtonClick={onSecondaryButtonClick}
                tertiaryButtonProps={tertiaryButtonProps}
                handleApplyDates={handleApplyDates}
                primaryButtonProps={primaryButtonProps}
                hasInputErrors={hasInputErrors}
              />
            </div>
            <div className="dateRangePicker-right-container">
              {showRangeSelector ? (
                <DateRangePickerCustom
                  handleRangeSelectorChange={handleRangeSelectorChange}
                  selectedRange={selectedRange}
                />
              ) : null}
            </div>
          </div>
        </div>
        <div
          className="ia-select-container-v3-blanket"
          onClick={() => setIsOpen(false)}
        />
      </Portal>
    );
  }

  return (
    <div
      className={`impact-dateRangePicker-dropdown-container ${
        showRangeSelector ? "showRangeSelector" : ""
      }`}
      ref={dropDownContainerRef}
      style={{
        ...customPosition,
      }}
    >
      <div
        className={`dateRangePicker-left-container ${
          showWeekNumbers ? "showWeekNumbers" : ""
        }`}
      >
        <DayPickerRangeController
          {...args}
          onDatesChange={onDatesChange}
          onFocusChange={onFocusChange}
          focusedInput={focusedInput}
          startDate={startDate}
          endDate={endDate}
          hideKeyboardShortcutsPanel={true}
          daySize={26}
          horizontalMonthPadding={showWeekNumbers ? 16 : 12}
          startDateOffset={
            startDateOffset
              ? startDateOffset
              : selectedRange === "custom"
              ? undefined
              : (day) => setStartDateOffset(selectedRange, day)
          }
          endDateOffset={
            endDateOffset
              ? endDateOffset
              : selectedRange === "custom"
              ? undefined
              : (day) => setEndDateOffset(selectedRange, day)
          }
          renderDayContents={showWeekNumbers ? renderDayContents : null}
          renderMonthElement={
            showMonthYearSelect
              ? ({ month, onMonthSelect, onYearSelect }) => (
                  <ShowMonthYearSelect
                    customYears={customYears}
                    month={month}
                    onMonthSelect={onMonthSelect}
                    onYearSelect={onYearSelect}
                  />
                )
              : null
          }
          numberOfMonths={2}
          initialVisibleMonth={() => {
            if (startDate) return startDate;
            if (endDate) return endDate;
            return moment();
          }}
          onPrevMonthClick={onPrevMonthClick}
          onNextMonthClick={onNextMonthClick}
        />
        <DateRangePickerFooter
          selectedDaysNumber={selectedDaysNumber}
          handleResetDates={handleResetDates}
          handleCancelDates={handleCancelDates}
          onSecondaryButtonClick={onSecondaryButtonClick}
          tertiaryButtonProps={tertiaryButtonProps}
          handleApplyDates={handleApplyDates}
          primaryButtonProps={primaryButtonProps}
          hasInputErrors={hasInputErrors}
        />
      </div>

      {showRangeSelector ? (
        <DateRangePickerCustom
          handleRangeSelectorChange={handleRangeSelectorChange}
          selectedRange={selectedRange}
        />
      ) : null}
    </div>
  );
}
