import React, { useState, useEffect } from "react";
import "./priceList.css";
import Image from "next/image";
import { getDaysRemaining } from "@/app/utils/datehelpers";
import {
  addToSelectedEvents,
  resetPrice,
} from "../../../redux/features/main/campaigns/advertAction";
import { useAppDispatch } from "../../../hooks/useDispatch";
interface Event {
  title: string;
  description: string;
  cover_image: string;
  id: number;
  start_date: string;
  end_date: string;
  city_name: string;
  slug: string;
  facebookEventId: string;
  have_endDateTime_timeStamp: number;
  time: string;
  end_time: string;
  event_lat: string;
  event_long: string;
  postal_code: string;
  pricing: any;
}

interface PriceListContentProps {
  event: Event;
  onBack: () => void;
  handleEventClick: any;
}

import { useAppSelector } from "../../../hooks/useDispatch";

const PriceListContent: React.FC<PriceListContentProps> = ({
  event,
  onBack,
  handleEventClick,
}) => {
  const dispatch = useAppDispatch();
  const eventTier = event.pricing?.tier;
  const { campaignForm, geoPricingDataArray } = useAppSelector(
    (state) => state.compaign
  );
  const activeAdvertType = campaignForm.media_type || "image";
  const geoPricingData = geoPricingDataArray?.find(
    (item: any) => item.tier === eventTier
  );
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedDay, setSelectedDay] = useState(5);
  const itemsPerPage = 8;
  const totalDays = 30;
  const startFromDay = 5;

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

    // If geoPricingData is not available yet, return empty string
    if (!geoPricingData) {
      return { price: "", euro: "" };
    }

    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;

    // Format the price with comma as decimal separator (French format)
    const formattedPrice = totalPrice.toFixed(2).replace(".", ",");

    return { price: formattedPrice, euro: "€" };
  };
  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.end_date);
  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) => {
    setSelectedDay(days);
    const price = calculatePrice(days);
    setPrice(price);
  };
  const handleCartClick = () => {
    const priceString = `${price.price}`;
    handleEventClick(event, priceString, selectedDay);
    dispatch(addToSelectedEvents());
    dispatch(resetPrice());
  };
  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 className="location-info">
            <Image
              src="/location.svg"
              alt="location"
              className="location-icon"
              width={24}
              height={24}
              priority
            />
            <p className="location-text">
              {event?.city_name + " " + event?.postal_code}
            </p>
          </div>
        </div>
        <div className="cross">
          <button onClick={onBack}>
            <svg
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M18 6L6 18"
                stroke="#6B7280"
                strokeWidth="2"
                strokeLinecap="round"
              />
              <path
                d="M6 6L18 18"
                stroke="#6B7280"
                strokeWidth="2"
                strokeLinecap="round"
              />
            </svg>
          </button>
        </div>
      </div>

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

      <div className="days-container">
        <div className="dimension-box">
          <p className="dimension-text">{formatWithoutPx}</p>
        </div>
        <div className="days-section">
          <p className="days-label">Days to run</p>
          <div className="days-counter">
            <span className="days-number">
              {getDaysRemaining(event.end_date)}
            </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) => {
              const priceData = calculatePrice(day.days);
              return (
                <div
                  key={`${currentPage}-first-price-${index}`}
                  className={`price-item-container ${
                    isPriceSelected(day.days) ? "price-item-selected" : ""
                  } ${!isDayAvailable(day.days) ? "price-item-disabled" : ""}`}
                  onClick={() =>
                    isDayAvailable(day.days) && handlePriceSelect(day.days)
                  }
                >
                  <span
                    className={`price-item ${
                      !isDayAvailable(day.days) ? "price-item-disabled" : ""
                    }`}
                  >
                    <span className="price-amount">{priceData.price}</span>
                    <span className="euro-symbol">{priceData.euro}</span>
                  </span>
                </div>
              );
            })}
          </div>
        </div>
        {/* {nextFourDays.length >= 4 && ( */}
        <>
          <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>
        {/* {nextFourDays.length >= 4 &&  */}
        <div className="divider-line"></div>
        {/* } */}
        <div className="price-section">
          <div className="price-items">
            {nextFourDaysWithPlaceholders.map((day, index) => {
              const priceData = calculatePrice(day.days);
              return (
                <div
                  key={`${currentPage}-first-price-${index}`}
                  className={`price-item-container ${
                    isPriceSelected(day.days) ? "price-item-selected" : ""
                  } ${!isDayAvailable(day.days) ? "price-item-disabled" : ""}`}
                  onClick={() =>
                    isDayAvailable(day.days) && handlePriceSelect(day.days)
                  }
                >
                  <span
                    className={`price-item ${
                      !isDayAvailable(day.days) ? "price-item-disabled" : ""
                    }`}
                  >
                    <span className="price-amount">{priceData.price}</span>
                    <span className="euro-symbol">{priceData.euro}</span>
                  </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
        className="close-button-container"
        style={{
          marginTop:
            daysRemaining > 12 || currentPage > 1 ? "0.5rem" : "1.5rem",
        }}
      >
        <button className="close-action-button" onClick={handleCartClick}>
          <Image
            src="/cart.svg"
            alt="Price info"
            className="cart-icon"
            width={36}
            height={36}
          />
        </button>
      </div>
    </div>
  );
};

export default PriceListContent;
