"use client";

import dynamic from "next/dynamic";
import Image from "next/image";
import Link from "next/link";
import { Fragment, useEffect, useState } from "react";
import DataLink from "@/components/common/DataLink";
import type { BlogListMetaLink } from "@/data/blog";
import { blogListPosts } from "@/data/blog";
import SearchWidget from "./common/SearchWidget";
import CategorieWidget from "./common/CategorieWidget";
import TagWidget from "./common/TagWidget";
import FormWidget from "./common/FormWidget";

const imgFluid = { width: "100%", height: "auto" } as const;
const ReactPlayer = dynamic(() => import("react-player"), { ssr: false });

function BlogMetaRow({ meta }: { meta: BlogListMetaLink[] }) {
  return (
    <ul className="blog-meta2">
      {meta.map((item, i) => (
        <Fragment key={`${item.label}-${i}`}>
          {i > 0 ? <li className="dot" /> : null}
          <li>
            <DataLink href={item.href ?? "#"} title="">
              {item.label}
            </DataLink>
          </li>
        </Fragment>
      ))}
    </ul>
  );
}

export default function BlogList() {
  const [activeVideoUrl, setActiveVideoUrl] = useState<string | null>(null);

  useEffect(() => {
    if (activeVideoUrl == null) return;

    const onEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") setActiveVideoUrl(null);
    };

    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onEscape);

    return () => {
      document.body.style.overflow = originalOverflow;
      window.removeEventListener("keydown", onEscape);
    };
  }, [activeVideoUrl]);

  return (
    <>
      <div className="col-lg-8">
        <div className="blog-info">
          {blogListPosts.map((post, index) => {
            const canOpenVideo = index === 0 && Boolean(post.videoUrl);
            return (
              <div
                key={post.id}
                className="blog-card2"
                data-aos="fade-up"
                data-aos-duration={900}
                data-aos-delay={post.aosDelay}
              >
                <div className="blog-img2">
                  <Link href={post.href}>
                    <Image
                      src={post.image}
                      alt={post.imageAlt}
                      width={800}
                      height={450}
                      style={imgFluid}
                    />
                  </Link>
                  {canOpenVideo ? (
                    <button
                      type="button"
                      className="video-trigger"
                      data-video={post.videoUrl}
                      onClick={() => setActiveVideoUrl(post.videoUrl ?? null)}
                      aria-label="Play post video"
                    >
                      ▶
                    </button>
                  ) : null}
                </div>
                <div className="blog-content2">
                  <BlogMetaRow meta={post.meta} />
                  <h2 className="title">
                    <Link href={post.href} title="">
                      {post.title}
                    </Link>
                  </h2>
                  <p>{post.excerpt}</p>
                  <Link href={post.href} className="btn-style1">
                    Read More
                    <span>
                      <Image
                        src="/assets/images/icon/arrow.svg"
                        alt="Arrow icon for Read More button"
                        width={14}
                        height={14}
                      />
                    </span>
                  </Link>
                </div>
              </div>
            );
          })}
        </div>
      </div>
      {/* End blog list */}

      <div className="col-lg-4">
        <div className="side-bar">
          <SearchWidget />
          <CategorieWidget />
          <TagWidget />
          <FormWidget />
        </div>
      </div>

      {activeVideoUrl ? (
        <div
          className="video-modal"
          onClick={() => setActiveVideoUrl(null)}
          role="button"
          tabIndex={0}
          aria-label="Close video modal"
          style={{
            position: "fixed",
            inset: 0,
            backgroundColor: "rgba(0, 0, 0, 0.8)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            zIndex: 10000,
            padding: "1rem",
          }}
        >
          <div
            onClick={(event) => event.stopPropagation()}
            style={{
              position: "relative",
              width: "min(100%, 900px)",
              aspectRatio: "16 / 9",
              backgroundColor: "#000",
            }}
          >
            <button
              type="button"
              onClick={() => setActiveVideoUrl(null)}
              aria-label="Close video"
              style={{
                position: "absolute",
                right: "0.5rem",
                top: "-2.2rem",
                border: 0,
                background: "transparent",
                color: "#fff",
                fontSize: "2rem",
                lineHeight: 1,
              }}
            >
              ×
            </button>
            <ReactPlayer
              src={activeVideoUrl}
              controls
              playing
              width="100%"
              height="100%"
            />
          </div>
        </div>
      ) : null}
    </>
  );
}
