import { Link, useParams } from "react-router-dom";
import { ArrowLeft, ChevronRight, Ear } from "lucide-react";
import { useEffect,useState } from "react";
import { normalizeDrupalUrl } from "../services/drupalAPI";
import { getNodes,getTermByTid } from "../services/drupalAPI";
import { getIcon } from "../utils/lucideIcon";

function HearingAidBrandDetail() {
  const { brandId } = useParams();
  const [products, setProducts] = useState([]);
  const [brand, setBrand] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);



  useEffect(() => {
      if (!brandId) return;

      

      Promise.all([
        getNodes('hearing_aid', [{ fieldName: 'field_images', mode: 'media', mediaSourceField: 'field_media_image' }]),
        getTermByTid('hearing_classification', brandId, [{ fieldName: 'field_icon', mode: 'file' }])
      ])
        .then(([productsData, brandData]) => {
          setProducts(productsData);
          setBrand(brandData);
        })
        .catch(setError)
        .finally(() => setLoading(false));
  }, [brandId]);
  console.log(brand);
  console.log(products);
  const filteredProducts = products.filter(product => product.relationships.field_category?.data?.id === brand?.id);
   if (loading) return <p>Loading...</p>;
   if (error) return <p>Error: {error.message}</p>;

const getImageUrl = (product) => {
  const resolved = product.field_images_resolved;
  if (!resolved) return null;
  const url = Array.isArray(resolved)
    ? resolved[0]?.file?.attributes?.uri?.url
    : resolved.file?.attributes?.uri?.url;
  return normalizeDrupalUrl(url);
  };

 

  const getIconUrl = (brand, fieldName = 'field_icon') => {
  if (!brand) return null;
  const resolved = brand[`${fieldName}_resolved`];
  if (!resolved) return null;

  const raw = Array.isArray(resolved)
    ? resolved[0]?.attributes?.uri?.url          // file mode — unlimited
    : resolved?.attributes?.uri?.url             // file mode — single
    ?? resolved?.file?.attributes?.uri?.url;     // media mode — fallback

  return normalizeDrupalUrl(raw);
};



  return (
    <main className="min-h-screen bg-[color:var(--hearex-light-bg)]">
      <section className="relative py-8 lg:py-8 bg-gradient-to-br from-[#f8f9fa] to-[#e8f5d8] flex items-center">
        <div className="mx-auto w-full max-w-6xl px-4 sm:px-6 lg:px-8">
          <Link
            to="/"
            className="mb-8 inline-flex items-center gap-2 text-sm font-semibold text-[color:var(--secondary)] hover:text-[color:var(--hearex-green)]"
          >
            <ArrowLeft size={16} />
            Back to Our Hearing Aid
          </Link>

          <div className="py-2">
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center">
              <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-[color:var(--hearex-green)] shadow-md">
                <img
                  src={getIconUrl(brand)}
                  alt={`${brand.attributes.name} icon`}
                  className="h-6 w-6 text-white"
                />
                
              </div>
              <h1 className="text-4xl font-bold tracking-tight text-[color:var(--secondary)] sm:text-5xl">
                {brand.attributes.name}
              </h1>
            </div>
            <div className="mt-6 w-full text-base text-[color:var(--muted-foreground)] sm:text-lg">
             {brand.attributes.description.processed
                      ? <div dangerouslySetInnerHTML={{ __html: `${brand.attributes.description.processed}` }} />
                      : `${brand.attributes.description?.value || ''}`}
            </div>
          </div>
        </div>
      </section>

      <section className="mx-auto max-w-6xl px-4 py-14 sm:px-6 lg:px-8">
        <div className="mt-10">
          <div className="mb-7 text-center">
            <h2 className="text-3xl font-bold text-[color:var(--secondary)]">Available Products</h2>
            <p className="mx-auto mt-3 max-w-3xl text-[color:var(--muted-foreground)]">
              State-of-the-art diagnostic equipment for comprehensive hearing assessments
              and precise audiological evaluations.
            </p>
          </div>
          <div className="mt-5 grid gap-6 md:grid-cols-2 xl:grid-cols-3">
            {filteredProducts.map((product) => (
              <article
                key={product.id}
                className="group overflow-hidden rounded-2xl border-0 bg-[color:var(--card)] shadow-lg transition-all duration-500 hover:-translate-y-1 hover:shadow-2xl"
              >
                <div className="relative h-40 overflow-hidden">
                 <div className="absolute top-6 left-6 w-14 h-14 bg-[#8ac642] rounded-full flex items-center justify-center">
                    {getIcon(product.attributes.field_lucide_icon, { className: "w-7 h-7 text-white" })}
                  </div>
                  <img
                    src={getImageUrl(product)}
                    alt={product.attributes.title}
                    className="h-full w-full object-cover transition duration-500 group-hover:scale-105"
                  />
                </div>
                <div className="p-5">
                  <h3 className="text-lg font-semibold text-[color:var(--secondary)]">{product.attributes.title}</h3>
                  <p className="mt-2 text-sm text-[color:var(--muted-foreground)]">
                    {product.attributes?.body?.processed
                      ? product.attributes.body.processed.replace(/<[^>]+>/g, '').slice(0, 100) + '...'
                      : 'No description available.'}
                  </p>
                  <Link
                    to={`/product/${brandId}/${product.attributes.drupal_internal__nid}`}
                    className="mt-5 inline-flex items-center gap-2 rounded-lg bg-[color:var(--hearex-green)] px-4 py-2 text-sm font-semibold text-[color:var(--primary-foreground)]"
                  >
                    View Details
                    <ChevronRight size={16} />
                  </Link>
                </div>
              </article>
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

export default HearingAidBrandDetail;