"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { ThumbsUp, ThumbsDown } from "lucide-react";
import { Card } from "../ui/card";
import Link from "next/link";
import { listData } from "@/service/landing/landing";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/navigation";
import { Navigation } from "swiper/modules";

// Format tanggal
function formatTanggal(dateString: string) {
  if (!dateString) return "";
  return (
    new Date(dateString)
      .toLocaleString("id-ID", {
        day: "2-digit",
        month: "short",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
        hour12: false,
        timeZone: "Asia/Jakarta",
      })
      .replace(/\./g, ":") + " WIB"
  );
}

export default function MediaUpdate() {
  const [tab, setTab] = useState<"latest" | "popular">("latest");
  const [dataToRender, setDataToRender] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchData(tab);
  }, [tab]);

  async function fetchData(section: "latest" | "popular") {
    try {
      setLoading(true);
      const res = await listData(
        "1",
        "",
        "",
        20,
        0,
        section === "latest" ? "createdAt" : "clickCount",
        "",
        "",
        ""
      );
      setDataToRender(res?.data?.data?.content || []);
    } catch (err) {
      console.error("Gagal memuat data:", err);
    } finally {
      setLoading(false);
    }
  }

  return (
    <section className="bg-white px-4 py-10 border max-w-[1350px] mx-auto rounded-md border-[#CDD5DF] my-10">
      <div className="max-w-screen-xl mx-auto">
        <h2 className="text-2xl font-semibold text-center mb-6">
          Media Update
        </h2>

        {/* Tab */}
        <div className="flex justify-center mb-8 bg-white">
          <Card className="bg-[#FFFFFF] rounded-xl flex flex-row p-3 gap-2">
            <button
              onClick={() => setTab("latest")}
              className={`px-5 py-2 rounded-lg text-sm font-medium ${
                tab === "latest" ? "bg-[#C6A455] text-white" : "text-[#C6A455]"
              }`}
            >
              Konten Terbaru
            </button>
            <button
              onClick={() => setTab("popular")}
              className={`px-5 py-2 rounded-lg text-sm font-medium ${
                tab === "popular" ? "bg-[#C6A455] text-white" : "text-[#C6A455]"
              }`}
            >
              Konten Terpopuler
            </button>
          </Card>
        </div>

        {/* Slider */}
        {loading ? (
          <p className="text-center">Loading...</p>
        ) : (
          <Swiper
            modules={[Navigation]}
            navigation
            spaceBetween={20}
            slidesPerView={1}
            breakpoints={{
              640: { slidesPerView: 2 },
              1024: { slidesPerView: 4 },
            }}
          >
            {dataToRender.map((item) => (
              <SwiperSlide key={item.id}>
                <div className="rounded-xl shadow-md overflow-hidden bg-white">
                  <div className="w-full h-[204px] relative">
                    <Image
                      src={item.smallThumbnailLink || "/placeholder.png"}
                      alt={item.title || "No Title"}
                      fill
                      className="object-cover"
                    />
                  </div>
                  <div className="p-3">
                    <div className="flex gap-2 mb-1">
                      <span className="text-xs text-white px-2 py-0.5 rounded bg-blue-600">
                        {item.category || "Tanpa Kategori"}
                      </span>
                      <span className="text-xs font-medium text-[#b3882e]">
                        {item.label || ""}
                      </span>
                    </div>
                    <p className="text-xs text-gray-500 mb-1">
                      {formatTanggal(item.createdAt)}
                    </p>
                    <p className="text-sm font-semibold mb-3 line-clamp-2">
                      {item.title}
                    </p>

                    <div className="flex items-center justify-between">
                      <div className="flex gap-2 text-gray-600">
                        <ThumbsUp className="w-4 h-4 cursor-pointer" />
                        <ThumbsDown className="w-4 h-4 cursor-pointer" />
                      </div>
                      <Button
                        variant="default"
                        size="sm"
                        className="text-white bg-blue-600 rounded px-4"
                      >
                        Save
                      </Button>
                    </div>
                  </div>
                </div>
              </SwiperSlide>
            ))}
          </Swiper>
        )}

        {/* Lihat lebih banyak */}
        <div className="text-center mt-10">
          <Link
            href={
              tab === "latest"
                ? "https://mediahub.polri.go.id/"
                : "https://tribratanews.polri.go.id/"
            }
          >
            <Button
              size={"lg"}
              className="text-[#b3882e] bg-transparent border border-[#b3882e] px-6 py-2 rounded-s-sm text-sm font-medium hover:bg-[#b3882e]/10 transition"
            >
              Lihat Lebih Banyak
            </Button>
          </Link>
        </div>
      </div>
    </section>
  );
}
