"use client";

import React, { useState } from "react";
import { useTranslation } from "@/hooks/useTranslation";
import type { ArticleCard, FeaturedArticle } from "../types/category.types";
import { useAppSelector } from "@/store/hooks";
import {
  selectCategorySections,
  selectSectionByLayout,
} from "@/store/slices/homeSlice";
import { slugify } from "@/lib/utils/slugify";
import type { SectionArticle } from "@/types/api/section.types";

interface CategoryContentProps {
  categoryName: string;
  categorySlug: string;
  featured: FeaturedArticle;
  articles: ArticleCard[];
  totalCount: string;
  children?: React.ReactNode;
}

const SaveIcon = () => (
  <svg viewBox="0 0 24 24">
    <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />
  </svg>
);

const ShareIcon = () => (
  <svg viewBox="0 0 24 24">
    <circle cx="18" cy="5" r="3" />
    <circle cx="6" cy="12" r="3" />
    <circle cx="18" cy="19" r="3" />
    <path d="M8.6 13.5l6.8 4M15.4 6.5l-6.8 4" />
  </svg>
);

const PlayIcon = () => (
  <svg viewBox="0 0 24 24">
    <polygon points="6 4 20 12 6 20" />
  </svg>
);

const LockIcon = () => (
  <svg viewBox="0 0 24 24">
    <rect x="5" y="11" width="14" height="10" rx="2" />
    <path d="M8 11V7a4 4 0 0 1 8 0v4" />
  </svg>
);

const GridIcon = () => (
  <svg viewBox="0 0 24 24">
    <rect x="3" y="3" width="7" height="7" />
    <rect x="14" y="3" width="7" height="7" />
    <rect x="3" y="14" width="7" height="7" />
    <rect x="14" y="14" width="7" height="7" />
  </svg>
);

const ListIcon = () => (
  <svg viewBox="0 0 24 24">
    <line x1="8" y1="6" x2="21" y2="6" />
    <line x1="8" y1="12" x2="21" y2="12" />
    <line x1="8" y1="18" x2="21" y2="18" />
    <circle cx="4" cy="6" r="1" />
    <circle cx="4" cy="12" r="1" />
    <circle cx="4" cy="18" r="1" />
  </svg>
);

const ClockIcon = () => (
  <svg className="icn icn-sm" viewBox="0 0 24 24">
    <circle cx="12" cy="12" r="9" />
    <path d="M12 7v5l3 2" />
  </svg>
);

const EyeIcon = () => (
  <svg className="icn icn-sm" viewBox="0 0 24 24">
    <circle cx="12" cy="12" r="3" />
    <path d="M2 12s4-8 10-8 10 8 10 8-4 8-10 8S2 12 2 12z" />
  </svg>
);

function fmtRelTime(dateStr: string) {
  const diff = Date.now() - new Date(dateStr).getTime();
  const hrs = Math.floor(diff / 3600000);
  if (hrs < 1) return `${Math.floor(diff / 60000)}m`;
  if (hrs < 24) return `${hrs}h`;
  return `${Math.floor(hrs / 24)}d`;
}
function fmtViews(n: number) {
  if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
  if (n >= 1000) return `${Math.round(n / 1000)}K`;
  return String(n);
}
function isValidImg(url: string) {
  return !!url && !url.includes("no_img");
}

function apiToArticleCard(a: SectionArticle): ArticleCard {
  return {
    id: String(a.id),
    slug: String(a.id),
    category: a.category ?? "",
    title: a.title,
    excerpt: a.short_description ?? "",
    image: isValidImg(a.web_image)
      ? a.web_image
      : isValidImg(a.landscape_img)
        ? a.landscape_img
        : "",
    author: a.channel_name,
    publishedAt: fmtRelTime(a.created_at),
    readTime: "3 min read",
    views: fmtViews(a.total_view),
    type: a.is_premium ? "premium" : "article",
  };
}

function apiToFeatured(a: SectionArticle): FeaturedArticle {
  return {
    slug: String(a.id),
    category: a.category ?? "",
    title: a.title,
    lede: a.short_description ?? "",
    image: isValidImg(a.web_image)
      ? a.web_image
      : isValidImg(a.landscape_img)
        ? a.landscape_img
        : "https://images.unsplash.com/photo-1467269204594-9661b134dd2b?w=1200&q=80",
    author: a.channel_name,
    authorInitials: a.channel_name?.slice(0, 2).toUpperCase() ?? "DT",
    publishedAt: fmtRelTime(a.created_at),
    readTime: "5 min read",
    views: fmtViews(a.total_view),
  };
}

