import React, { Ref, useRef, useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import Header from '../components/Header';
import clsx from 'clsx';
import BottomNav from '../components/BottomNav';
import { generateDeputyNews, generateNewsThumbnail } from '../utils/news';
import { getDeputyTitleFromRouteId } from '../utils/deputy';
import { getBackgroundImage } from '../utils/organization';
import { useParams } from 'react-router-dom';

interface NewsContainerProps {
  title: string;
  content: React.ReactNode;
  activeNews: number;
  totalNews: number;
  handleClickThumbnail: (idx: number) => void;
  articleRef: Ref<HTMLDivElement>;
  thumbnails: string[];
  deputyTitle: string;
}

function NewsContainer({
  title,
  content,
  activeNews,
  totalNews,
  handleClickThumbnail,
  articleRef,
  thumbnails,
  deputyTitle,
}: NewsContainerProps) {
  const { t } = useTranslation();

  return (
    <div className="grid grid-cols-1 lg:grid-cols-12 gap-[32px] my-auto w-full flex-1 items-center py-[10px] overflow-hidden">
      {/* Active Article Content Card (8 Cols) */}
      <div className="lg:col-span-8 h-[calc(100vh-250px)] flex flex-col justify-between bg-slate-900/70 border border-white/15 rounded-3xl p-[28px] md:p-[32px] backdrop-blur-md shadow-2xl overflow-hidden">
        <div className="space-y-[10px] flex-shrink-0">
          <div className="flex items-center space-x-[12px]">
            <span className="text-xs uppercase font-extrabold tracking-widest text-[#00AFDD] bg-[#001E31]/90 px-[16px] py-[6px] rounded-full border border-[#00AFDD]/40 backdrop-blur-md shadow-md">
              {deputyTitle} &bull; {t('achievement')}
            </span>
          </div>
          <h1 className="text-xl md:text-2xl lg:text-3xl font-extrabold text-white capitalize leading-tight drop-shadow-md">
            {title}
          </h1>
          <div className="w-[80px] h-[3px] bg-[#00AFDD] rounded-full"></div>
        </div>

        {/* Scrollable Article Text Body */}
        <div
          ref={articleRef}
          className="flex-1 mt-[16px] overflow-y-auto pr-[16px] custom-scrollbar text-slate-200 text-sm md:text-base leading-relaxed font-normal"
        >
          {typeof content === 'string' ? (
            <div dangerouslySetInnerHTML={{ __html: content }} />
          ) : (
            content
          )}
        </div>
      </div>

      {/* Thumbnail Selector Column (4 Cols) */}
      <div className="lg:col-span-4 h-[calc(100vh-250px)] flex flex-col space-y-[14px] overflow-y-auto pr-[10px] custom-scrollbar">
        {Array(totalNews)
          .fill('')
          .map((_, idx) => {
            const isActive = activeNews === idx;
            const numStr = idx < 9 ? `0${idx + 1}` : `${idx + 1}`;
            return (
              <div
                key={idx}
                onClick={() => handleClickThumbnail(idx)}
                className={clsx(
                  'p-[12px] md:p-[16px] rounded-2xl cursor-pointer transition-all duration-300 flex items-center justify-between border backdrop-blur-md group transform hover:translate-x-[4px]',
                  {
                    'bg-[#002D4B]/95 border-[#00AFDD] shadow-[0_4px_20px_rgba(0,175,221,0.3)]': isActive,
                    'bg-slate-900/60 border-white/10 hover:border-white/30 hover:bg-slate-900/80': !isActive,
                  }
                )}
              >
                <div className="flex items-center space-x-[14px] overflow-hidden">
                  <span
                    className={clsx(
                      'text-sm font-mono font-bold px-[10px] py-[4px] rounded-lg border flex-shrink-0',
                      {
                        'text-[#00AFDD] bg-[#001E31] border-[#00AFDD]/40': isActive,
                        'text-slate-400 bg-slate-800 border-white/10 group-hover:text-white': !isActive,
                      }
                    )}
                  >
                    {numStr}
                  </span>
                  <div className="truncate">
                    <div
                      className={clsx(
                        'text-xs md:text-sm font-bold truncate uppercase tracking-wide',
                        {
                          'text-[#00AFDD]': isActive,
                          'text-white group-hover:text-[#00AFDD]': !isActive,
                        }
                      )}
                    >
                      Artikel {numStr}
                    </div>
                  </div>
                </div>

                <img
                  src={thumbnails[idx]}
                  alt="thumbnail"
                  className={clsx(
                    'w-[80px] h-[55px] md:w-[95px] md:h-[65px] rounded-xl object-cover border transition-all duration-300 flex-shrink-0 ml-[12px]',
                    {
                      'border-[#00AFDD] scale-[1.03] shadow-md': isActive,
                      'border-white/20 opacity-80 group-hover:opacity-100 group-hover:border-white/50': !isActive,
                    }
                  )}
                />
              </div>
            );
          })}
      </div>
    </div>
  );
}

export default function AchievementPage() {
  const { t } = useTranslation();
  const { id } = useParams();
  const [activeNews, setActiveNews] = useState(0);
  const articleRef = useRef<HTMLDivElement>(null);

  const staticNews = generateDeputyNews(id, t);
  const staticThumbnails = generateNewsThumbnail(id);

  const [newsConfig, setNewsConfig] = useState<
    { title: string; content: React.ReactNode }[]
  >(staticNews);
  const [thumbnails, setThumbnails] = useState<string[]>(staticThumbnails);

  useEffect(() => {
    setActiveNews(0);
    const sNews = generateDeputyNews(id, t);
    const sThumbs = generateNewsThumbnail(id);

    fetch(`/api/news?deputy_id=${id}`)
      .then((res) => res.json())
      .then((data) => {
        if (Array.isArray(data) && data.length > 0) {
          const dbItems = data.map((item: any) => ({
            title: item.title,
            content: item.content,
          }));
          const dbThumbs = data.map((item: any, idx: number) =>
            item.thumbnail_url ? item.thumbnail_url : sThumbs[idx % sThumbs.length]
          );
          setNewsConfig(dbItems);
          setThumbnails(dbThumbs);
        } else {
          setNewsConfig(sNews);
          setThumbnails(sThumbs);
        }
      })
      .catch(() => {
        setNewsConfig(sNews);
        setThumbnails(sThumbs);
      });
  }, [id, t]);

  const articleScrollToTop = () => {
    if (articleRef.current) {
      articleRef.current.scrollTop = 0;
    }
  };

  const handleClickThumbnail = (idx: number) => {
    setActiveNews(idx);
    articleScrollToTop();
  };

  const handlePreviousNews = () => {
    if (activeNews > 0) {
      setActiveNews(activeNews - 1);
      articleScrollToTop();
    }
  };

  const handleNextNews = () => {
    if (activeNews < newsConfig.length - 1) {
      setActiveNews(activeNews + 1);
      articleScrollToTop();
    }
  };

  const currentBg = getBackgroundImage(id);
  const deputyTitle = getDeputyTitleFromRouteId(id, t);
  const currentTitle = newsConfig[activeNews]?.title || '';
  const currentContent = newsConfig[activeNews]?.content || '';

  return (
    <div
      className="h-screen w-screen max-w-full bg-[#002D4B] flex flex-col justify-between text-white bg-cover bg-no-repeat overflow-hidden relative"
      style={{
        backgroundImage: `linear-gradient(180deg, rgba(0, 30, 49, 0.88) 0%, rgba(0, 45, 75, 0.95) 100%), url("${currentBg}")`,
      }}
    >
      <div className="w-full max-w-[1500px] mx-auto px-[60px] h-full flex flex-col justify-between py-[20px] relative z-10 overflow-hidden">
        <Header />
        <NewsContainer
          articleRef={articleRef}
          title={currentTitle}
          content={currentContent}
          activeNews={activeNews}
          totalNews={newsConfig.length}
          handleClickThumbnail={handleClickThumbnail}
          thumbnails={thumbnails}
          deputyTitle={deputyTitle}
        />
        <BottomNav
          page={activeNews}
          totalPage={newsConfig.length}
          onClickPrev={handlePreviousNews}
          onClickNext={handleNextNews}
        />
      </div>
    </div>
  );
}
