"use client";

import { useEffect, useRef } from "react";
import Link from "next/link";
import Image from "next/image";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchSectionDetail,
  selectSectionDetailItems,
  selectSectionDetailLoaded,
  selectSectionDetailLoading,
  selectSectionDetailPagination,
} from "@/store/slices/sectionDetailSlice";
import { selectHomeSections } from "@/store/slices/homeSlice";
import { getStoredUser } from "@/lib/utils/persistAuth";
import { slugify } from "@/lib/utils/slugify";
import type {
  SectionArticle,
  SectionChannel,
  SectionCategory,
  SectionOpinionPoll,
} from "@/types/api/section.types";

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

// ── Article Card ─────────────────────────────────────────────────────────────
function ArticleCard({ item }: { item: SectionArticle }) {
  const img = isValidImg(item.web_image) ? item.web_image
    : isValidImg(item.landscape_img) ? item.landscape_img : null;
  return (
    <Link
      href={`/detail/${item.id}`}
      style={{
        display: "flex",
        gap: "1rem",
        padding: "1rem",
        background: "var(--surface)",
        border: "1px solid var(--border)",
        borderRadius: 10,
        textDecoration: "none",
        color: "inherit",
        transition: "box-shadow 0.15s",
      }}
    >
      <div style={{ flexShrink: 0, width: 110, height: 74, borderRadius: 7, overflow: "hidden", position: "relative", background: "#e5e7eb" }}>
        {img && <Image src={img} alt="" fill style={{ objectFit: "cover" }} unoptimized />}
        {item.is_premium === 1 && (
          <span style={{ position: "absolute", top: 4, left: 4, background: "#b45309", color: "#fff", fontSize: 8, fontWeight: 700, padding: "1px 5px", borderRadius: 3 }}>PREMIUM</span>
        )}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        {item.category && (
          <span style={{ fontSize: 9, fontWeight: 800, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--brand)", display: "block", marginBottom: 4 }}>
            {item.category}
          </span>
        )}
        <h3 style={{ fontSize: "0.875rem", fontWeight: 600, lineHeight: 1.4, margin: "0 0 6px", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", color: "var(--ink)" }}>
          {item.title}
        </h3>
        <div style={{ display: "flex", gap: "0.5rem", fontSize: "0.688rem", fontFamily: "var(--mono)", color: "var(--text-tertiary)" }}>
          <span>{fmtRelTime(item.created_at)}</span>
          {item.total_view > 0 && <><span>·</span><span>{fmtViews(item.total_view)}</span></>}
          {item.channel_name && <><span>·</span><span>{item.channel_name}</span></>}
        </div>
      </div>
    </Link>
  );
}

// ── Channel Card ─────────────────────────────────────────────────────────────
function ChannelCard({ item }: { item: SectionChannel }) {
  const img = isValidImg(item.landscape_img) ? item.landscape_img
    : isValidImg(item.portrait_img) ? item.portrait_img : null;
  return (
    <Link
      href={`/channel/${item.id}`}
      style={{
        display: "flex",
        flexDirection: "column",
        background: "var(--surface)",
        border: "1px solid var(--border)",
        borderRadius: 12,
        overflow: "hidden",
        textDecoration: "none",
        color: "inherit",
      }}
    >
      <div style={{ height: 120, position: "relative", background: "#1a1a2e" }}>
        {img && <Image src={img} alt={item.name} fill style={{ objectFit: "cover" }} unoptimized />}
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(0,0,0,0.6) 0%, transparent 60%)" }} />
        <div style={{ position: "absolute", bottom: 10, left: 12, right: 12 }}>
          <h3 style={{ color: "#fff", fontSize: "0.9375rem", fontWeight: 700, margin: 0 }}>{item.name}</h3>
        </div>
      </div>
      <div style={{ padding: "0.75rem 1rem" }}>
        <p style={{ fontSize: "0.8125rem", color: "var(--text-secondary)", margin: 0, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", lineHeight: 1.5 }}>
          {item.description}
        </p>
        <div style={{ marginTop: "0.5rem", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <span style={{ fontSize: "0.75rem", fontFamily: "var(--mono)", color: "var(--text-tertiary)" }}>
            {item.ch_full_name || item.ch_user_name}
          </span>
          <span style={{
            fontSize: "0.75rem", fontWeight: 700, color: "var(--brand)",
            padding: "3px 10px", border: "1px solid var(--brand)", borderRadius: 99,
          }}>
            Follow
          </span>
        </div>
      </div>
    </Link>
  );
}

// ── Category Card ─────────────────────────────────────────────────────────────
function CategoryCard({ item }: { item: SectionCategory }) {
  const img = isValidImg(item.web_image) ? item.web_image
    : isValidImg(item.app_image) ? item.app_image : null;
  const slug = slugify(item.name);
  return (
    <Link
      href={`/category/${slug}`}
      style={{
        display: "flex",
        alignItems: "center",
        gap: "1rem",
        padding: "1rem",
        background: "var(--surface)",
        border: "1px solid var(--border)",
        borderRadius: 10,
        textDecoration: "none",
        color: "inherit",
      }}
    >
      <div style={{ flexShrink: 0, width: 56, height: 56, borderRadius: 10, overflow: "hidden", position: "relative", background: "var(--brand-light)" }}>
        {img
          ? <Image src={img} alt={item.name} fill style={{ objectFit: "cover" }} unoptimized />
          : (
            <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <span style={{ fontSize: "1.25rem", fontWeight: 800, color: "var(--brand)" }}>
                {item.name.charAt(0).toUpperCase()}
              </span>
            </div>
          )
        }
      </div>
      <div>
        <h3 style={{ fontSize: "0.9375rem", fontWeight: 600, margin: "0 0 2px", color: "var(--ink)" }}>{item.name}</h3>
        <span style={{ fontSize: "0.75rem", color: "var(--text-secondary)" }}>Browse articles →</span>
      </div>
    </Link>
  );
}

// ── Opinion Poll Card ─────────────────────────────────────────────────────────
function OpinionPollCard({ item }: { item: SectionOpinionPoll }) {
  const options = [
    { key: "a", label: item.option_a, pct: item.percentage_option_a, count: item.option_a_count },
    { key: "b", label: item.option_b, pct: item.percentage_option_b, count: item.option_b_count },
    { key: "c", label: item.option_c, pct: item.percentage_option_c, count: item.option_c_count },
    { key: "d", label: item.option_d, pct: item.percentage_option_d, count: item.option_d_count },
  ].filter((o) => !!o.label);

  const maxPct = Math.max(...options.map((o) => parseFloat(o.pct) || 0));

  return (
    <div
      style={{
        background: "var(--surface)",
        border: "1px solid var(--border)",
        borderRadius: 12,
        padding: "1.25rem",
      }}
    >
      <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: "0.875rem" }}>
        {isValidImg(item.channel_image) ? (
          <Image src={item.channel_image} alt="" width={24} height={24} style={{ borderRadius: "50%" }} unoptimized />
        ) : (
          <div style={{ width: 24, height: 24, borderRadius: "50%", background: "var(--brand-light)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <span style={{ fontSize: 10, fontWeight: 700, color: "var(--brand)" }}>{item.channel_name?.charAt(0)}</span>
          </div>
        )}
        <span style={{ fontSize: "0.75rem", fontWeight: 600, color: "var(--text-secondary)" }}>{item.channel_name}</span>
        {item.is_complete === 1 && (
          <span style={{ marginLeft: "auto", fontSize: 9, fontWeight: 700, letterSpacing: "0.06em", color: "var(--text-tertiary)", textTransform: "uppercase" }}>Closed</span>
        )}
      </div>

      <h3 style={{ fontSize: "0.9375rem", fontWeight: 700, lineHeight: 1.4, margin: "0 0 1rem", color: "var(--ink)" }}>
        {item.question}
      </h3>

      <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem", marginBottom: "0.875rem" }}>
        {options.map((opt) => {
          const pct = parseFloat(opt.pct) || 0;
          const isLeading = pct === maxPct && pct > 0;
          return (
            <div key={opt.key} style={{ position: "relative" }}>
              <div style={{
                height: 38,
                borderRadius: 8,
                background: isLeading ? "var(--brand-light)" : "#f3f4f6",
                overflow: "hidden",
                position: "relative",
                border: `1px solid ${isLeading ? "var(--brand)" : "transparent"}`,
              }}>
                <div style={{
                  position: "absolute",
                  left: 0,
                  top: 0,
                  height: "100%",
                  width: `${pct}%`,
                  background: isLeading ? "rgba(193,39,45,0.12)" : "rgba(0,0,0,0.04)",
                  transition: "width 0.5s ease",
                }} />
                <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 10px" }}>
                  <span style={{ fontSize: "0.8125rem", fontWeight: isLeading ? 700 : 500, color: isLeading ? "var(--brand)" : "var(--ink)" }}>
                    {opt.label}
                  </span>
                  <span style={{ fontSize: "0.75rem", fontFamily: "var(--mono)", fontWeight: 700, color: isLeading ? "var(--brand)" : "var(--text-secondary)" }}>
                    {pct}%
                  </span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: "0.75rem", fontFamily: "var(--mono)", color: "var(--text-tertiary)" }}>
        <span>{item.total_opinions} votes</span>
        {item.closing_date && <span>Closes {item.closing_date}</span>}
      </div>
    </div>
  );
}

// ── Skeleton ──────────────────────────────────────────────────────────────────
function Skeleton() {
  return (
    <div style={{ display: "flex", gap: "1rem", padding: "1rem", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 10 }}>
      <div style={{ flexShrink: 0, width: 110, height: 74, borderRadius: 7, background: "#e5e7eb" }} />
      <div style={{ flex: 1 }}>
        <div style={{ height: 9, width: "25%", borderRadius: 4, background: "#e5e7eb", marginBottom: 8 }} />
        <div style={{ height: 13, width: "90%", borderRadius: 4, background: "#e5e7eb", marginBottom: 5 }} />
        <div style={{ height: 13, width: "70%", borderRadius: 4, background: "#e5e7eb", marginBottom: 10 }} />
        <div style={{ height: 9, width: "40%", borderRadius: 4, background: "#e5e7eb" }} />
      </div>
    </div>
  );
}

// ── Main Shell ────────────────────────────────────────────────────────────────
interface Props {
  sectionId: number;
  sectionType?: number;
  sectionTitle?: string;
}

function renderItem(item: Record<string, unknown>, detectedType: number, index: number) {
  const key = `${detectedType}-${(item.id as number) ?? index}`;

  switch (detectedType) {
    case 9: return <ChannelCard key={key} item={item as unknown as SectionChannel} />;
    case 7: return <CategoryCard key={key} item={item as unknown as SectionCategory} />;
    case 6: return <OpinionPollCard key={key} item={item as unknown as SectionOpinionPoll} />;
    default: return <ArticleCard key={key} item={item as unknown as SectionArticle} />;
  }
}

export default function SectionDetailShell({ sectionId, sectionType, sectionTitle }: Props) {
  const dispatch = useAppDispatch();
  const dispatchedRef = useRef(false);

  const homeSections = useAppSelector(selectHomeSections);
  const items   = useAppSelector(selectSectionDetailItems(sectionId));
  const isLoaded = useAppSelector(selectSectionDetailLoaded(sectionId));
  const isLoading = useAppSelector(selectSectionDetailLoading);
  const pagination = useAppSelector(selectSectionDetailPagination(sectionId));

  // Derive section metadata from Redux home state or URL params
  const homeSection = homeSections.find((s) => s.id === sectionId);
  const title = homeSection?.title ?? sectionTitle ?? "Section";
  const subTitle = homeSection?.sub_title;
  // Determine type: from homeSection → URL param → detect from first item
  const resolvedType = homeSection?.type ?? sectionType ?? 1;

  // Detect type from first item when no other hint is available
  const firstItem = items[0] as unknown as Record<string, unknown> | undefined;
  const detectedType =
    resolvedType ||
    (firstItem?.question ? 6 : firstItem?.ch_user_name ? 9 : firstItem?.app_image ? 7 : 1);

  useEffect(() => {
    if (!isLoaded && !dispatchedRef.current) {
      dispatchedRef.current = true;
      dispatch(fetchSectionDetail({ sectionId, userId: getStoredUser()?.id ?? 0, page: 1 }));
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Grid layout per type
  const isGrid = [7, 9].includes(detectedType);
  const isPoll = detectedType === 6;

  return (
    <main style={{ minHeight: "60vh", background: "var(--bg)" }}>
      <div className="wrap" style={{ paddingTop: "2rem", paddingBottom: "3rem" }}>

        {/* ── Breadcrumb ── */}
        <nav style={{ display: "flex", alignItems: "center", gap: "0.5rem", fontSize: "0.8125rem", color: "var(--text-tertiary)", marginBottom: "1.5rem", fontFamily: "var(--mono)" }}>
          <Link href="/home" style={{ color: "var(--text-tertiary)", textDecoration: "none" }}>Home</Link>
          <span>›</span>
          <span style={{ color: "var(--ink)" }}>{title}</span>
        </nav>

        {/* ── Section Header ── */}
        <div style={{ marginBottom: "2rem", paddingBottom: "1.25rem", borderBottom: "2px solid var(--brand)" }}>
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: "1rem" }}>
            <div>
              <h1 style={{ fontFamily: "var(--serif)", fontSize: "clamp(1.5rem, 3vw, 2.25rem)", fontWeight: 700, margin: "0 0 0.375rem", color: "var(--ink)" }}>
                {title}
              </h1>
              {subTitle && (
                <p style={{ fontSize: "0.9375rem", color: "var(--text-secondary)", margin: 0 }}>{subTitle}</p>
              )}
            </div>
            {pagination && (
              <span style={{ fontSize: "0.75rem", fontFamily: "var(--mono)", color: "var(--text-tertiary)", flexShrink: 0 }}>
                {pagination.totalRows} items
              </span>
            )}
          </div>
        </div>

        {/* ── Content ── */}
        {isLoading && items.length === 0 ? (
          <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
            {Array.from({ length: 8 }).map((_, i) => <Skeleton key={i} />)}
          </div>
        ) : items.length === 0 ? (
          <div style={{ textAlign: "center", padding: "4rem 0", color: "var(--text-secondary)" }}>
            <p style={{ fontWeight: 600, marginBottom: "0.5rem" }}>No items found</p>
            <p style={{ fontSize: "0.875rem" }}>This section has no content yet</p>
          </div>
        ) : (
          <div style={
            isGrid
              ? { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: "1rem" }
              : isPoll
              ? { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: "1.25rem" }
              : { display: "flex", flexDirection: "column", gap: "0.75rem" }
          }>
            {items.map((item, i) => renderItem(item as unknown as Record<string, unknown>, detectedType, i))}
          </div>
        )}

        {/* ── Load More ── */}
        {pagination?.hasMore && !isLoading && (
          <div style={{ textAlign: "center", marginTop: "2rem" }}>
            <button
              onClick={() =>
                dispatch(fetchSectionDetail({
                  sectionId,
                  userId: getStoredUser()?.id ?? 0,
                  page: (pagination.currentPage ?? 1) + 1,
                }))
              }
              style={{
                padding: "0.625rem 2rem",
                background: "var(--brand)",
                color: "#fff",
                border: "none",
                borderRadius: 8,
                fontWeight: 700,
                fontSize: "0.875rem",
                cursor: "pointer",
              }}
            >
              Load more
            </button>
          </div>
        )}
        {isLoading && items.length > 0 && (
          <div style={{ textAlign: "center", marginTop: "1.5rem", color: "var(--text-tertiary)", fontSize: "0.875rem" }}>
            Loading…
          </div>
        )}
      </div>
    </main>
  );
}
