import { Link } from "react-router-dom";
import { useEffect , useState } from "react";
import { ChevronRight } from "lucide-react";
import { getNodes,getTerms } from "../services/drupalAPI";
import { normalizeDrupalUrl } from "../services/drupalAPI";

function BrandCard({ title, tagline, image, linkTo }) {
  return (
    <article 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-44 overflow-hidden">
        <img
          src={image}
          alt={title}
          className="h-full w-full object-cover transition duration-500 group-hover:scale-105"
        />
      </div>
      <div className="p-6">
        <h3 className="text-lg font-semibold text-[color:var(--secondary)]">{title}</h3>
        <div className="mt-2 text-sm text-[color:var(--muted-foreground)]" dangerouslySetInnerHTML={{ __html: tagline }} />
        <Link
          to={linkTo}
          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)]"
        >
          Learn More
          <ChevronRight size={16} />
        </Link>
      </div>
    </article>
  );
}

function BrandsSection() {
    const [Brands, setBrands] = useState([]);
    const [Devices, setDevices] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
 
    useEffect(() => {
        getNodes('devices', [{ fieldName: 'field_images', mode: 'media', mediaSourceField: 'field_media_image' }])
          .then(setDevices)
          .catch(setError)
          .finally(() => setLoading(false));
        getTerms('hearing_classification', [{ fieldName: 'field_image', mode: 'media', mediaSourceField: 'field_media_image' }])
          .then(setBrands)
          .catch(setError)
          .finally(() => setLoading(false));
      }, []);
     
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error: {error.message}</p>;

      const getImageDevicesUrl = (device) => {
        const resolved = device.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 getImageBrandsUrl = (brand) => {
        const resolved = brand.field_image_resolved;
        if (!resolved) return null;
        const url = Array.isArray(resolved)
          ? resolved[0]?.file?.attributes?.uri?.url
          : resolved.file?.attributes?.uri?.url;
        return normalizeDrupalUrl(url);
    };

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;
  return (
   
      <section className="mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8 bg-[color:var(--hearex-light-bg)]">
        <div id="hearing-aids">
          <div className="mb-6 text-center">
            <h2 className="text-2xl font-bold text-[color:var(--secondary)]">Our Hearing Aid</h2>
          </div>
          <p className="mx-auto mb-6 max-w-3xl text-center text-[color:var(--muted-foreground)]">
            Advanced hearing solutions from world-renowned manufacturers, designed to
            restore natural hearing and improve quality of life.
          </p>
          <div className="brandCard grid gap-6 md:grid-cols-2 xl:grid-cols-3">
            {Brands.map((brand) => (
              <BrandCard
                key={brand.id}
                title={brand.attributes.name}
                tagline={brand.attributes.field_card_description?.processed ?? brand.attributes.field_card_description?.value ?? ''}
                
                image={getImageBrandsUrl(brand)}
                linkTo={`/hearing-aid/${brand.attributes.drupal_internal__tid}`}
              />
            ))}
          </div>
        </div>

        <hr className="my-12 border-t border-[color:var(--border)]" />

        <div id="our-devices">
          <div className="mb-6 text-center">
            <h2 className="text-2xl font-bold text-[color:var(--secondary)]">Our Devices</h2>
          </div>
          <p className="mx-auto mb-6 max-w-3xl text-center text-[color:var(--muted-foreground)]">
            State-of-the-art diagnostic equipment for comprehensive hearing assessments
            and precise audiological evaluations.
          </p>
          <div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
            {Devices.map((device) => (
              <BrandCard
                key={device.id}
                tagline={device.attributes.body.processed?.length > 100
  ? device.attributes.body.processed.slice(0, 100) + "..."
  : device.attributes.body.processed}
                title={device.attributes.title}
                image={getImageDevicesUrl(device)}
                linkTo={`/devices/${device.id}`}
              />
            ))}
          </div>
        </div>
      </section>
    
  );
}

export default BrandsSection;