import { Link, useNavigate, useParams } from "react-router-dom";
import { useEffect , useState } from "react";
import { ArrowLeft, Globe } from "lucide-react";

import { getNode } from "../services/drupalAPI";
import { normalizeDrupalUrl } from "../services/drupalAPI";
import ImageSlider from "./ImageSlider";

function DeviceDetail() {
  const { deviceId } = useParams();
  const navigate = useNavigate();
  const [deviceItem, setDevice] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    getNode('devices', deviceId, [{ fieldName: 'field_images', mode: 'media', mediaSourceField: 'field_media_image' }])
      .then(setDevice)
      .catch(setError)
      .finally(() => setLoading(false));
  }, [deviceId]);

  console.log('Device Item:', deviceItem);
    const getDeviceImages = (device) => {
            const resolved = device.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)];
          };
  
  if (loading) {    
    return (
      <main className="mx-auto max-w-3xl px-4 py-16 text-center">
        <h1 className="text-3xl font-bold text-[color:var(--secondary)]">Loading...</h1>
        <p className="mt-3 text-[color:var(--muted-foreground)]">
          Fetching device details, please wait.
        </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-[color:var(--secondary)]">Error</h1>
        <p className="mt-3 text-[color:var(--muted-foreground)]">
          An error occurred while fetching device details: {error.message}
        </p>
        <Link
          to="/"
          className="mt-6 inline-flex rounded-xl bg-[color:var(--hearex-green)] px-4 py-2 font-semibold text-[color:var(--primary-foreground)] hover:brightness-95"
        >
          Back to Home
        </Link>
      </main>
    );
  }

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

  return (
    <main className="min-h-screen bg-[color:var(--hearex-light-bg)]">
      {/* Top bar — device name centered */}
      <div className="w-full border-b border-[color:var(--border)] bg-[color:var(--muted)]/40 py-4">
        <h1 className="text-center text-xl font-bold text-[color:var(--secondary)] sm:text-2xl">
          {deviceItem.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-[color:var(--border)] bg-[color:var(--card)] px-4 py-2 text-sm font-medium text-[color:var(--secondary)] hover:bg-[color:var(--hearex-light-bg)]"
        >
          <ArrowLeft size={16} />
          Back
        </button>

        {/* 50% slider | 50% device info */}
        <div className="grid gap-10 lg:grid-cols-2 lg:items-start lg:gap-12">
          <div className="w-full min-w-0">
            <ImageSlider images={getDeviceImages(deviceItem)} altPrefix={deviceItem.attributes.title} />
          </div>

          <div className="flex min-w-0 flex-col">
            {/* <h2 className="text-3xl font-bold tracking-tight text-[color:var(--secondary)] sm:text-4xl">
              {device.tagline}
            </h2> */}

            <div className="device-body mt-5 space-y-4 text-[color:var(--muted-foreground)]">
              
               
                {deviceItem?.attributes?.body?.processed 
                  ? <span dangerouslySetInnerHTML={{ __html: deviceItem.attributes.body.processed }} />
                  : 'Your trusted partner in hearing healthcare.'}
              
            </div>

            <a
              href={deviceItem.attributes.field_link_to_website}
              target="_blank"
              rel="noreferrer"
              className="mt-8 inline-flex items-center justify-center gap-2 rounded-xl border border-[color:var(--border)] bg-[color:var(--hearex-green-light)] px-6 py-3 font-semibold text-[color:var(--secondary)] hover:brightness-95"
            >
              <Globe size={18} />
              Website Link
            </a>
          </div>
        </div>
      </div>
    </main>
  );
}

export default DeviceDetail;
