"use client";

import Image from "next/image";
import Link from "next/link";
import useSWR from "swr";
import { Skeleton } from "@/components/ui/skeleton";
import NewsService from "@/services/news.service";
import type { News, NewsFeaturedResponse } from "@/types/news.type";
import { format } from "date-fns";
import { id } from "date-fns/locale";

import MaterialSymbolsArrowRightAltIcon from "@/components/icons/material-symbols/arrow-right-alt";

// Fallback data
const FALLBACK_FEATURED: News = {
  id: "1",
  title: "Penyuluhan MCU di Masyarakat Tingkatkan Kesadaran Deteksi Dini dan Pencegahan Penyakit",
  slug: "penyuluhan-mcu",
  excerpt: "Penyuluhan MCU di Desa Nologaten, Jogja, bertujuan meningkatkan kesadaran masyarakat terhadap pentingnya pemeriksaan kesehatan rutin sebagai langkah deteksi dini penyakit dan menjaga kualitas hidup.",
  content: "",
  imageUrl: "/assets/home/news.jpg",
  status: "PUBLISHED",
  isFeatured: true,
  isRecommended: false,
  viewCount: 0,
  publishedAt: new Date().toISOString(),
  category: { id: "1", name: "MCU", slug: "mcu" },
  tags: [],
};

const FALLBACK_SIDEBAR: News[] = [
  {
    id: "2",
    title: "Sunat Adera cepat, aman, dan moderen sekarang ada di sleman. Cek yuk!",
    slug: "sunat-adera",
    excerpt: "",
    content: "",
    imageUrl: "/assets/home/news.jpg",
    status: "PUBLISHED",
    isFeatured: false,
    isRecommended: true,
    viewCount: 0,
    publishedAt: new Date().toISOString(),
    category: { id: "1", name: "Sunat", slug: "sunat" },
    tags: [],
  },
  {
    id: "3",
    title: "Pentingnya USG Kehamilan untuk Ibu Hamil Deteksi Dini Kesehatan Janin dan Optimal",
    slug: "usg-kehamilan",
    excerpt: "",
    content: "",
    imageUrl: "/assets/home/news.jpg",
    status: "PUBLISHED",
    isFeatured: false,
    isRecommended: true,
    viewCount: 0,
    publishedAt: new Date().toISOString(),
    category: { id: "1", name: "KIA", slug: "kia" },
    tags: [],
  },
  {
    id: "4",
    title: "Kenali jenis vaksin virus global dan manfaat untuk kesehatannya",
    slug: "vaksin-virus",
    excerpt: "",
    content: "",
    imageUrl: "/assets/home/news.jpg",
    status: "PUBLISHED",
    isFeatured: false,
    isRecommended: true,
    viewCount: 0,
    publishedAt: new Date().toISOString(),
    category: { id: "1", name: "Vaksinasi", slug: "vaksinasi" },
    tags: [],
  },
];

const formatDate = (dateString?: string) => {
  if (!dateString) return "";
  try {
    return format(new Date(dateString), "d MMMM yyyy", { locale: id });
  } catch {
    return "";
  }
};

const BeritaHeroSection = () => {
  const { data: featuredData, isLoading } = useSWR<NewsFeaturedResponse>(
    "/news/featured",
    () => NewsService.getFeatured(),
    {
      revalidateOnFocus: false,
    }
  );

  const featured = featuredData?.featured || FALLBACK_FEATURED;
  const sidebar = featuredData?.sidebar?.slice(0, 3) || FALLBACK_SIDEBAR;

  return (
    <section className="relative bg-background-custom py-6 overflow-hidden">
      {/* Decorative ellipses */}
      <div className="absolute -left-10 top-37.5 size-57.75 opacity-30">
        <div className="absolute inset-0 rounded-full bg-[#B8D4FF] blur-3xl" />
      </div>
      <div className="absolute left-9.5 top-100.5 size-66.75 opacity-30">
        <div className="absolute inset-0 rounded-full bg-[#B8D4FF] blur-3xl" />
      </div>
      <div className="absolute right-25 top-42.5 size-92.75 opacity-30">
        <div className="absolute inset-0 rounded-full bg-[#B8D4FF] blur-3xl" />
      </div>

      <div className="max-w-7xl mx-auto px-6 relative z-10">
        <div className="flex flex-col lg:flex-row gap-6">
          {/* Featured News Card - Left */}
          <div className="lg:w-[60%] relative">
            {isLoading ? (
              <Skeleton className="h-149.5 rounded-[23px]" />
            ) : (
              <div className="relative h-149.5 rounded-[23px] overflow-hidden shadow-lg">
                <Image
                  src={featured.imageUrl || "/assets/home/news.jpg"}
                  alt={featured.title}
                  fill
                  className="object-cover"
                />
                {/* Gradient overlay */}
                <div className="absolute inset-0 bg-linear-to-t from-black via-black/40 to-transparent" />

                {/* Content */}
                <div className="absolute bottom-0 left-0 right-0 p-8 flex flex-col gap-4">
                  <h2 className="text-white font-semibold text-[36px] leading-tight tracking-[-1.44px] max-w-xl">
                    {featured.title}
                  </h2>
                  <p className="text-white/60 text-[20px] leading-tight tracking-[-0.8px] line-clamp-3">
                    {featured.excerpt}
                  </p>
                  <Link
                    href={`/berita/${featured.slug}`}
                    className="inline-flex items-center gap-3 bg-white font-semibold text-[#003dd8] text-[22px] tracking-[-0.88px] px-6 py-1 rounded-[29px] w-fit hover:bg-white/90 transition-colors"
                  >
                    Baca sekarang
                    <MaterialSymbolsArrowRightAltIcon className="size-6 text-primary" />
                  </Link>
                </div>
              </div>
            )}
          </div>

          {/* Sidebar News Cards - Right */}
          <div className="lg:w-[50%] flex flex-col gap-2.5">
            {isLoading
              ? Array.from({ length: 3 }).map((_, idx) => (
                  <Skeleton key={`sidebar-skeleton-${idx}`} className="h-48.5 rounded-4xl" />
                ))
              : sidebar.map((news) => (
                  <Link
                    key={news.id}
                    href={`/berita/${news.slug}`}
                    className="flex items-center rounded-4xl overflow-hidden h-48.5 hover:bg-white/50 transition-colors"
                  >
                    {/* Thumbnail */}
                    <div className="w-65.5 h-full p-2.5 shrink-0">
                      <div className="relative h-full rounded-[14px] overflow-hidden shadow-md">
                        <Image
                          src={news.imageUrl || "/assets/home/news.jpg"}
                          alt={news.title}
                          fill
                          className="object-cover"
                        />
                      </div>
                    </div>

                    {/* Content */}
                    <div className="flex flex-col justify-between h-full p-4 w-full">
                      <div className="flex justify-between text-[12px] text-black/60 tracking-[-0.48px] mb-2">
                        <span>{formatDate(news.publishedAt)}</span>
                        <span>by Adera clinic</span>
                      </div>
                      <h3 className="font-semibold text-[25px] text-[#3a3a3a] leading-tight tracking-[-1px] line-clamp-4">
                        {news.title}
                      </h3>
                    </div>
                  </Link>
                ))}
          </div>
        </div>
      </div>
    </section>
  );
};

export default BeritaHeroSection;
