'use client';
import React, { useState } from 'react';
import { Article } from '@/types';
import Link from 'next/link';
import Image from 'next/image';
import { FaTimes } from 'react-icons/fa';

type ItemArticleProps = {
  item: Article;
};

const ItemArticleVideo: React.FC<ItemArticleProps> = ({ item }) => {
  const [open, setOpen] = useState(false);

  // chọn link: nếu có external_url thì dùng, ngược lại dùng url
  const linkHref = item.external_url && item.external_url !== '' ? item.external_url : item.url;

  // chọn ảnh: nếu có original thì dùng, ngược lại ảnh mặc định
  const imageSrc =
    item.image?.original && item.image.original !== ''
      ? item.image.original
      : '/static/assets/nguyencong_2023/images/not-image.png';

  // chọn thời gian: ưu tiên article_time, fallback createDate
  const timeDisplay =
    item.article_time && item.article_time !== '' ? item.article_time : item.createDate;

  const getYoutubeEmbedUrl = (url: string): string => {
    try {
      const urlObj = new URL(url);
      // nếu là link youtube dạng watch?v=...
      if (urlObj.hostname.includes('youtube.com')) {
        const videoId = urlObj.searchParams.get('v');
        if (videoId) {
          return `https://www.youtube.com/embed/${videoId}?autoplay=1`;
        }
      }
      // nếu là link youtu.be/xxxx
      if (urlObj.hostname.includes('youtu.be')) {
        const videoId = urlObj.pathname.replace('/', '');
        if (videoId) {
          return `https://www.youtube.com/embed/${videoId}?autoplay=1`;
        }
      }
      // fallback: trả về chính url
      return url;
    } catch {
      return url;
    }
  };

  return (
    <>
      <div className="item-article flex gap-3">
        <Link
          onClick={(e) => {
            e.preventDefault();
            setOpen(true);
          }}
          href="javascript:void(0)"
          className="img-article boder-radius-10 relative"
        >
          <Image
            className="boder-radius-10"
            src={imageSrc}
            width={265}
            height={180}
            alt={item.title}
          />
          {/* icon video nếu cần */}
          <i className="sprite sprite-icon-play-video-detail icon-video-feature incon-play-youtube"></i>
          <i className="sprite sprite-play-youtube incon-play-youtube"></i>
        </Link>

        <div className="content-article content-article-item flex flex-1 flex-col">
          <Link href={linkHref} className="title-article">
            <h3 className="line-clamp-2 font-[400]">{item.title}</h3>
          </Link>

          <p className="time-article flex items-center gap-4">
            <i className="sprite sprite-clock-item-article"></i>
            <span>{timeDisplay}</span>
          </p>

          <p className="descreption-article line-clamp-2">{item.summary}</p>
        </div>
      </div>
      {open && (
        <dialog id="video_modal" className="modal modal-open">
          <div className="modal-box w-11/12 max-w-3xl">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-bold">{item.title}</h3>
              <form method="dialog">
                <button
                  className="btn btn-sm btn-circle btn-ghost absolute top-2 right-2"
                  onClick={() => setOpen(false)}
                >
                  <FaTimes size={16} />
                </button>
              </form>
            </div>
            <div className="video-wrapper mt-4">
              <iframe
                width="100%"
                height="400"
                src={getYoutubeEmbedUrl(item.external_url)}
                title={item.title}
                frameBorder="0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
              ></iframe>
            </div>
          </div>
          <form method="dialog" className="modal-backdrop">
            <button onClick={() => setOpen(false)}>close</button>
          </form>
        </dialog>
      )}
    </>
  );
};

export default ItemArticleVideo;