export default function CategoryContent({
  categoryName,
  categorySlug,
  totalCount,
  featured,
  children,
}: Omit<CategoryContentProps, "articles">) {
  const { t } = useTranslation("category");
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const [activeFilter, setActiveFilter] = useState("today");
  const [visibleCount, setVisibleCount] = useState(12);

  // Use real API data when available
  const navCategories = useAppSelector((s) => s.navCategories.items);
  const category = navCategories.find((c) => slugify(c.name) === categorySlug);
  const categoryId = category?.id ?? 0;
  const sections = useAppSelector((s) => selectCategorySections(s, categoryId));
  const listViewSection = selectSectionByLayout(sections, "list_view");
  const apiArticles = (listViewSection?.data ?? []) as SectionArticle[];

  const allArticles: ArticleCard[] =
    apiArticles.length > 0 ? apiArticles.map(apiToArticleCard) : [];
  const resolvedArticles = allArticles.slice(0, visibleCount);
  const hasMore = visibleCount < allArticles.length;
  const resolvedFeatured: FeaturedArticle =
    apiArticles.length > 0 ? apiToFeatured(apiArticles[0]) : featured;

  const filters = [
    { key: "today", label: t("filter.today") },
    { key: "week", label: t("filter.this_week") },
    { key: "month", label: t("filter.this_month") },
  ];

  return (
    <>
      {/* Filter bar */}
      <div className="filterbar">
        <div className="wrap filterbar-row">
          <div className="filter-side">
            <span className="filter-lbl">{t("filter.label")}</span>
            {filters.map((f) => (
              <button
                key={f.key}
                className={`fchip${activeFilter === f.key ? " active" : ""}`}
                onClick={() => setActiveFilter(f.key)}
              >
                {f.label}
              </button>
            ))}
            <button className="fchip">
              <PlayIcon />
              {t("filter.video")}
            </button>
            <button className="fchip">{t("filter.audio")}</button>
            <button className="fchip">{t("filter.premium")}</button>
          </div>
          <div className="sort-side">
            <span className="filter-lbl">{t("filter.sort_by")}</span>
            <select className="sort-sel">
              <option>{t("filter.latest")}</option>
              <option>{t("filter.most_viewed")}</option>
              <option>{t("filter.most_shared")}</option>
              <option>{t("filter.trending")}</option>
            </select>
            <div className="view-toggle">
              <button
                className={viewMode === "grid" ? "on" : ""}
                onClick={() => setViewMode("grid")}
                title="Grid view"
              >
                <GridIcon />
              </button>
              <button
                className={viewMode === "list" ? "on" : ""}
                onClick={() => setViewMode("list")}
                title="List view"
              >
                <ListIcon />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Featured article */}

      {/* Article grid */}
      <section className="wrap">
        <div className="main-grid">
          <div>
            <div className="section-head">
              <h2>
                {t("latest_in")} {categoryName}
              </h2>
              <span className="count-mini">
                {t("showing_of", { total: totalCount })}
              </span>
            </div>

            <div
              className={viewMode === "grid" ? "grid-view" : "list-view"}
              id="articleList"
            >
              {resolvedArticles.length === 0 ? (
                <div style={{
                  gridColumn: "1 / -1",
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "center",
                  padding: "4rem 1rem",
                  gap: "0.75rem",
                  color: "var(--text-secondary, #6b7280)",
                }}>
                  <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" opacity={0.4}>
                    <circle cx="11" cy="11" r="8" />
                    <path d="M21 21l-4.35-4.35M11 8v6M8 11h6" />
                  </svg>
                  <p style={{ margin: 0, fontSize: "1rem", fontWeight: 600 }}>No articles found</p>
                  <p style={{ margin: 0, fontSize: "0.875rem" }}>There are no articles in this category yet.</p>
                </div>
              ) : resolvedArticles.map((card) => (
                <article key={card.id} className="card">
                  <div className="card-img">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    {card.image ? <img src={card.image} alt="" /> : null}
                    {card.type === "video" && card.duration && (
                      <>
                        <span className="play-btn">
                          <PlayIcon />
                        </span>
                        <span className="duration">{card.duration}</span>
                      </>
                    )}
                    {card.type === "premium" && (
                      <span className="premium-lock">
                        <LockIcon />
                        PREMIUM
                      </span>
                    )}
                  </div>
                  <div className="card-body">
                    <span className="card-tag">{card.category}</span>
                    <h3>{card.title}</h3>
                    <p className="excerpt">{card.excerpt}</p>
                    <div className="card-foot">
                      <span>
                        <span className="who">{card.author}</span>
                        <span className="who-sep">·</span>
                        <span className="time">{card.publishedAt}</span>
                      </span>
                      <span className="icns">
                        <button className="icn-btn" title={t("save")}>
                          <SaveIcon />
                        </button>
                        <button className="icn-btn" title={t("share")}>
                          <ShareIcon />
                        </button>
                      </span>
                    </div>
                  </div>
                </article>
              ))}
            </div>


            {/* View More */}
            {hasMore && (
              <div style={{ display: "flex", justifyContent: "center", marginTop: "2rem" }}>
                <button
                  onClick={() => setVisibleCount((n) => n + 12)}
                  style={{
                    display: "inline-flex",
                    alignItems: "center",
                    gap: "0.5rem",
                    padding: "0.625rem 2rem",
                    border: "1.5px solid var(--brand, #C1272D)",
                    borderRadius: 8,
                    background: "transparent",
                    color: "var(--brand, #C1272D)",
                    fontSize: "0.9375rem",
                    fontWeight: 700,
                    cursor: "pointer",
                    transition: "background 0.15s, color 0.15s",
                  }}
                  onMouseEnter={(e) => {
                    (e.currentTarget as HTMLButtonElement).style.background = "var(--brand, #C1272D)";
                    (e.currentTarget as HTMLButtonElement).style.color = "#fff";
                  }}
                  onMouseLeave={(e) => {
                    (e.currentTarget as HTMLButtonElement).style.background = "transparent";
                    (e.currentTarget as HTMLButtonElement).style.color = "var(--brand, #C1272D)";
                  }}
                >
                  View More
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                    <path d="M12 5v14M5 12l7 7 7-7" />
                  </svg>
                </button>
              </div>
            )}
          </div>

          {children}
        </div>
      </section>
    </>
  );
}

