import { Layout, Image, Button, Form, Skeleton } from "antd";
import ProHeader from "components/ProHeader/ProHeader";
import { useTranslation } from "react-i18next";
import styles from "./CardDetails.module.css";
import ProText from "components/ProText";
import { useGetEGiftCardsQuery } from "redux/api/others";
import { selectCart } from "features/order/orderSlice";
import { useAppSelector } from "redux/hooks";
import { useState, useEffect, useCallback } from "react";
import BackIcon from "components/Icons/BackIcon";
import NextIcon from "components/Icons/NextIcon";
import cardStyles from "./CardDetails.module.css";
import ReceivernformationCard from "./components/ReceivernformationCard/ReceivernformationCard";
import SenderformationCard from "./components/SenderformationCard/SenderformationCard";
import TimeEstimateCard from "pages/cart/components/timeEstimate/TimeEstimateCard";
import { useNavigate, useParams } from "react-router-dom";
import GiftAmountCard from "./components/GiftAmountCard/GiftAmountCard";
import { GiftAmountBottomSheet } from "./components/GiftAmountBottomSheet";

export default function CardDetailsPage() {
  const { t } = useTranslation();
  const { data: cards, isLoading } = useGetEGiftCardsQuery();
  const { giftDetails } = useAppSelector(selectCart);
  const { isRTL } = useAppSelector((state) => state.locale);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isGiftAmountBottomSheetOpen, setIsGiftAmountBottomSheetOpen] = useState(false);
  const { subdomain } = useParams();
  const navigate = useNavigate();

  // Find the initial index based on selected cardId from gift details
  useEffect(() => {
    if (cards && giftDetails?.cardId) {
      const index = cards.findIndex(
        (card) => card?.id?.toString() === giftDetails.cardId,
      );
      if (index !== -1) {
        setCurrentIndex(index);
      }
    }
  }, [cards, giftDetails?.cardId]);

  const handlePrevious = () => {
    if (cards && cards.length > 0) {
      setCurrentIndex((prev) => (prev === 0 ? cards.length - 1 : prev - 1));
    }
  };

  const handleNext = () => {
    if (cards && cards.length > 0) {
      setCurrentIndex((prev) => (prev === cards.length - 1 ? 0 : prev + 1));
    }
  };

  const currentCard = cards && cards.length > 0 ? cards[currentIndex] : null;

  const handleCheckout = useCallback(() => {
    navigate(`/${subdomain}/checkout`);
  }, [subdomain]);

  return (
    <>
    <Layout>
      <ProHeader>{t("cardDetails.title")}</ProHeader>
      <Layout.Content className={styles.checkoutContainer}>
        <div
          style={{
            textAlign: "center",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
            margin: "50px 28px 35px 28px",
            gap: 8,
          }}
        >
          <ProText style={{ fontSize: 16, fontWeight: 600, color: "#333333" }}>
            {t("cardDetails.addGiftDetails")}
          </ProText>
          <ProText style={{ fontSize: 14, fontWeight: 400, color: "#95949C" }}>
            {t("cardDetails.description")}
          </ProText>
        </div>
        {isLoading || !currentCard ? (
          <div className={cardStyles.carouselContainer}>
            <Skeleton.Avatar
              active
              size={40}
              shape="circle"
              style={{ flexShrink: 0 }}
            />
            <div className={cardStyles.cardWrapper}>
              <Skeleton.Image
                active
                style={{
                  width: 205,
                  height: 134,
                  borderRadius: 8,
                }}
              />
            </div>
            <Skeleton.Avatar
              active
              size={40}
              shape="circle"
              style={{ flexShrink: 0 }}
            />
          </div>
        ) : (
          <div className={cardStyles.carouselContainer}>
            <Button
              type="text"
              className={cardStyles.arrowButton}
              onClick={isRTL ? handleNext : handlePrevious}
              icon={<BackIcon iconSize={24} />}
            />
            <div className={cardStyles.cardWrapper}>
              <Image
                src={currentCard.imageURL}
                alt={currentCard.image}
                width={205}
                height={134}
                className={cardStyles.cardImage}
              />
            </div>
            <Button
              type="text"
              className={cardStyles.arrowButton}
              onClick={isRTL ? handlePrevious : handleNext}
              icon={<NextIcon iconSize={24} />}
            />
          </div>
        )}
        <Form
          layout="vertical"
          style={{ display: "flex", flexDirection: "column", gap: 16 }}
        >
          {giftDetails?.giftType !== "items" && <GiftAmountCard onOpen={() => setIsGiftAmountBottomSheetOpen(true)} />}
          <ReceivernformationCard />
          <SenderformationCard />
          <TimeEstimateCard />
        </Form>
      </Layout.Content>
      <Layout.Footer className={styles.checkoutButtonContainer}>
        <Button
          type="primary"
          shape="round"
          className={styles.checkoutButton}
          onClick={handleCheckout}
        >
          {t("cardDetails.checkout")}
        </Button>
      </Layout.Footer>
    </Layout>
    <GiftAmountBottomSheet isOpen={isGiftAmountBottomSheetOpen} onClose={() => setIsGiftAmountBottomSheetOpen(false)} />
    </>
  );
}
