"use client";

import Image from "next/image";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { loading, close } from "@/config/swal";
import { getMediaBlastBroadCast } from "@/service/service/broadcast/broadcast";

interface BroadcastDetail {
  id: number;
  body: string;
  subject: string;
  sendTime: string;
  thumbnail: string;
  contentUrl: string;
}

export default function DetailContentBlast() {
  const params = useParams();
  const { id } = params as { id: string };

  const [detail, setDetail] = useState<BroadcastDetail | null>(null);
  const [notFound, setNotFound] = useState(false);

  useEffect(() => {
    fetchDetailData();
  }, [id]);

  async function fetchDetailData() {
    loading();
    try {
      const res = await getMediaBlastBroadCast(id);
      close();

      const detailData = res?.data?.data;
      let updatedUrl = detailData.contentUrl;

      const domainsToUpdate = ["mediahub.polri.go.id", "netidhub.com"];

      domainsToUpdate.forEach((domain) => {
        if (
          updatedUrl.includes(domain) &&
          !updatedUrl.includes(`${domain}/in`)
        ) {
          updatedUrl = updatedUrl.replace(domain, `${domain}/in`);
        }
      });
      if (detailData && detailData.id === Number(id)) {
        setDetail({
          id: detailData.id,
          body: detailData.body,
          subject: detailData.subject,
          sendTime: detailData.sendTime,
          thumbnail: detailData.thumbnail,
          contentUrl: updatedUrl,
        });
      } else {
        setNotFound(true);
      }
    } catch (error) {
      close();
      console.error("Failed to fetch broadcast detail:", error);
      setNotFound(true);
    }
  }

  if (notFound) {
    return <div className="text-red-500 p-4">Data tidak ditemukan.</div>;
  }

  if (!detail) {
    return <div className="text-gray-500 p-4">Loading preview...</div>;
  }

  return (
    <div className="bg-white rounded-md w-full p-4">
      <p className="text-xl font-semibold py-1">Preview</p>
      <div className="bg-[#ddf7c8] p-4 rounded-xl mx-auto space-y-4">
        <div className="flex gap-4">
          <Image
            src={detail.thumbnail}
            alt="Media Thumbnail"
            width={250}
            height={200}
            className="rounded-md object-cover"
          />
        </div>

        <div className="text-sm text-black font-bold">{detail.subject}</div>
        <p>
          Selengkapnya silakan cek di sini:{" "}
          <a
            href={detail.contentUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="text-blue-600 underline"
          >
            {detail.contentUrl}
          </a>
        </p>
        <div className="text-right text-xs text-gray-500">
          {detail.sendTime}
        </div>
      </div>
    </div>
  );
}
