import { notFound } from "next/navigation";
import { Calendar, ArrowLeft, Share2, Mail } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { formatTanggalIndonesia } from "@/types/news";
import { buildImageUrl } from "@/lib/utils/image";
import type { Metadata } from "next";
import { newsService } from "@/lib/api/public/news";

interface Props {
  params: Promise<{ slug: string }>;
}

export async function generateStaticParams() {
  try {
    const res = await newsService.getAll({ per_page: 100 });
    return res.data.data.map((item) => ({ slug: item.slug }));
  } catch {
    return [];
  }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  try {
    const { slug } = await params;
    const { data } = await newsService.getBySlug(slug);
    return {
      title: `${data.title} | PTBMMKI`,
      description: data.description ?? data.content?.slice(0, 160),
      openGraph: {
        title: data.title,
        description: data.description ?? undefined,
        images: data.thumbnail ? [buildImageUrl(data.thumbnail)] : undefined,
      },
    };
  } catch {
    return { title: "Berita | PTBMMKI" };
  }
}

export default async function DetailBerita({ params }: Props) {
  const { slug } = await params;

  const [articleResult, otherResult] = await Promise.allSettled([
    newsService.getBySlug(slug),
    newsService.getLatest(6),
  ]);

  if (articleResult.status === "rejected") return notFound();

  const data = articleResult.value.data;

  const otherNews = (
    otherResult.status === "fulfilled" ? otherResult.value.data : []
  )
    .filter((item) => item.slug !== slug)
    .slice(0, 5);

  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000";
  const shareUrl = `${siteUrl}/berita/${slug}`;
  const shareText = `Baca berita: ${data.title} - PTBMMKI`;
  const imageUrl = buildImageUrl(data.thumbnail ?? data.image);
  const tanggal = formatTanggalIndonesia(data.published_date);

  return (
    <section className="min-h-screen py-12 md:py-16 lg:py-20 px-6 md:px-20 lg:px-36 bg-gray-50 mt-20">
      <div className="w-full mx-auto">
        <div className="mb-8">
          <Link
            href="/berita"
            className="inline-flex items-center gap-2 text-brand hover:text-brand/80 font-medium transition-colors duration-200 group"
          >
            <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform duration-200" />
            Kembali ke Daftar Berita
          </Link>
        </div>

        <div className="flex flex-col lg:flex-row gap-8 lg:gap-12">
          <div className="lg:w-2/3">
            <div className="mb-8 md:mb-12">
              <div className="flex flex-wrap items-center gap-3 mb-6">
                {data.category && (
                  <span className="bg-brand text-white px-4 py-1.5 rounded-full text-sm font-semibold shadow-sm">
                    {data.category}
                  </span>
                )}
                <div className="flex items-center gap-2 text-sec text-sm md:text-base">
                  <Calendar className="w-4 h-4 flex-shrink-0" />
                  <span>{tanggal}</span>
                </div>
              </div>

              <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold text-main leading-tight mb-6">
                {data.title}
              </h1>
            </div>

            <div className="relative h-64 md:h-80 lg:h-96 rounded-2xl overflow-hidden shadow-xl mb-10 md:mb-12 bg-gradient-to-br from-gray-200 to-gray-300">
              <Image
                src={imageUrl}
                alt={data.title}
                fill
                priority
                className="object-cover"
                sizes="(max-width: 1024px) 100vw, 66vw"
                unoptimized
              />
              <div className="absolute inset-0 bg-gradient-to-br from-brand/20 to-brand/10" />
            </div>

            <article className="prose prose-lg md:prose-xl max-w-none mb-12 md:mb-16">
              {data.content.split(/\n\s*\n/).map((paragraph, index) => {
                const trimmed = paragraph.trim();
                if (!trimmed) return null;

                if (trimmed.startsWith("- ")) {
                  const items = trimmed.split("\n- ").filter(Boolean);
                  return (
                    <div key={index} className="my-8">
                      <ul className="space-y-3">
                        {items.map((item, idx) => (
                          <li key={idx} className="flex items-start">
                            <span className="w-2 h-2 bg-brand rounded-full mt-2 mr-3 flex-shrink-0" />
                            <span className="text-sec text-lg">
                              {item.replace(/^- /, "").trim()}
                            </span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  );
                }

                return (
                  <p key={index} className="text-sec leading-relaxed mb-6 text-lg">
                    {trimmed}
                  </p>
                );
              })}
            </article>

            <div className="my-10 p-6 md:p-8 border-l-4 border-brand bg-brand/5 rounded-r-lg">
              <blockquote className="text-lg md:text-xl italic text-main font-medium">
                &ldquo;Dengan Persaudaraan, Demi kemanusiaan. Jayalah PTBMMKI!&rdquo;
              </blockquote>
              <div className="mt-3 text-sec">— PTBMMKI</div>
            </div>

            <div className="border-t border-gray-200 pt-8 md:pt-10">
              <div className="flex items-center gap-2 mb-3">
                <Share2 className="w-5 h-5 text-sec" />
                <h3 className="text-lg font-semibold text-main">Bagikan Berita:</h3>
              </div>
              <div className="flex flex-wrap gap-3">
                <ShareButton href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`} label="Facebook" color="bg-[#1877F2] hover:bg-[#166FE5]">
                  <svg className="w-7 h-7 fill-current" viewBox="0 0 24 24"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" /></svg>
                </ShareButton>
                <ShareButton href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(shareText)}`} label="X (Twitter)" color="bg-black hover:bg-gray-800">
                  <svg className="w-6 h-6 fill-current" viewBox="0 0 24 24"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" /></svg>
                </ShareButton>
                <ShareButton href={`https://wa.me/?text=${encodeURIComponent(`${shareText} ${shareUrl}`)}`} label="WhatsApp" color="bg-[#25D366] hover:bg-[#1DA851]">
                  <svg className="w-7 h-7 fill-current" viewBox="0 0 24 24"><path d="M20.52 3.49C18.18 1.13 15.19 0 12 0 5.37 0 0 5.37 0 12c0 2.04.5 4.02 1.45 5.78L0 24l6.33-1.58c1.67.94 3.56 1.44 5.55 1.44 6.63 0 12-5.37 12-12 0-3.19-1.13-6.18-3.48-8.52zM12 21.8c-1.68 0-3.31-.44-4.75-1.27l-.34-.2-3.53.93.94-3.45-.22-.36C2.9 15.31 2.2 13.69 2.2 12c0-5.4 4.4-9.8 9.8-9.8 2.61 0 5.07 1.02 6.92 2.87 1.85 1.85 2.87 4.31 2.87 6.92 0 5.4-4.4 9.8-9.79 9.8z" /><path d="M17.05 14.41c-.3-.15-1.77-.87-2.04-.97-.27-.1-.47-.15-.67.15-.2.3-.77.97-.95 1.17-.17.2-.35.22-.64.07-.3-.15-1.25-.46-2.38-1.46-.88-.78-1.47-1.74-1.64-2.04-.17-.3-.02-.46.13-.61.13-.13.3-.34.45-.51.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52-.08-.15-.67-1.61-.92-2.2-.24-.58-.49-.5-.67-.5-.17 0-.37-.01-.57-.01-.2 0-.52.08-.79.38-.27.3-1.04 1.02-1.04 2.49s1.07 2.89 1.22 3.09c.15.2 2.11 3.22 5.12 4.52.71.3 1.27.48 1.71.62.71.22 1.36.19 1.87.12.57-.08 1.77-.72 2.02-1.42.25-.7.25-1.3.18-1.42-.08-.13-.3-.2-.6-.35z" /></svg>
                </ShareButton>
                <ShareButton href={`https://t.me/share/url?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(shareText)}`} label="Telegram" color="bg-[#0088CC] hover:bg-[#0077B5]">
                  <svg className="w-7 h-7 fill-current" viewBox="0 0 24 24"><path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" /></svg>
                </ShareButton>
                <ShareButton href={`mailto:?subject=${encodeURIComponent(shareText)}&body=${encodeURIComponent(`Baca berita lengkap di: ${shareUrl}`)}`} label="Email" color="bg-gray-600 hover:bg-gray-700">
                  <Mail className="w-6 h-6" />
                </ShareButton>
              </div>
            </div>
          </div>

          <div className="lg:w-1/3">
            <div className="sticky top-8">
              <div className="bg-white rounded-2xl shadow-lg p-6 md:p-8 border border-gray-200">
                <h3 className="text-xl md:text-2xl font-bold text-main mb-6 pb-4 border-b border-gray-200">
                  Berita Lainnya
                </h3>

                <div className="space-y-6">
                  {otherNews.length > 0 ? (
                    otherNews.map((item, index) => (
                      <Link
                        key={item.id}
                        href={`/berita/${item.slug}`}
                        className={`group block ${index > 0 ? "pt-6 border-t border-gray-100" : ""}`}
                      >
                        <div className="flex gap-4">
                          <div className="relative w-20 h-20 md:w-24 md:h-24 rounded-lg overflow-hidden shadow-sm bg-gradient-to-br from-gray-200 to-gray-300 flex-shrink-0">
                            <Image
                              src={buildImageUrl(item.thumbnail ?? item.image)}
                              alt={item.title}
                              fill
                              className="object-cover group-hover:scale-105 transition-transform duration-300"
                              sizes="96px"
                              unoptimized
                            />
                          </div>
                          <div className="flex-1 min-w-0">
                            <span className="text-xs text-sec flex items-center gap-1 mb-2">
                              <Calendar className="w-3 h-3" />
                              {formatTanggalIndonesia(item.published_date)}
                            </span>
                            <h4 className="font-semibold text-main group-hover:text-brand transition-colors duration-200 line-clamp-2 mb-2">
                              {item.title}
                            </h4>
                            <div className="flex items-center justify-between">
                              {item.category && (
                                <span className="text-xs font-medium px-2 py-1 bg-brand/10 text-brand rounded-full">
                                  {item.category}
                                </span>
                              )}
                              <ArrowLeft className="w-4 h-4 rotate-180 text-gray-400 group-hover:text-brand group-hover:translate-x-1 transition-all duration-200" />
                            </div>
                          </div>
                        </div>
                      </Link>
                    ))
                  ) : (
                    <p className="text-center py-8 text-gray-400">
                      Tidak ada berita lainnya
                    </p>
                  )}
                </div>

                {otherNews.length > 0 && (
                  <div className="mt-8 pt-6 border-t border-gray-200">
                    <Link
                      href="/berita"
                      className="w-full inline-flex items-center justify-center gap-2 bg-brand text-white px-4 py-3 rounded-lg hover:bg-brand/90 transition-colors duration-200 font-semibold group"
                    >
                      Lihat Semua Berita
                      <ArrowLeft className="w-4 h-4 rotate-180 group-hover:translate-x-1 transition-transform duration-200" />
                    </Link>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function ShareButton({
  href,
  label,
  color,
  children,
}: {
  href: string;
  label: string;
  color: string;
  children: React.ReactNode;
}) {
  return (
    <a
      href={href}
      target="_blank"
      rel="noopener noreferrer"
      className={`w-12 h-12 ${color} text-white rounded-full flex items-center justify-center transition-colors duration-200 shadow-sm`}
      aria-label={`Bagikan di ${label}`}
    >
      {children}
    </a>
  );
}