"use client";
import React, { useRef, useState, useEffect } from "react";
import Image from "next/image";
import { ChevronRight } from "lucide-react";
import CreditCardApplyModal from "@/components/customui/CreditCardApplyModal";

interface Feature {
  id: number;
  details: string;
}

interface Offer {
  id: number;
  details: string;
}

interface CreditCard {
  id: number;
  name: string;
  bankname: string;
  minSalary: number;
  annualFee: string;
  image: string;
  ccurl: string; // Assuming this is the URL for card details
  features: Feature[];
  offers: Offer[];
}

const Card: React.FC<{ card: CreditCard }> = ({ card }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedCard, setSelectedCard] = useState<CreditCard | null>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const [canScrollRight, setCanScrollRight] = useState(false);

  // Check if horizontal scrolling is possible
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;

    const checkScrollable = () => {
      setCanScrollRight(el.scrollWidth > el.clientWidth);
    };

    checkScrollable();

    window.addEventListener("resize", checkScrollable);
    return () => window.removeEventListener("resize", checkScrollable);
  }, [card.features]);

  const scroll = (direction: "left" | "right") => {
    if (scrollRef.current) {
      scrollRef.current.scrollBy({
        left: direction === "right" ? 200 : -200,
        behavior: "smooth",
      });
    }
  };

  const openApplyModal = async (cardId: number) => {
    try {
      const res = await fetch(`/api/applycard/${cardId}`);
      if (!res.ok) throw new Error("Failed to fetch card details");
      const fullCard = await res.json();
      setSelectedCard(fullCard);
      setIsModalOpen(true);
    } catch (err) {
      alert(`Error loading card details: ${err}`);
    }
  };

  return (
    <div className="border rounded-sm shadow-sm bg-white h-25 overflow-hidden w-full text-sm">
      <div className="flex p-2 gap-4 items-start relative">
        {/* Left Column: Image */}
        <div className="flex-shrink-0">
          <Image
            src={card.image && card.image.trim() !== "" ? card.image : "/default.webp"}
            alt={card.name || "Card Image"}
            width={150}
            height={150}
            className="object-contain rounded-md"
            priority
          />
        </div>

        {/* Right Column: Details */}
        <div className="flex-1">
          <div className="flex flex-wrap w-full gap-x-6 gap-y-2 items-start">
            <div className="flex flex-col w-full md:flex-[2]">
              <h3 className="text-sm font-medium text-gray-800 mb-0">{card.bankname}</h3>
              <p className="text-xs text-gray-600 mb-0">{card.name}</p>
            </div>

            <div className="flex flex-col w-1/2 md:flex-1">
              <span className="text-sm font-medium text-gray-800">Minimum Salary</span>
              <span className="text-xs text-gray-600 mb-0">(AED): {card.minSalary}</span>
            </div>

            <div className="flex flex-col w-1/2 md:flex-1">
              <span className="text-sm font-medium text-gray-800">Annual Fee</span>
              <span className="text-xs text-gray-600 mb-0">{card.annualFee}</span>
            </div>
          </div>

          <div className="block w-full h-px bg-gray-300 mt-2 mb-1" />
        </div>
      </div>

      {/* Offers + Buttons Row */}
      {card.offers && card.offers.length > 0 && (
        <div className="flex flex-col md:flex-row justify-between items-start gap-1 p-8 pt-0">
          <div className="flex-1">
            <div className="flex items-center gap-1 mb-1">
              <span className="text-green-600 font-semibold text-sm">🎁 Offers</span>
            </div>
            <ul className="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-1 list-disc list-inside text-gray-700 text-xs">
              {card.offers.map((offer) => (
                <li key={offer.id}>{offer.details}</li>
              ))}
            </ul>
          </div>

          <div className="flex flex-col gap-2 w-full md:w-auto mt-0">
            <button
              onClick={() => openApplyModal(card.id)}
              className="w-auto md:w-[140px] border border-blue-500 text-center text-blue-500 px-3 py-1 text-sm font-semibold rounded-md hover:bg-blue-500 hover:text-white"
            >
              Apply
            </button>
            <a
            href={`/carddetails?cardno=${card.ccurl}`}
              className="w-auto md:w-[140px] border border-red-500 text-center text-red-500 px-3 py-1 text-sm font-semibold rounded-md hover:bg-red-500 hover:text-white"
            >
              Know More
            </a>
          </div>
        </div>
      )}

      {/* Features Section */}
      {card.features && card.features.length > 0 && (
        <div className="mt-0 bg-yellow-100 p-2 rounded-md flex items-center w-full text-xs">
          {/* Scrollable container with sticky label */}
          <div
            ref={scrollRef}
            className="flex overflow-x-auto no-scrollbar bg-yellow-100 px-0 py-1 rounded-md text-[11px] flex-1 relative"
          >
            {/* Sticky label */}
            <span
              className="font-semibold text-xs text-gray-800 whitespace-nowrap sticky left-0 z-10 bg-yellow-100 px-0 py-1 border-r border-yellow-300"
            >
              ✨ Features:
            </span>

            {/* Features */}
            {card.features.map((feature) => (
              <div
                key={feature.id}
                className="flex-shrink-0 flex items-center text-gray-700 px-1 py-0.5 rounded whitespace-nowrap"
              >
                <span className="text-green-600 text-xs mr-0.5">✔</span>
                <span>{feature.details}</span>
              </div>
            ))}
          </div>

          {/* Right Arrow: only show if scrollable */}
          {canScrollRight && (
            <button
              onClick={() => scroll("right")}
              className="p-1 rounded-full bg-transparent text-blue-700 shadow hover:bg-gray-100 flex-shrink-0 ml-1"
              aria-label="Scroll right"
            >
              <ChevronRight className="w-4 h-4" />
            </button>
          )}
        </div>
      )}

      {/* Modal */}
      {selectedCard && (
        <CreditCardApplyModal
          open={isModalOpen}
          onClose={() => setIsModalOpen(false)}
          card={{
            id: selectedCard.id,
            name: selectedCard.name,
            bankname: selectedCard.bankname,
            minSalary: selectedCard.minSalary,
            annualFee: selectedCard.annualFee,
            image: selectedCard.image,
            features: selectedCard.features,
            offers: selectedCard.offers,
          }}
        />
      )}
    </div>
  );
};

export default Card;
