"use client";

import { Calendar, Tag, User, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { createPortal } from "react-dom";
import { useEffect, useState } from "react";

interface NewsPreviewProps {
  open: boolean;
  onClose: () => void;
  title: string;
  excerpt: string;
  content: string;
  image: string;
  category: string;
  author: string;
  published_at: string;
}

const categoryColors: Record<string, string> = {
  "Company News": "bg-blue-500/10 text-blue-600",
  Expansion: "bg-green-500/10 text-green-600",
  Training: "bg-orange-500/10 text-orange-600",
  Technology: "bg-purple-500/10 text-purple-600",
  Certification: "bg-cyan-500/10 text-cyan-600",
};

function formatDate(dateStr: string) {
  if (!dateStr) return "";
  return new Date(dateStr).toLocaleDateString("en-GB", {
    day: "numeric",
    month: "long",
    year: "numeric",
  });
}

export function NewsPreview({
  open, onClose,
  title, excerpt, content, image, category, author, published_at,
}: NewsPreviewProps) {
  const [mounted, setMounted] = useState(false);
  useEffect(() => { setMounted(true); }, []);

  // Close on Escape
  useEffect(() => {
    if (!open) return;
    const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  }, [open, onClose]);

  // Prevent body scroll while open
  useEffect(() => {
    if (open) { document.body.style.overflow = "hidden"; }
    else { document.body.style.overflow = ""; }
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  if (!mounted || !open) return null;

  const modal = (
    <div
      className="fixed inset-0 z-[100] bg-black/60 backdrop-blur-sm flex flex-col overflow-hidden"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      {/* Preview topbar */}
      <div className="shrink-0 bg-background/95 backdrop-blur-sm border-b border-border px-4 py-2 flex items-center gap-3">
        <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground bg-amber-500/10 text-amber-600 border border-amber-500/20 rounded px-2 py-0.5">
          Preview
        </span>
        <span className="text-sm text-muted-foreground flex-1 truncate">
          {title || "Untitled Article"}
        </span>
        <Button
          type="button"
          variant="ghost"
          size="icon"
          className="h-7 w-7 shrink-0"
          onClick={onClose}
        >
          <X size={15} />
        </Button>
      </div>

      {/* Scrollable preview area */}
      <div className="flex-1 overflow-y-auto bg-background">

        {/* Hero */}
        <section className="relative h-[50vh] min-h-[320px] flex items-end overflow-hidden bg-primary">
          {image ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={image}
              alt={title}
              className="absolute inset-0 w-full h-full object-cover"
            />
          ) : (
            <div className="absolute inset-0 bg-gradient-to-br from-primary to-primary/60" />
          )}
          <div className="absolute inset-0 bg-gradient-to-t from-primary via-primary/60 to-transparent" />
          <div className="relative px-6 lg:px-16 pb-10 z-10 max-w-5xl w-full mx-auto">
            {category && (
              <span
                className={`inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-1 rounded-full mb-4 ${categoryColors[category] ?? "bg-accent/10 text-accent"}`}
              >
                <Tag size={11} />
                {category}
              </span>
            )}
            <h1 className="text-2xl md:text-4xl font-bold text-primary-foreground max-w-3xl leading-tight">
              {title || <span className="opacity-40">Article title will appear here…</span>}
            </h1>
            <div className="flex items-center gap-6 mt-4 text-primary-foreground/60 text-sm">
              {author && <span className="flex items-center gap-2"><User size={13} />{author}</span>}
              {published_at && <span className="flex items-center gap-2"><Calendar size={13} />{formatDate(published_at)}</span>}
            </div>
          </div>
        </section>

        {/* Content */}
        <section className="py-12 px-6 lg:px-16">
          <div className="max-w-3xl mx-auto">
            {excerpt && (
              <p className="text-lg text-muted-foreground leading-relaxed mb-8 font-medium border-l-4 border-accent pl-6">
                {excerpt}
              </p>
            )}
            {content && content !== "<p></p>" ? (
              <div
                className="prose prose-lg max-w-none text-foreground leading-relaxed [&_p]:text-muted-foreground [&_p]:leading-relaxed [&_img]:rounded-lg [&_img[data-align='center']]:mx-auto [&_img[data-align='center']]:block [&_img[data-align='right']]:float-right [&_img[data-align='right']]:ml-6 [&_img[data-align='left']]:float-left [&_img[data-align='left']]:mr-6 [&_a]:text-accent [&_a]:underline-offset-2 [&_blockquote]:border-l-accent"
                dangerouslySetInnerHTML={{ __html: content }}
              />
            ) : (
              <p className="text-muted-foreground/40 italic text-sm">Article body will appear here once you start writing…</p>
            )}
          </div>
        </section>

      </div>
    </div>
  );

  return createPortal(modal, document.body);
}
