"use client";

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

type BankAccountCardProps = {
  id: number;
  bankLogo: string;
  bankName: string;
  accountName: string;
  minBalance?: number | null;
  minIncome?: number | null;
  accountType?: string;
  features: string[];
  offers?: string[];
  accountUrl?: string;
};

export default function BankAccountCard({
  id,
  bankLogo,
  bankName,
  accountName,
  minBalance,
  minIncome,
  accountType,
  features,
  offers = [],
  accountUrl,
}: BankAccountCardProps) {
  const [isChecked, setIsChecked] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);
  const [canScrollRight, setCanScrollRight] = 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 scroll = (direction: "left" | "right") => {
    if (!scrollRef.current) return;
    scrollRef.current.scrollBy({ left: direction === "right" ? 200 : -200, behavior: "smooth" });
  };

  const handleCheckbox = (e: React.ChangeEvent<HTMLInputElement>) => {
    setIsChecked(e.target.checked);
  };

  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 ? `${bankName} - ${accountName}` : "Bank Account Logo"} 
            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">{accountName}</p>
              {accountType && <span className="text-xs text-blue-600">{accountType}</span>}
            </div>

            {minBalance !== undefined && (
              <div className="flex flex-col w-1/2 md:flex-1">
                <span className="text-sm font-medium text-gray-800">Minimum Balance</span>
                <span className="text-xs text-gray-600 mb-0">(AED): {minBalance ?? "N/A"}</span>
              </div>
            )}

            {minIncome !== undefined && (
              <div className="flex flex-col w-1/2 md:flex-1">
                <span className="text-sm font-medium text-gray-800">Minimum Income</span>
                <span className="text-xs text-gray-600 mb-0">(AED): {minIncome ?? "N/A"}</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-2 pb-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>
      )}

      {/* Buttons Row (Always Visible) */}
      <div className={`flex flex-col md:flex-row justify-between items-start gap-1 ${offers.length > 0 ? 'p-8 pt-2' : 'p-8 pt-0'}`}>
        <div className="flex-1" />
        
        <div className="flex flex-col gap-2 w-full md:w-auto">
          {accountUrl ? (
            <a
              href={accountUrl}
              target="_blank"
              rel="noopener noreferrer"
              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
            </a>
          ) : (
            <button
              type="button"
              disabled
              className="w-auto md:w-[140px] border border-blue-300 text-center text-blue-300 px-3 py-1 text-sm font-semibold rounded-md cursor-not-allowed"
            >
              Apply Now
            </button>
          )}
          <a
            href={`/bankaccounts/${id}`}
            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>
      </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>
  );
}
