"use client";

import { useEffect, useState, useCallback } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import {
  ArrowLeft, Play, Music2, Download, Heart,
  Eye, Clock, MoreHorizontal,
} from "lucide-react";
import { useAppDispatch } from "@/store/hooks";
import { setTrack, setQueue } from "@/store/slices/playerSlice";
import { musicSectionService, type MusicItem } from "@/services/musicSectionService";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";

/* ── Format helpers ──────────────────────────────────────────────────────── */

function fmtDuration(ms: number): string {
  const totalSec = Math.floor(ms / 1000);
  const m = Math.floor(totalSec / 60);
  const s = totalSec % 60;
  return `${m}:${String(s).padStart(2, "0")}`;
}

/* ── Track row ───────────────────────────────────────────────────────────── */

function TrackRow({
  item,
  index,
  total,
  onPlay,
  isActive,
}: {
  item: MusicItem;
  index: number;
  total: number;
  onPlay: () => void;
  isActive: boolean;
}) {
  const [hovered, setHovered] = useState(false);

  return (
    <div
      className="group flex items-center gap-4 px-4 py-2.5 rounded-xl cursor-pointer transition-all duration-150"
      style={{
        background: isActive
          ? "rgba(var(--accent-rgb),0.08)"
          : hovered
          ? "var(--btn-ghost)"
          : "transparent",
        borderLeft: `2px solid ${isActive ? "var(--accent)" : "transparent"}`,
        animation: "msd-row-in 0.38s ease both",
        animationDelay: `${Math.min(index * 35, 600)}ms`,
      }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      onClick={onPlay}
    >
      {/* Index / play toggle */}
      <div className="w-8 flex items-center justify-center flex-shrink-0">
        {isActive ? (
          <div className="flex items-end gap-[2px] h-4">
            {[3, 5, 4, 6, 3].map((h, i) => (
              <span
                key={i}
                className="w-[2px] rounded-full"
                style={{
                  background: "var(--accent)",
                  height: `${h * 2}px`,
                  animation: `eq-bounce ${0.4 + i * 0.08}s ease-in-out infinite alternate`,
                }}
              />
            ))}
          </div>
        ) : hovered ? (
          <div
            className="w-7 h-7 rounded-full flex items-center justify-center transition-all"
            style={{ background: "var(--accent)", paddingLeft: 1 }}
          >
            <Play size={11} fill="#fff" color="#fff" strokeWidth={0} />
          </div>
        ) : (
          <span
            className="text-[12px] font-semibold tabular-nums"
            style={{ color: isActive ? "var(--accent)" : "#555" }}
          >
            {String(index + 1).padStart(2, "0")}
          </span>
        )}
      </div>

      {/* Thumbnail */}
      <div
        className="relative flex-shrink-0 rounded-lg overflow-hidden"
        style={{
          width: 40, height: 40, background: "var(--deep)",
          boxShadow: isActive ? "0 0 0 1.5px var(--accent)" : "none",
        }}
      >
        {item.thumbnail ? (
          <Image
            src={item.thumbnail}
            alt={item.title}
            fill
            className="object-cover"
            unoptimized
            sizes="40px"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Music2 size={16} color="var(--text-muted)" />
          </div>
        )}
      </div>

      {/* Title + artist */}
      <div className="flex-1 min-w-0">
        <p
          className="text-[13px] font-semibold truncate"
          style={{ color: isActive ? "var(--accent)" : "#fff" }}
        >
          {item.title}
        </p>
        <p className="text-[11px] truncate mt-0.5" style={{ color: "#777" }}>
          {item.channelName}
        </p>
      </div>

      {/* Stats (visible on wider screens) */}
      <div
        className="hidden sm:flex items-center gap-4 flex-shrink-0"
        style={{ color: "#555" }}
      >
        {item.views && (
          <div className="flex items-center gap-1">
            <Eye size={10} strokeWidth={1.8} />
            <span className="text-[10px]">{item.views}</span>
          </div>
        )}
        {item.likes && (
          <div className="flex items-center gap-1">
            <Heart size={10} strokeWidth={1.8} />
            <span className="text-[10px]">{item.likes}</span>
          </div>
        )}
        {item.isDownload && (
          <Download size={12} strokeWidth={1.8} />
        )}
      </div>

      {/* Duration */}
      {item.durationMs > 0 && (
        <div className="flex items-center gap-1 flex-shrink-0" style={{ color: "#555" }}>
          <Clock size={10} strokeWidth={1.8} />
          <span className="text-[11px] tabular-nums">{fmtDuration(item.durationMs)}</span>
        </div>
      )}

      {/* More */}
      <button
        className="w-7 h-7 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all flex-shrink-0"
        style={{ color: "#666" }}
        onClick={(e) => e.stopPropagation()}
      >
        <MoreHorizontal size={14} strokeWidth={1.8} />
      </button>
    </div>
  );
}

/* ── Skeleton ────────────────────────────────────────────────────────────── */

function RowSkeleton({ i }: { i: number }) {
  return (
    <div
      className="flex items-center gap-4 px-4 py-2.5 animate-pulse"
      style={{ animationDelay: `${i * 40}ms` }}
    >
      <div className="w-8 h-4 rounded flex-shrink-0" style={{ background: "var(--border-soft)" }} />
      <div className="w-10 h-10 rounded-lg flex-shrink-0" style={{ background: "var(--border)" }} />
      <div className="flex-1 space-y-1.5">
        <div className="h-3 rounded-full" style={{ background: "var(--border)", width: `${55 + (i % 4) * 10}%` }} />
        <div className="h-2.5 rounded-full" style={{ background: "var(--btn-ghost)", width: "40%" }} />
      </div>
      <div className="w-10 h-2.5 rounded-full hidden sm:block" style={{ background: "var(--btn-ghost)" }} />
      <div className="w-8 h-2.5 rounded-full" style={{ background: "var(--btn-ghost)" }} />
    </div>
  );
}

/* ── Header ──────────────────────────────────────────────────────────────── */

function SectionHeader({
  title,
  count,
  tracks,
  onPlayAll,
}: {
  title: string;
  count: number;
  tracks: MusicItem[];
  onPlayAll: () => void;
}) {
  const coverImages = tracks.slice(0, 4).map((t) => t.thumbnail).filter(Boolean);

  return (
    <div
      className="relative overflow-hidden px-5 pt-8 pb-6"
      style={{
        background: "linear-gradient(180deg, rgba(var(--accent-rgb),0.08) 0%, transparent 100%)",
        borderBottom: "1px solid var(--border-soft)",
        animation: "msd-head-in 0.4s ease both",
      }}
    >
      {/* Ambient glow */}
      <div
        className="absolute top-0 left-0 w-64 h-64 pointer-events-none"
        style={{
          background: "radial-gradient(circle, rgba(var(--accent-rgb),0.07) 0%, transparent 70%)",
          transform: "translate(-30%, -30%)",
        }}
      />

      <div className="flex items-end gap-5 relative z-10">
        {/* Collage cover */}
        <div
          className="flex-shrink-0 rounded-2xl overflow-hidden"
          style={{
            width: 96, height: 96,
            background: "var(--deep)",
            boxShadow: "0 12px 36px rgba(0,0,0,0.55)",
          }}
        >
          {coverImages.length >= 4 ? (
            <div className="grid grid-cols-2 w-full h-full">
              {coverImages.map((src, i) => (
                <div key={i} className="relative overflow-hidden">
                  <Image src={src} alt="" fill className="object-cover" unoptimized sizes="48px" />
                </div>
              ))}
            </div>
          ) : coverImages[0] ? (
            <div className="relative w-full h-full">
              <Image src={coverImages[0]} alt="" fill className="object-cover" unoptimized sizes="96px" />
            </div>
          ) : (
            <div className="w-full h-full flex items-center justify-center">
              <Music2 size={32} color="var(--text-muted)" />
            </div>
          )}
        </div>

        {/* Meta */}
        <div className="flex-1 min-w-0">
          <p className="text-[10px] font-bold uppercase tracking-widest mb-1" style={{ color: "var(--accent)" }}>
            Music Collection
          </p>
          <h1
            className="text-xl font-black leading-tight mb-2 line-clamp-2"
            style={{ color: "var(--text-primary)", letterSpacing: "-0.02em" }}
          >
            {title}
          </h1>
          <p className="text-[11px]" style={{ color: "#666" }}>
            {count} {count === 1 ? "track" : "tracks"}
          </p>
        </div>
      </div>

      {/* Play all button */}
      {tracks.length > 0 && (
        <button
          onClick={onPlayAll}
          className="mt-5 flex items-center gap-2.5 px-5 py-2.5 rounded-full text-[12px] font-black text-[#ffffff] transition-all active:scale-95 hover:brightness-110"
          style={{
            background: "var(--accent)",
            boxShadow: "0 6px 20px rgba(var(--accent-rgb),0.3)",
          }}
        >
          <Play size={14} fill="#fff" color="#fff" strokeWidth={0} />
          Play All
        </button>
      )}
    </div>
  );
}

/* ── Main page ───────────────────────────────────────────────────────────── */

export default function MusicSectionDetailPage({
  sectionId,
  sectionTitle,
}: {
  sectionId: string;
  sectionTitle: string;
}) {
  const router = useRouter();
  const dispatch = useAppDispatch();

  const [tracks, setTracks] = useState<MusicItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [hasMore, setHasMore] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalRows, setTotalRows] = useState(0);
  const [activeId, setActiveId] = useState<string | null>(null);
  const [error, setError] = useState("");
  const fetchPage = useCallback(async (pageNo: number) => {
    if (pageNo === 1) setIsLoading(true);
    else setIsLoadingMore(true);
    try {
      const res = await musicSectionService.getSectionDetail(sectionId, pageNo);
      const mapped = (res.result ?? []).map((r) => musicSectionService.mapItem(r));
      setTracks((prev) => pageNo === 1 ? mapped : [...prev, ...mapped]);
      setHasMore(res.more_page);
      setCurrentPage(res.current_page);
      setTotalRows(res.total_rows);
    } catch {
      setError("Failed to load tracks.");
    } finally {
      setIsLoading(false);
      setIsLoadingMore(false);
    }
  }, [sectionId]);

  useEffect(() => { fetchPage(1); }, [fetchPage]);

  const handleLoadMore = useCallback(() => {
    fetchPage(currentPage + 1);
  }, [fetchPage, currentPage]);

  const sentinelRef = useInfiniteScroll({
    hasMore,
    isLoading: isLoading || isLoadingMore,
    onLoadMore: handleLoadMore,
  });

  const handlePlay = (item: MusicItem, index: number) => {
    setActiveId(item.id);
    dispatch(setQueue(tracks));
    dispatch(setTrack(item));
  };

  const handlePlayAll = () => {
    if (tracks.length === 0) return;
    setActiveId(tracks[0]!.id);
    dispatch(setQueue(tracks));
    dispatch(setTrack(tracks[0]!));
  };

  return (
    <div className="min-h-screen pb-28" style={{ background: "var(--bg)" }}>

      {/* Back bar */}
      <div
        className="sticky top-0 z-10 flex items-center gap-3 px-4 py-3"
        style={{ background: "var(--bg)", borderBottom: "1px solid var(--border-soft)" }}
      >
        <button
          onClick={() => router.back()}
          className="w-8 h-8 rounded-full flex items-center justify-center transition-all hover:brightness-125"
          style={{ background: "var(--btn-ghost)" }}
        >
          <ArrowLeft size={15} color="#fff" strokeWidth={2} />
        </button>
        <span className="text-sm font-bold truncate" style={{ color: "var(--text-primary)" }}>{sectionTitle}</span>
      </div>

      {/* Header */}
      {!isLoading && !error && (
        <SectionHeader
          title={sectionTitle}
          count={totalRows}
          tracks={tracks}
          onPlayAll={handlePlayAll}
        />
      )}

      {/* Track list */}
      <div className="px-2 py-3">

        {/* Column headers */}
        {!isLoading && tracks.length > 0 && (
          <div
            className="flex items-center gap-4 px-4 py-2 mb-1"
            style={{ borderBottom: "1px solid var(--border-soft)" }}
          >
            <span className="w-8 text-center text-[10px] font-bold" style={{ color: "#444" }}>#</span>
            <span className="flex-1 text-[10px] font-bold uppercase tracking-widest" style={{ color: "#444" }}>Title</span>
            <div className="hidden sm:flex items-center gap-4">
              <Eye size={10} color="#444" strokeWidth={1.8} />
              <Heart size={10} color="#444" strokeWidth={1.8} />
              <Download size={10} color="transparent" strokeWidth={1.8} />
            </div>
            <Clock size={10} color="#444" strokeWidth={1.8} />
            <span className="w-7" />
          </div>
        )}

        {/* Loading skeletons */}
        {isLoading && (
          <div className="flex flex-col">
            {Array.from({ length: 12 }).map((_, i) => <RowSkeleton key={i} i={i} />)}
          </div>
        )}

        {/* Error */}
        {!isLoading && error && (
          <div className="flex flex-col items-center justify-center py-20 gap-3">
            <Music2 size={32} color="#555" strokeWidth={1.2} />
            <p className="text-sm" style={{ color: "#888" }}>{error}</p>
            <button
              onClick={() => fetchPage(1)}
              className="text-[11px] font-semibold px-4 py-2 rounded-full text-[#ffffff] active:scale-95"
              style={{ background: "var(--accent)" }}
            >
              Retry
            </button>
          </div>
        )}

        {/* Empty */}
        {!isLoading && !error && tracks.length === 0 && (
          <div className="flex flex-col items-center justify-center py-20 gap-2">
            <Music2 size={32} color="#555" strokeWidth={1.2} />
            <p className="text-sm" style={{ color: "#888" }}>No tracks in this section</p>
          </div>
        )}

        {/* Tracks */}
        {!isLoading && tracks.length > 0 && (
          <>
            {tracks.map((item, i) => (
              <TrackRow
                key={item.id}
                item={item}
                index={i}
                total={tracks.length}
                isActive={activeId === item.id}
                onPlay={() => handlePlay(item, i)}
              />
            ))}

            {/* Infinite scroll sentinel */}
            <div ref={sentinelRef} className="h-1" />

            {isLoadingMore && (
              <div className="flex justify-center py-6">
                <div className="flex gap-1.5">
                  {[0, 1, 2].map((i) => (
                    <div
                      key={i}
                      className="w-1.5 h-1.5 rounded-full animate-pulse"
                      style={{ background: "var(--accent)", animationDelay: `${i * 150}ms` }}
                    />
                  ))}
                </div>
              </div>
            )}

            {!hasMore && tracks.length > 0 && (
              <p className="text-center text-[10px] py-6" style={{ color: "#333" }}>
                — {totalRows} tracks total —
              </p>
            )}
          </>
        )}
      </div>
    </div>
  );
}
