"use client";


import Image from "next/image";
import { ChevronRight } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import BankLoanApplyModal from "./BankLoanApplyModal";

type BankLoanCardProps = {
  id: number;
  bankLogo: string;
  bankName: string;
  planName: string;
  minSalary: number;
  flatRate: string;
  reducingRate: string;
  loanUrl?: string | null;
  features: string[];
  offers?: string[];
  onCompareChange: (checked: boolean, loan: { id: number; name: string }) => void;
};

export default function BankLoanCard({
  id,
  bankLogo,
  bankName,
  planName,
  minSalary,
  flatRate,
  reducingRate,
  loanUrl,
  features,
  offers = [],
  onCompareChange,
}: BankLoanCardProps) {
  const [isChecked, setIsChecked] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);
  const [canScrollRight, setCanScrollRight] = useState(false);
  const [showApplyModal, setShowApplyModal] = useState(false);

  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);
  }, [features]);

  const handleCheckbox = (e: React.ChangeEvent<HTMLInputElement>) => {
    const checked = e.target.checked;
    setIsChecked(checked);
    onCompareChange(checked, { id, name: planName });
  };

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

  return (
    <div className="border rounded-sm shadow-sm bg-white overflow-hidden w-full text-sm">
      <div className="flex p-2 gap-4 items-start relative">
        {/* Left Column: Image */}
        <div className="flex-shrink-0 w-32 h-32">
          <Image 
            src={bankLogo || "/default.webp"} 
            alt={bankName} 
            width={150} 
            height={150} 
            className="object-contain rounded-md w-full h-full" 
            unoptimized={true}
            onError={(e) => {
              const img = e.target as HTMLImageElement;
              img.src = "/default.webp";
            }}
          />
        </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">{bankName}</h3>
              <p className="text-xs text-gray-600 mb-0">{planName}</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): {minSalary}</span>
            </div>

            <div className="flex flex-col w-1/2 md:flex-1">
              <span className="text-sm font-medium text-gray-800">Fixed Rate</span>
              <span className="text-xs text-gray-600 mb-0">{flatRate}</span>
            </div>

            <div className="flex flex-col w-1/2 md:flex-1">
              <span className="text-sm font-medium text-gray-800">Reducing Rate</span>
              <span className="text-xs text-gray-600 mb-0">{reducingRate}</span>
            </div>
          </div>

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

      {/* Offers + Buttons Row */}
      {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">
              {offers.map((offer, idx) => (
                <li key={idx}>{offer}</li>
              ))}
            </ul>
          </div>

          <div className="flex flex-col gap-2 w-full md:w-auto mt-0">
            <button
              type="button"
              onClick={() => setShowApplyModal(true)}
              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 Now
            </button>
            <a
              href={`/loandetails?loanurl=${loanUrl}`}
              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>
            {/* Compare Checkbox below buttons */}
            <label className="flex items-center justify-center space-x-2 text-sm text-gray-600 cursor-pointer mt-1">
              <input
                type="checkbox"
                checked={isChecked}
                onChange={handleCheckbox}
                className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
              />
              <span>Compare</span>
            </label>
          </div>
              {/* Loan Apply Modal */}
              {showApplyModal && (
                <BankLoanApplyModal
                  open={showApplyModal}
                  onClose={() => setShowApplyModal(false)}
                  loan={{
                    id,
                    name: planName,
                    bankname: bankName,
                    minIncome: minSalary,
                    image: bankLogo,
                    features: features.map((details, idx) => ({ id: idx, details })),
                    offers: (offers || []).map((details, idx) => ({ id: idx, details })),
                    flatRate,
                    reducingRate,
                  }}
                />
              )}
        </div>
      )}

      {/* Features Section */}
      {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 */}
            {features.map((feature, idx) => (
              <div
                key={idx}
                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}</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>
      )}
    </div>
  );
}
