import {
  Button,
  Card,
  CardBody,
  CardFooter,
  Image,
  Spinner,
  Tab,
  Tabs,
} from "@heroui/react";
import React, { useEffect, useState } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import { Navigation, Pagination } from "swiper/modules";
import { topNewsMediahub } from "@/services/medol-news-update";
import Link from "next/link";
import {
  getImageInp,
  inpLogin,
  topNewsInp,
  topNewsTbn,
} from "@/services/third-party-service";
import { convertDateFormatNoTime, textEllipsis } from "@/utils/global";
import PolriTvWidget from "../ui/social-media/polri-tv";
import { useTranslations } from "next-intl";

export default function MedolUpdate() {
  const [selectedTab, setSelectedTab] = useState<any>("mediahub");
  const [mediahubUpdate, setMediahubUpdate] = useState<any>([]);
  const [tbnUpdate, setTbnUpdate] = useState([]);
  const [inpUpdate, setInpUpdate] = useState([]);

  // const t = useTranslations("Landing");

  useEffect(() => {
    if (selectedTab === "mediahub" && mediahubUpdate?.length < 1) {
      getMedihubUpdate();
    }
    if (selectedTab === "tbnews" && tbnUpdate?.length < 1) {
      getTbnUpdate();
    }
    if (selectedTab === "inp" && inpUpdate?.length < 1) {
      getInpUpdate();
    }
  }, [selectedTab]);

  async function getMedihubUpdate() {
    const res = await topNewsMediahub();
    setMediahubUpdate(res?.data?.data?.content);
  }

  async function getTbnUpdate() {
    const res = await topNewsTbn();
    setTbnUpdate(res?.data?.data);
  }
  async function getInpUpdate() {
    const headers = {
      "content-type": "application/json",
    };
    const resLog = await inpLogin(headers);
    const res = await topNewsInp(resLog?.data?.access_token);
    // setInpUpdate(res?.data);
    setInpUpdate(res?.data?.data);

    // getDataImage(res?.data);
  }

  async function getDataImage(data: any) {
    let temp = data;
    for (let i = 0; i < data?.length; i++) {
      const res = await getImageInp(temp[i].id);
      const data = res?.data[0]?.guid?.rendered;
      temp[i].image = data;
    }
    setInpUpdate(temp);
  }

  const formatDate = (dateString: string): string => {
    const date = new Date(dateString);

    let timeZone = "Asia/Jakarta";
    let timeZoneAbbr = "WIB";

    if (dateString.includes("+09:00")) {
      timeZone = "Asia/Jayapura";
      timeZoneAbbr = "WIT";
    } else if (dateString.includes("+08:00")) {
      timeZone = "Asia/Makassar";
      timeZoneAbbr = "WITA";
    }

    const options: Intl.DateTimeFormatOptions = {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
      hour12: false,
      timeZone,
    };

    // Format tanggal
    const formattedDate = new Intl.DateTimeFormat("id-ID", options)
      .format(date)
      .replace(/\//g, "-"); // Ubah '/' menjadi '-'

    return `${formattedDate} ${timeZoneAbbr}`;
  };

  return (
    <div className="border-1 rounded-xl py-2 w-[90%] lg:w-[75%] mx-auto bg-white text-black">
      <div className="text-xl font-semibold w-full ">
        <p className="border-b-2 border-red-600 w-fit mx-auto">Media Update</p>
      </div>
      <div className=" p-1 md:py-5 md:px-5 space-y-5">
        <Tabs
          classNames={{
            tabList: "bg-white shadow-lg border p-2 rounded-lg",
            tab: "group-data-[selected=true]:bg-[#bb3523] bg-white p-0 mx-2",
            tabContent: [
              "group-data-[selected=true]:text-[white] text-[#bb3523]",
              "group-data-[selected=true]:bg-[#bb3523] bg-white rounded-md p-2",
            ],
          }}
          aria-label="Options"
          // color="[#bb3523]"
          className="flex justify-center"
          selectedKey={selectedTab}
          onSelectionChange={setSelectedTab}
        >
          <Tab key="mediahub" title="MediaHUB Update">
            {mediahubUpdate?.length > 1 ? (
              <>
                <Swiper
                  navigation={true}
                  modules={[Navigation]}
                  spaceBetween={10}
                  slidesPerView={1}
                  breakpoints={{
                    // When the window width is less than 640px
                    720: {
                      slidesPerView: 3, // Set slidesPerView to 1 on mobile
                    },
                    1080: {
                      slidesPerView: 4,
                    },
                  }}
                  pagination={true}
                  className="mySwiper custom-button-slider !px-[8px]"
                  onSwiper={(swiper) => {
                    swiper.navigation.nextEl?.classList.add(
                      "bg-white",
                      "!text-black",
                      "rounded-full",
                      "!w-[40px]",
                      "!h-[40px]",
                      "!border-2"
                    );
                    swiper.navigation.prevEl?.classList.add(
                      "bg-white",
                      "!text-black",
                      "rounded-full",
                      "!w-[40px]",
                      "!h-[40px]",
                      "!border-2"
                    );
                  }}
                >
                  {mediahubUpdate?.map((newsItem: any) => (
                    <SwiperSlide
                      key={newsItem?.title}
                      className="hover:shadow-xl hover:opacity-90"
                    >
                      <Link href={newsItem?.pageUrl} target="_blank">
                        <Card
                          isPressable
                          shadow="sm"
                          className=" bg-white text-black border-2 w-full"
                        >
                          <CardBody className="overflow-visible p-0">
                            <Image
                              alt="thumbnail"
                              className="object-cover !h-[20vh]"
                              // src={newsItem.thumbnailLink}
                              src={`https://mediahub.polri.go.id/api/media/view?id=${newsItem?.id}&operation=thumbnail&isSmall=true`}
                            />
                          </CardBody>
                          <CardFooter className="flex flex-col items-start text-left">
                            <p className="text-xs">
                              {formatDate(newsItem?.createdAt)}
                            </p>
                            <b className="text-sm">
                              {textEllipsis(newsItem?.title, 50)}
                            </b>
                          </CardFooter>
                        </Card>
                      </Link>
                    </SwiperSlide>
                  ))}
                </Swiper>
                <div className="text-center pt-6">
                  <Link href="https://mediahub.polri.go.id" target="_blank">
                    <Button
                      className="bg-white text-[#bb3523] font-bold w-56"
                      size="sm"
                      color="danger"
                      variant="bordered"
                    >
                      {/* {t("lebihBanyak")} */}
                      Lihat Lebih Banyak
                    </Button>
                  </Link>
                </div>
              </>
            ) : (
              <div className="w-full flex justify-center items-center">
                <Spinner size="lg" className="mx-auto" color="default" />
              </div>
            )}
          </Tab>
          <Tab key="tbnews" title="Tribrata News Update">
            {tbnUpdate?.length > 1 ? (
              <>
                {" "}
                <Swiper
                  navigation={true}
                  modules={[Navigation]}
                  spaceBetween={10}
                  slidesPerView={1}
                  breakpoints={{
                    // When the window width is less than 640px
                    720: {
                      slidesPerView: 3, // Set slidesPerView to 1 on mobile
                    },
                    1080: {
                      slidesPerView: 4,
                    },
                  }}
                  pagination={true}
                  className="mySwiper custom-button-slider !px-[8px]"
                  onSwiper={(swiper) => {
                    swiper.navigation.nextEl?.classList.add(
                      "bg-white/70",
                      "!text-black",
                      "rounded-full",
                      "!w-[40px]",
                      "!h-[40px]"
                    );
                    swiper.navigation.prevEl?.classList.add(
                      "bg-white/70",
                      "!text-black",
                      "rounded-full",
                      "!w-[40px]",
                      "!h-[40px]"
                    );
                  }}
                >
                  {tbnUpdate?.map((newsItem: any) => (
                    <SwiperSlide
                      key={newsItem.title}
                      className="hover:shadow-xl hover:opacity-90"
                    >
                      <Link href={newsItem?.source_url} target="_blank">
                        <Card
                          isPressable
                          shadow="sm"
                          className=" bg-white text-black border-2 w-full"
                        >
                          <CardBody className="overflow-visible p-0">
                            <Image
                              alt="thumbnail"
                              className="object-cover !h-[20vh]"
                              src={newsItem?.image}
                            />
                          </CardBody>
                          <CardFooter className="flex flex-col items-start text-left">
                            {/* {convertDateFormatNoTime(newsItem?.date)} */}
                            <p className="text-xs">
                              {formatDate(newsItem?.date)}
                            </p>
                            <b className="text-sm">
                              {textEllipsis(newsItem?.title, 50)}
                            </b>
                          </CardFooter>
                        </Card>
                      </Link>
                    </SwiperSlide>
                  ))}
                </Swiper>
                <div className="text-center pt-6">
                  <Link href="https://tribratanews.polri.go.id" target="_blank">
                    <Button
                      className="bg-white text-[#bb3523] font-bold w-56"
                      size="sm"
                      color="danger"
                      variant="bordered"
                    >
                      {/* {t("lebihBanyak")} */}
                      Lihat Lebih Banyak
                    </Button>
                  </Link>
                </div>
              </>
            ) : (
              <div className="w-full flex justify-center items-center">
                <Spinner size="lg" className="mx-auto" color="default" />
              </div>
            )}
          </Tab>
          <Tab key="inp" title="Indonesia Nasional Police Update">
            {inpUpdate?.length > 1 ? (
              <>
                <Swiper
                  navigation={true}
                  modules={[Navigation]}
                  spaceBetween={10}
                  slidesPerView={1}
                  breakpoints={{
                    // When the window width is less than 640px
                    720: {
                      slidesPerView: 3, // Set slidesPerView to 1 on mobile
                    },
                    1080: {
                      slidesPerView: 4,
                    },
                  }}
                  pagination={true}
                  className="mySwiper custom-button-slider !px-[8px]"
                  onSwiper={(swiper) => {
                    swiper.navigation.nextEl?.classList.add(
                      "bg-white/70",
                      "!text-black",
                      "rounded-full",
                      "!w-[40px]",
                      "!h-[40px]"
                    );
                    swiper.navigation.prevEl?.classList.add(
                      "bg-white/70",
                      "!text-black",
                      "rounded-full",
                      "!w-[40px]",
                      "!h-[40px]"
                    );
                  }}
                >
                  {inpUpdate?.map((newsItem: any) => (
                    <SwiperSlide
                      key={newsItem?.slug}
                      className="hover:shadow-xl hover:opacity-90"
                    >
                      <Link
                        href={`https://inp.polri.go.id/artikel/${newsItem?.slug}`}
                        target="_blank"
                      >
                        <Card
                          isPressable
                          shadow="sm"
                          className=" bg-white text-black border-2 w-full"
                        >
                          <CardBody className="overflow-visible p-0">
                            <Image
                              alt="thumnail"
                              className="object-cover !h-[20vh]"
                              src={newsItem?.thumbnail}
                            />
                          </CardBody>
                          <CardFooter className="flex flex-col items-start text-left">
                            {/* {newsItem?.created_at} */}
                            <p className="text-xs">{newsItem?.created_at}</p>
                            <b className="text-sm">
                              {textEllipsis(newsItem?.judul, 50)}
                            </b>
                          </CardFooter>
                        </Card>
                      </Link>
                    </SwiperSlide>
                  ))}
                </Swiper>
                <div className="text-center pt-6">
                  <a href="https://inp.polri.go.id/" target="_blank">
                    <Button
                      className="bg-white text-[#bb3523] font-bold w-56"
                      size="sm"
                      color="danger"
                      variant="bordered"
                    >
                      {/* {t("lebihBanyak")} */}
                      Lihat Lebih Banyak
                    </Button>
                  </a>
                </div>
              </>
            ) : (
              <div className="w-full flex justify-center items-center">
                <Spinner size="lg" className="mx-auto" color="default" />
              </div>
            )}
          </Tab>
          <Tab key="polritv" title="Polri TV Update">
            <PolriTvWidget />

            <div className="text-center pt-6">
              <Link
                href="https://www.youtube.com/@TvRadioPolri"
                target="_blank"
              >
                <Button
                  className="bg-white text-[#bb3523] font-bold w-56"
                  size="sm"
                  color="danger"
                  variant="bordered"
                >
                  {/* {t("lebihBanyak")} */}
                  Lihat Lebih Banyak
                </Button>
              </Link>
            </div>
          </Tab>
        </Tabs>
      </div>
    </div>
  );
}
