import { useState, useEffect , useRef } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { ArrowLeft, ExternalLink, FileText, ChevronDown } from "lucide-react";
import { getNodeFullByNid } from "../services/drupalAPI";
import { normalizeDrupalUrl } from "../services/drupalAPI";
import ImageSlider from "./ImageSlider";

function ProductDetail() {
  const { brandId, productId } = useParams();
  const navigate = useNavigate();
  const initedRef = useRef(false);
  // FIX 1: initialize as null, not [] — product is an object, not an array
  const [product, setProduct] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [expandedSpecs, setExpandedSpecs] = useState({});

  const toggleSpec = (label) => {
    setExpandedSpecs((prev) => ({
      ...prev,
      [label]: !prev[label],
    }));
  };

  useEffect(() => {
    
    getNodeFullByNid('hearing_aid', productId, {
      imageFields: [
        { fieldName: 'field_images', mode: 'media', mediaSourceField: 'field_media_image' },
      ],
      documentFields: [
        { fieldName: 'field_pdf', mediaSourceField: 'field_media_document' },
      ],
      taxonomyFields: [
        { fieldName: 'field_category' },
      ],
      paragraphField: 'field_specification',
    })
      .then((data) => {
        setLoading(false);
        setProduct(data);
        console.log('Fetched product data:', data);
      })
      .catch((err) => {
        console.error('Error fetching product data:', err); 
        setError(err);
      })
      
      .finally(() => setLoading(false));
      
  }, [productId]);

  useEffect(() => {
    if (!initedRef.current && product && product.field_specification_resolved && Object.keys(product.field_specification_resolved).length > 0) {
      initedRef.current = true;
      const firstSpec = Object.keys(product.field_specification_resolved)[0];
      // Use microtask to defer state update
      Promise.resolve().then(() => {
        setExpandedSpecs({ [firstSpec]: true });
      });
    }
  }, [product]);

  // FIX 2: loading / error / null guards BEFORE accessing product.attributes
  if (loading) {
    return (
      <main className="mx-auto max-w-3xl px-4 py-16 text-center">
        <p className="text-muted-foreground">Loading product…</p>
      </main>
    );
  }

  if (error) {
    return (
      <main className="mx-auto max-w-3xl px-4 py-16 text-center">
        <h1 className="text-3xl font-bold text-secondary">Error</h1>
        <p className="mt-3 text-muted-foreground">{error.message}</p>
        <Link
          to="/"
          className="mt-6 inline-flex rounded-xl bg-(--hearex-green) px-4 py-2 font-semibold text-primary-foreground hover:brightness-95"
        >
          Back to Home
        </Link>
      </main>
    );
  }

  if (!product || !brandId) {
    return (
      <main className="mx-auto max-w-3xl px-4 py-16 text-center">
        <h1 className="text-3xl font-bold text-secondary">Product Not Found</h1>
        <p className="mt-3 text-muted-foreground">
          The requested product detail is unavailable.
        </p>
        <Link
          to="/"
          className="mt-6 inline-flex rounded-xl bg-(--hearex-green) px-4 py-2 font-semibold text-primary-foreground hover:brightness-95"
        >
          Back to Home
        </Link>
      </main>
    );
  }

  // FIX 3: resolve images as an array — field_images_resolved is an array of media objects
  const getProductImages = (product) => {
    const resolved = product.field_images_resolved;
    if (!resolved) return [];
    return Array.isArray(resolved)
      ? resolved.map((img) => normalizeDrupalUrl(img?.file?.attributes?.uri?.url)).filter(Boolean)
      : [normalizeDrupalUrl(resolved?.file?.attributes?.uri?.url)].filter(Boolean);
  };

  const images = getProductImages(product);

  // Resolve PDF URL if available
  const pdfResolved = product.field_pdf_resolved;
  const pdfUrl = pdfResolved
    ? normalizeDrupalUrl(
        Array.isArray(pdfResolved)
          ? pdfResolved[0]?.file?.attributes?.uri?.url
          : pdfResolved?.file?.attributes?.uri?.url
      )
    : null;

  // Resolved paragraphs (specifications)
  const specifications = product.field_specification_resolved ?? [];


  return (
    <main className="min-h-screen bg-(--hearex-light-bg)">
      {/* Top bar */}
      <div className="w-full border-b border-border bg-(--muted)/40 py-4">
        <h1 className="text-center text-xl font-bold text-secondary sm:text-2xl">
          {product.attributes.title}
        </h1>
      </div>

      <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
        <button
          type="button"
          onClick={() => navigate(-1)}
          className="mb-6 inline-flex items-center gap-2 rounded-xl border border-border bg-card px-4 py-2 text-sm font-medium text-secondary hover:bg-(--hearex-light-bg)"
        >
          <ArrowLeft size={16} />
          Back
        </button>

        {/* 50% slider | 50% product info */}
        <div className="grid gap-10 lg:grid-cols-2 lg:items-start lg:gap-12">
          <div className="w-full min-w-0">
            {/* FIX 3: pass images array, not a single normalized string */}
            <ImageSlider images={images} altPrefix={product.attributes.title} />
          </div>

          <div className="flex min-w-0 flex-col">
            {product.field_category_resolved?.attributes?.name && (
              <Link
                to={`/hearing-aid/${brandId}`}
                className="text-sm font-semibold text-(--hearex-green) hover:brightness-95"
              >
                {product.field_category_resolved.attributes.name}
              </Link>
            )}

            <h2 className="mt-2 text-3xl font-bold tracking-tight text-secondary sm:text-4xl">
              {product.attributes.title}
            </h2>

            {product.attributes.body?.processed && (
              <div
                className="mt-4 text-muted-foreground prose max-w-none"
                dangerouslySetInnerHTML={{ __html: product.attributes.body.processed }}
                
              />
            )}
            <h3 className="mt-8 text-lg font-bold text-(--hearex-green)">Key Features</h3>
            {product.attributes.field_key_features?.processed && (
              <div
                className="mt-6 space-y-4 text-muted-foreground"
                dangerouslySetInnerHTML={{ __html: product.attributes.field_key_features.processed }}
                
              />
            )}
            <div className="mt-10 flex flex-col gap-3 sm:flex-row sm:flex-wrap">
                {product.attributes.field_link_to_website?.uri && (
                
                
                <a
                  href={product.attributes.field_link_to_website.uri}
                  target="_blank"
                  rel="noreferrer"
                  className="inline-flex flex-1 items-center justify-center gap-2 rounded-lg bg-(--hearex-green) px-6 py-3 text-sm font-bold uppercase tracking-wide text-primary-foreground hover:brightness-95 sm:min-w-50"
                  >
                  <ExternalLink size={18} />
                  View Website
                </a>)}
                {pdfUrl && (
              
                <a
                  href={pdfUrl}
                  target="_blank"
                  rel="noreferrer"
                  className="inline-flex flex-1 items-center justify-center gap-2 rounded-lg border-2 border-(--hearex-green) bg-card px-6 py-3 text-sm font-bold uppercase tracking-wide text-(--hearex-green) hover:bg-(--hearex-green-light) sm:min-w-50"
                >
                  <FileText size={18} />
                  View Catalog
                </a>
              
            )}
                </div>
            {/* PDF / Catalog button */}
            
          </div>
        </div>
      </div>

      {/* Specifications — full width */}
      {specifications.length > 0 && (
        <section className="w-full border-t border-border bg-card py-12">
          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
            <h2 className="text-center text-2xl font-bold text-(--hearex-green) sm:text-3xl">
              Specifications
            </h2>

            <div className="mt-10 grid w-full gap-4">
              {specifications.map((spec) => {
                const label = spec.attributes?.field_label ?? spec.attributes?.title ?? spec.id;
                const value = spec.attributes?.field_info?.processed
                  ?? '';

                return (
                  <div
                    key={spec.id}
                    className="flex w-full flex-col rounded-xl border border-border bg-(--hearex-light-bg)"
                  >
                    <button
                      onClick={() => toggleSpec(label)}
                      className="flex w-full items-center justify-between px-5 py-4 hover:bg-(--border)/50 transition-colors"
                    >
                      <span className="text-xs font-bold uppercase tracking-wide text-(--hearex-green)">
                        {label}
                      </span>
                      <ChevronDown
                        size={16}
                        className={`shrink-0 text-(--hearex-green) transition-transform ${
                          expandedSpecs[label] ? "rotate-180" : ""
                        }`}
                      />
                    </button>
                    {expandedSpecs[label] && (
                      <div className="border-t border-border px-5 py-4">
                        {value ? (
                          <div
                            className="text-sm font-medium text-secondary prose max-w-none"
                            dangerouslySetInnerHTML={{ __html: value }}
                          />
                        ) : (
                          <span className="text-sm text-muted-foreground">No details available.</span>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </section>
      )}
    </main>
  );
}

export default ProductDetail;