//  <section className="wrap section-wrap">
//         <article className="featured">
//           <div className="featured-img">
//             {/* eslint-disable-next-line @next/next/no-img-element */}
//             <img
//               className="frame"
//               src={resolvedFeatured.image}
//               alt={resolvedFeatured.title}
//             />
//             {resolvedFeatured.liveTag && (
//               <span className="live-tag">{resolvedFeatured.liveTag}</span>
//             )}
//           </div>
//           <div className="featured-body">
//             <span className="featured-label">{t("featured")}</span>
//             <h2>{resolvedFeatured.title}</h2>
//             <p className="lede">{resolvedFeatured.lede}</p>
//             <div className="featured-meta">
//               <span className="av">{resolvedFeatured.authorInitials}</span>
//               <span className="who">{resolvedFeatured.author}</span>
//               <span className="sep" />
//               <span className="stat">
//                 <ClockIcon />
//                 {resolvedFeatured.publishedAt} · {resolvedFeatured.readTime}
//               </span>
//               <span className="sep" />
//               <span className="stat">
//                 <EyeIcon />
//                 {resolvedFeatured.views}
//               </span>
//             </div>
//             <div className="featured-foot">
//               <a href={`/detail/${resolvedFeatured.slug}`}>
//                 {t("read_full_story")}
//                 <svg className="icn icn-sm" viewBox="0 0 24 24">
//                   <path d="M5 12h14M13 6l6 6-6 6" />
//                 </svg>
//               </a>
//               <div className="icns">
//                 <button className="icn-btn" title={t("save")}>
//                   <SaveIcon />
//                 </button>
//                 <button className="icn-btn" title={t("share")}>
//                   <ShareIcon />
//                 </button>
//               </div>
//             </div>
//           </div>
//         </article>
//       </section>
