import { useNavigate, useParams, Link } from "react-router-dom";
import { useEffect, useState } from "react";
import { ArrowLeft } from "lucide-react";
import { getNode, normalizeDrupalUrl } from '../services/drupalAPI';

export default function ArticleDetails() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [article, setArticle] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    getNode('news', id, [{ fieldName: 'field_images', mode: 'media', mediaSourceField: 'field_media_image' }])
      .then(setArticle)
      .catch(setError);
  }, [id]);

  // if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

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

  // Resolve image URL from media or file field
  const resolved = article.field_images_resolved;
  const rawUrl = Array.isArray(resolved)
    ? resolved[0]?.file?.attributes?.uri?.url
    : resolved?.file?.attributes?.uri?.url;
  const imageUrl = normalizeDrupalUrl(rawUrl);

  const { title, field_subtitle, field_date, body } = article.attributes;

  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">
          {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>

        <div className="mx-auto max-w-3xl">
          {/* Image */}
          {imageUrl && (
            <div className="mb-8 w-full overflow-hidden rounded-xl">
              <img
                src={imageUrl}
                alt={title}
                className="h-auto w-full object-cover"
              />
            </div>
          )}

          {/* Title & metadata */}
          <div className="mb-8">
            <h1 className="text-4xl font-bold tracking-tight text-secondary sm:text-5xl">
              {title}
            </h1>
            <div className="mt-6 flex flex-wrap items-center gap-4 text-muted-foreground sm:gap-6">
              {field_date && <span className="text-sm font-medium">{field_date}</span>}
              {field_subtitle && <span className="text-sm">{field_subtitle}</span>}
            </div>
          </div>

          {/* Body — Drupal body field is an object with value/processed */}
          <div className="prose prose-lg max-w-none text-secondary">
            {body?.processed ? (
              <div dangerouslySetInnerHTML={{ __html: body.processed }} />
            ) : (
              <p className="whitespace-pre-wrap text-lg leading-relaxed">
                {body?.value}
              </p>
            )}
          </div>
        </div>
      </div>
    </main>
  );
}