import React, { useState, useEffect } from "react";
import "./priceList.css";
import Image from "next/image";
import { getDaysRemaining } from "@/app/utils/datehelpers";
import { useAppSelector } from "../../../hooks/useDispatch";

interface PriceSelectorProps {
  event: any;
  onDurationSelect: (days: number, price: string) => void;
  initialSelectedDay?: number;
}

const PriceSelector: React.FC<PriceSelectorProps> = ({
  event,
  onDurationSelect,
  initialSelectedDay = 5,
}) => {
  console.log("event in the model+++", event);
  const { campaignForm, geoPricingData } = useAppSelector(
    (state) => state.compaign
  );
  const activeAdvertType = campaignForm.media_type || "image";
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedDay, setSelectedDay] = useState(initialSelectedDay);
  const itemsPerPage = 8;
  const totalDays = 30;
  const startFromDay = 5;

  const calculatePrice = (days: number) => {
    if (days === -1 || days > 30) {
      return "-";
    }

    if (!geoPricingData) {
      return "";
    }

    let basePrice: number;

    switch (campaignForm.advert_type) {
      case "medium":
        basePrice = parseFloat(geoPricingData.image.replace(",", "."));
        break;
      case "large":
        if (campaignForm.media_type === "rich text") {
          basePrice = parseFloat(
            geoPricingData.large_image_rich_text.replace(",", ".")
          );
        } else if (campaignForm.media_type === "video") {
          basePrice = parseFloat(
            geoPricingData.large_image_video.replace(",", ".")
          );
        } else {
          basePrice = parseFloat(geoPricingData.large_image.replace(",", "."));
        }
        break;
      case "pop under":
        basePrice = parseFloat(geoPricingData.banner.replace(",", "."));
        break;
      default:
        basePrice = parseFloat(geoPricingData.image.replace(",", "."));
    }

    const totalPrice = basePrice * days;
    const formattedPrice = totalPrice.toFixed(2).replace(".", ",");

    return formattedPrice;
  };

  const [price, setPrice] = useState(calculatePrice(selectedDay));
  const formatWithoutPx = campaignForm.format
    ? campaignForm.format.replace("px", "")
    : "250 x 350";

  const generateAllDays = () => {
    const allDays = [];
    for (let i = startFromDay; i <= totalDays; i++) {
      allDays.push({
        label: i === 1 ? "1 jour" : `${i} j`,
        days: i,
      });
    }
    return allDays;
  };

  const allDays = generateAllDays();
  const getCurrentDays = () => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    return allDays.slice(startIndex, endIndex);
  };

  const currentDays = getCurrentDays();
  const daysRemaining = getDaysRemaining(event.endDate);
  const maxAvailableDays = Math.min(daysRemaining, totalDays);

  const isDayAvailable = (days: number) => {
    if (days === 5) {
      return true;
    }
    return days <= maxAvailableDays;
  };

  const generatePlaceholderDays = (count: number) => {
    const placeholders = [];
    for (let i = 0; i < count; i++) {
      placeholders.push({
        label: "-",
        days: -1,
      });
    }
    return placeholders;
  };

  const getDaysWithPlaceholders = (daysArray: any[], requiredCount: number) => {
    if (daysArray.length >= requiredCount) {
      return daysArray.slice(0, requiredCount);
    }

    const placeholdersNeeded = requiredCount - daysArray.length;
    return [...daysArray, ...generatePlaceholderDays(placeholdersNeeded)];
  };

  const firstFourDaysWithPlaceholders = getDaysWithPlaceholders(
    currentDays.slice(0, 4),
    4
  );
  const nextFourDaysWithPlaceholders = getDaysWithPlaceholders(
    currentDays.slice(4, 8),
    4
  );

  const getNextPageItemsCount = () => {
    const nextStartIndex = currentPage * itemsPerPage;
    const nextEndIndex = nextStartIndex + itemsPerPage;
    return allDays.slice(nextStartIndex, nextEndIndex).length;
  };

  const nextPageItemsCount = getNextPageItemsCount();
  const hasNoNextItems = nextPageItemsCount === 0;

  const handleMoreClick = () => {
    const maxPage = Math.ceil(totalDays / itemsPerPage);
    if (currentPage < maxPage) {
      setCurrentPage(currentPage + 1);
    }
  };

  const handleLessClick = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  const handlePriceSelect = (days: number) => {
    if (isDayAvailable(days)) {
      setSelectedDay(days);
      const newPrice = calculatePrice(days);
      setPrice(newPrice);
      onDurationSelect(days, newPrice);
    }
  };

  const isPriceSelected = (days: number) => {
    return selectedDay === days;
  };

  return (
    <div className="price-content">
      <div className="price-header">
        <div className="header-content">
          <h2 className="event-title">{event?.title}</h2>
        </div>
      </div>

      <div className=" m-5"></div>

      <div className="days-container">
        <div className="dimension-box">
          <p className="dimension-text">{formatWithoutPx}</p>
        </div>
        <div className="days-section">
          <p className="days-label">Jours restants</p>
          <div className="days-counter">
            <span className="days-number">
              {getDaysRemaining(event.endDate)}
            </span>
          </div>
        </div>
      </div>

      <div className="image-container">{activeAdvertType}</div>

      <div className="divider-line section-divider-top"></div>

      <div>
        <div className="date-section">
          <div className="date-items">
            {firstFourDaysWithPlaceholders.map((day, index) => (
              <span
                key={`${currentPage}-first-${index}`}
                className={`date-item ${
                  !isDayAvailable(day.days) ? "date-item-disabled" : ""
                }`}
              >
                {day.label}
              </span>
            ))}
          </div>
        </div>

        <div className="divider-line"></div>

        <div className="price-section">
          <div className="price-items">
            {firstFourDaysWithPlaceholders.map((day, index) => (
              <div
                key={`${currentPage}-first-price-${index}`}
                className={`price-item-container ${
                  isPriceSelected(day.days) ? "price-item-selected" : ""
                } ${!isDayAvailable(day.days) ? "price-item-disabled" : ""}`}
                onClick={() => handlePriceSelect(day.days)}
              >
                <span
                  className={`price-item ${
                    !isDayAvailable(day.days) ? "price-item-disabled" : ""
                  }`}
                >
                  {calculatePrice(day.days)}
                  {calculatePrice(day.days) !== "-" ? "" : ""}
                </span>
              </div>
            ))}
          </div>
        </div>

        <>
          <div className="divider-line-green"></div>
          <div className="divider-line"></div>
        </>

        <div className="date-section">
          <div className="date-items">
            {nextFourDaysWithPlaceholders.map((day, index) => (
              <span
                key={`${currentPage}-first-${index}`}
                className={`date-item ${
                  !isDayAvailable(day.days) ? "date-item-disabled" : ""
                }`}
              >
                {day.label}
              </span>
            ))}
          </div>
        </div>

        <div className="divider-line"></div>

        <div className="price-section">
          <div className="price-items">
            {nextFourDaysWithPlaceholders.map((day, index) => (
              <div
                key={`${currentPage}-second-price-${index}`}
                className={`price-item-container ${
                  isPriceSelected(day.days) ? "price-item-selected" : ""
                } ${!isDayAvailable(day.days) ? "price-item-disabled" : ""}`}
                onClick={() => handlePriceSelect(day.days)}
              >
                <span
                  className={`price-item ${
                    !isDayAvailable(day.days) ? "price-item-disabled" : ""
                  }`}
                >
                  {calculatePrice(day.days)}
                  {calculatePrice(day.days) !== "-" ? "" : ""}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="more-section">
        <span
          className={`more-text less-text ${currentPage > 1 ? "" : "hidden"}`}
          style={{ color: "#299b13" }}
          onClick={handleLessClick}
        >
          moins...
        </span>
        {daysRemaining > 12 && (
          <span
            className={`more-text ${hasNoNextItems ? "more-section-blur" : ""}`}
            style={{ color: "#299b13" }}
            onClick={handleMoreClick}
          >
            plus...
          </span>
        )}
      </div>
    </div>
  );
};

export default PriceSelector;
