// components/customui/SimpleCardDetails.tsx
'use client';

import { useState } from 'react';
import Image from 'next/image';
import { Button } from "@/components/ui/button";
import CreditCardApplyModal from "@/components/customui/CreditCardApplyModal";
import { getPublicBaseUrl } from "@/lib/publicBaseUrl";
import { CheckCircle } from "lucide-react";

interface CardDetailsRow {
  benefitid: number;
  benefitdetails: string;
  benfitcatgory: string;
}

interface CardDetailsProps {
  id: number;
  title: string;
  image: string;
  details: { label: string; value: string }[];
  benefits: string[];
  creditcarddetails?: CardDetailsRow[];
}

type Feature = { id: number; details: string };
type Offer = { id: number; details: string };

interface Card {
  id: number;
  name: string;
  minSalary: string;
  annualFee: string;
  image: string;
  points: string[];
  features: Feature[];
  offers: Offer[];
}

export default function SimpleCardDetails({
  id,
  title,
  image,
  details,
  benefits,
  creditcarddetails = [],
}: CardDetailsProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedCard, setSelectedCard] = useState<Card | null>(null);

  const openApplyModal = async (cardId: number) => {
    try {
      const baseUrl = getPublicBaseUrl();
      const res = await fetch(
        `${baseUrl}/api/applycard/${encodeURIComponent(String(cardId))}`
      );
      if (!res.ok) throw new Error("Failed to fetch card details");

      const fullCard: Card = await res.json();

      if (
        !Array.isArray(fullCard.features) ||
        !Array.isArray(fullCard.offers)
      ) {
        throw new Error("Invalid card data structure");
      }

      setSelectedCard(fullCard);
      setIsModalOpen(true);
    } catch (err) {
      console.error("[ERROR] openApplyModal failed:", err);
      // Handle error, e.g., show a toast notification
    }
  };

  const safeImage = image || "/default.webp";
  const safeDetails = Array.isArray(details) ? details : [];
  const safeBenefits = Array.isArray(benefits) ? benefits : [];

  const groupedDetails = creditcarddetails.reduce((acc, item) => {
    const category = item.benfitcatgory;
    if (!acc[category]) acc[category] = [];
    acc[category].push(item.benefitdetails);
    return acc;
  }, {} as Record<string, string[]>);

  const getDetail = (label: string) =>
    safeDetails.find((d) =>
      d.label.toLowerCase().includes(label.toLowerCase())
    )?.value || "N/A";

  return (
    <div className="border border-blue-300 rounded-lg p-6 shadow-sm max-w-md w-full mx-auto text-center sm:text-left">
      {/* Title */}
      <h2 className="text-xl font-semibold mb-4">{title}</h2>

      {/* Card Image */}
      <div className="flex justify-center sm:justify-start">
        <Image
          src={safeImage}
          alt={title}
          width={300}
          height={160}
          className="rounded-md object-contain w-64 h-36"
          unoptimized={false}
        />
      </div>

      {/* Minimum Salary */}
      <div className="mt-4 text-sm font-medium text-gray-700">
        Minimum Salary:
        <div className="text-gray-900 font-normal mt-1">{getDetail("salary")}</div>
      </div>

      {/* Annual Fee */}
      <div className="mt-4 text-sm font-medium text-gray-700">
        Annual Fee:
        <div className="text-gray-900 font-normal mt-1">{getDetail("annual")}</div>
      </div>

      {/* Apply Now Button */}
      <div className="mt-6">
        <Button
          onClick={() => openApplyModal(id)}
          className="bg-blue-600 text-white px-6 py-2 w-full sm:w-auto"
        >
          Apply Now
        </Button>
      </div>

      {/* Main Benefits */}
      {safeBenefits.length > 0 && (
        <div className="mt-6 border border-blue-300 p-6 rounded-lg">
          <h3 className="text-lg font-semibold text-blue-700">Main Benefits</h3>
          <ul className="mt-3 space-y-2 text-sm text-gray-700">
            {safeBenefits.map((benefit, index) => (
              <li key={index} className="flex items-start gap-2">
                <CheckCircle className="w-4 h-4 text-green-500 mt-1" />
                <span>{benefit}</span>
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Grouped Benefit Categories */}
      {Object.entries(groupedDetails).map(([category, items]) => (
        <div key={category} className="mt-6 border border-blue-300 p-6 rounded-lg">
          <h3 className="text-lg font-semibold text-blue-700">{category}</h3>
          <ul className="mt-3 space-y-2 text-sm text-gray-700">
            {items.map((detail, index) => (
              <li key={index} className="flex items-start gap-2">
                <CheckCircle className="w-4 h-4 text-green-500 mt-1" />
                <span>{detail}</span>
              </li>
            ))}
          </ul>
        </div>
      ))}

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