"use client";

import { useState, useRef, useEffect } from "react";
import { useApi } from "@/lib/api";
import { Spinner, EmptyState } from "../skeleton";
import { cn } from "@/lib/utils";
import { toPersianDigits, formatViews } from "@/lib/poster";
import {
  Music, Play, Pause, SkipForward, SkipBack, Shuffle, Repeat, Volume2, VolumeX,
  Heart, ListMusic, Disc3, Mic2, BadgeCheck, Search,
} from "lucide-react";

interface Track {
  id: string; slug: string; title: string; audioUrl: string; duration: number;
  plays: number; genre?: string | null; isExplicit: boolean;
  coverColors: [string, string];
  artist: { id: string; name: string; persianName: string };
  album?: { id: string; title: string } | null;
}
interface Artist { id: string; slug: string; name: string; persianName: string; photo?: string | null; bio?: string | null; verified: boolean; monthlyListeners: number; gradient: [string, string]; albumsCount: number; tracksCount: number; }
interface Album { id: string; slug: string; title: string; year: number; genre?: string | null; coverColors: [string, string]; artist: { id: string; name: string; persianName: string }; tracksCount: number; }
interface MusicData { artists: Artist[]; albums: Album[]; tracks: Track[]; }

function fmtTime(s: number) {
  if (!isFinite(s) || s < 0) s = 0;
  const m = Math.floor(s / 60);
  const sec = Math.floor(s % 60);
  return `${toPersianDigits(m)}:${toPersianDigits(String(sec).padStart(2, "0"))}`;
}

export function MusicView() {
  const { data, loading } = useApi<MusicData>("/api/music");
  const [queue, setQueue] = useState<Track[]>([]);
  const [idx, setIdx] = useState(0);
  const [playing, setPlaying] = useState(false);
  const [q, setQ] = useState("");
  const audioRef = useRef<HTMLAudioElement>(null);
  const [current, setCurrent] = useState(0);
  const [duration, setDuration] = useState(0);
  const [volume, setVolume] = useState(0.8);
  const [muted, setMuted] = useState(false);
  const [shuffle, setShuffle] = useState(false);
  const [repeat, setRepeat] = useState(false);
  const [liked, setLiked] = useState<Set<string>>(new Set());

  const track = queue[idx] ?? null;

  const playTrack = (t: Track, list?: Track[]) => {
    const base = list ?? data?.tracks ?? [];
    const start = base.findIndex((x) => x.id === t.id);
    setQueue(start >= 0 ? base : [t, ...base]);
    setIdx(Math.max(0, start));
    setPlaying(true);
  };

  useEffect(() => {
    const a = audioRef.current;
    if (!a || !track) return;
    if (a.src !== track.audioUrl) {
      a.src = track.audioUrl;
      a.load();
    }
    if (playing) a.play().catch(() => setPlaying(false));
    else a.pause();
  }, [track, playing]);

  useEffect(() => {
    const a = audioRef.current;
    if (!a) return;
    a.volume = muted ? 0 : volume;
  }, [volume, muted]);

  const next = () => {
    if (!queue.length) return;
    if (shuffle) setIdx(Math.floor(Math.random() * queue.length));
    else setIdx((i) => (i + 1) % queue.length);
    setPlaying(true);
  };
  const prev = () => { if (queue.length > 1) setIdx((i) => (i - 1 + queue.length) % queue.length); setPlaying(true); };

  const onEnded = () => { if (repeat) { audioRef.current?.play(); } else next(); };

  const toggleLike = (id: string) => setLiked((s) => { const n = new Set(s); if (n.has(id)) n.delete(id); else n.add(id); return n; });

  const filteredTracks = (data?.tracks ?? []).filter((t) => !q || t.title.includes(q) || t.artist.persianName.includes(q));

  if (loading || !data) return <div className="h-[60vh] flex items-center justify-center"><Spinner /></div>;

  return (
    <div className="px-4 md:px-8 py-6 pb-32">
      <h1 className="text-2xl md:text-3xl font-black flex items-center gap-3 mb-6">
        <span className="h-8 w-1.5 rounded-full bg-accent" />
        <Music className="h-7 w-7 text-accent" /> موزیک
      </h1>

      {/* Featured artists */}
      <section className="mb-8">
        <h2 className="text-lg font-bold mb-3 flex items-center gap-2"><Mic2 className="h-5 w-5 text-accent" /> هنرمندان برتر</h2>
        <div className="flex gap-3 overflow-x-auto hide-scrollbar pb-2">
          {data.artists.map((a) => (
            <button key={a.id} className="shrink-0 w-28 text-center group">
              <div className="relative aspect-square rounded-full overflow-hidden mx-auto mb-2 group-hover:scale-105 transition" style={{ background: `linear-gradient(135deg, ${a.gradient[0]}, ${a.gradient[1]})` }}>
                <div className="absolute inset-0 flex items-center justify-center text-3xl font-black text-white/80">{a.persianName.charAt(0)}</div>
                {a.verified && <BadgeCheck className="absolute bottom-1 left-1 h-5 w-5 text-accent fill-card" />}
              </div>
              <div className="text-sm font-bold truncate">{a.persianName}</div>
              <div className="text-[10px] text-muted-foreground">{formatViews(a.monthlyListeners)} شنونده</div>
            </button>
          ))}
        </div>
      </section>

      {/* Albums */}
      <section className="mb-8">
        <h2 className="text-lg font-bold mb-3 flex items-center gap-2"><Disc3 className="h-5 w-5 text-accent" /> آلبوم‌ها</h2>
        <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 gap-3">
          {data.albums.map((al) => (
            <button key={al.id} className="text-right group" onClick={() => {
              const albumTracks = data.tracks.filter((t) => t.album?.id === al.id);
              if (albumTracks[0]) playTrack(albumTracks[0], albumTracks);
            }}>
              <div className="relative aspect-square rounded-xl overflow-hidden mb-2 group-hover:scale-[1.03] transition" style={{ background: `linear-gradient(135deg, ${al.coverColors[0]}, ${al.coverColors[1]})` }}>
                <div className="absolute inset-0 flex items-center justify-center text-white/80"><Disc3 className="h-10 w-10" /></div>
                <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition flex items-center justify-center">
                  <Play className="h-10 w-10 text-white fill-white" />
                </div>
              </div>
              <div className="text-sm font-bold truncate">{al.title}</div>
              <div className="text-[10px] text-muted-foreground truncate">{al.artist.persianName}</div>
            </button>
          ))}
        </div>
      </section>

      {/* Search + track list */}
      <section>
        <div className="flex items-center justify-between mb-3 flex-wrap gap-2">
          <h2 className="text-lg font-bold flex items-center gap-2"><ListMusic className="h-5 w-5 text-accent" /> آهنگ‌های محبوب</h2>
          <div className="flex items-center glass rounded-full px-3 py-1.5">
            <Search className="h-4 w-4 text-muted-foreground ml-2" />
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="جستجوی آهنگ یا هنرمند..." className="bg-transparent w-40 md:w-56 px-2 text-sm outline-none placeholder:text-muted-foreground" />
          </div>
        </div>
        {filteredTracks.length === 0 ? (
          <EmptyState icon={Music} title="آهنگی یافت نشد" />
        ) : (
          <div className="space-y-1">
            {filteredTracks.map((t, i) => (
              <div
                key={t.id}
                className={cn("flex items-center gap-3 rounded-lg p-2 hover:bg-white/5 transition group cursor-pointer", track?.id === t.id && "bg-primary/10")}
                onClick={() => playTrack(t, filteredTracks)}
              >
                <div className="shrink-0 w-6 text-center text-xs text-muted-foreground">{track?.id === t.id && playing ? <Volume2 className="h-4 w-4 text-accent mx-auto" /> : toPersianDigits(i + 1)}</div>
                <div className="shrink-0 relative h-10 w-10 rounded-md overflow-hidden" style={{ background: `linear-gradient(135deg, ${t.coverColors[0]}, ${t.coverColors[1]})` }}>
                  <div className="absolute inset-0 flex items-center justify-center">
                    {track?.id === t.id && playing ? <Pause className="h-4 w-4 text-white fill-white" /> : <Play className="h-4 w-4 text-white fill-white opacity-0 group-hover:opacity-100" />}
                  </div>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium truncate">{t.title} {t.isExplicit && <span className="text-[9px] border border-white/30 rounded px-1 ml-1">E</span>}</div>
                  <div className="text-xs text-muted-foreground truncate">{t.artist.persianName}</div>
                </div>
                <div className="hidden sm:block text-xs text-muted-foreground">{formatViews(t.plays)}</div>
                <button onClick={(e) => { e.stopPropagation(); toggleLike(t.id); }} className="shrink-0">
                  <Heart className={cn("h-4 w-4 transition", liked.has(t.id) ? "fill-secondary text-secondary" : "text-muted-foreground hover:text-white")} />
                </button>
                <div className="hidden sm:block text-xs text-muted-foreground tabular-nums">{fmtTime(t.duration)}</div>
              </div>
            ))}
          </div>
        )}
      </section>

      {/* Sticky player */}
      {track && (
        <div className="fixed bottom-16 md:bottom-0 inset-x-0 z-40 glass-strong border-t border-border">
          <div className="px-3 md:px-6 py-2.5 flex items-center gap-3">
            <div className="shrink-0 relative h-11 w-11 rounded-md overflow-hidden" style={{ background: `linear-gradient(135deg, ${track.coverColors[0]}, ${track.coverColors[1]})` }}>
              <div className="absolute inset-0 flex items-center justify-center text-white/80"><Music className="h-5 w-5" /></div>
            </div>
            <div className="hidden sm:block min-w-0 w-40">
              <div className="text-sm font-bold truncate">{track.title}</div>
              <div className="text-xs text-muted-foreground truncate">{track.artist.persianName}</div>
            </div>
            <div className="flex items-center gap-1">
              <button onClick={prev} className="h-9 w-9 flex items-center justify-center rounded-full hover:bg-white/10 transition" aria-label="قبلی"><SkipBack className="h-4 w-4" /></button>
              <button onClick={() => setPlaying(!playing)} className="h-10 w-10 flex items-center justify-center rounded-full bg-primary text-white hover:bg-primary/90 transition" aria-label="پخش/توقف">
                {playing ? <Pause className="h-5 w-5 fill-white" /> : <Play className="h-5 w-5 fill-white ml-0.5" />}
              </button>
              <button onClick={next} className="h-9 w-9 flex items-center justify-center rounded-full hover:bg-white/10 transition" aria-label="بعدی"><SkipForward className="h-4 w-4" /></button>
            </div>
            <div className="flex-1 flex items-center gap-2 max-w-xl">
              <span className="text-[10px] text-muted-foreground tabular-nums hidden md:inline">{fmtTime(current)}</span>
              <input type="range" min={0} max={duration || 0} value={current} onChange={(e) => { const v = Number(e.target.value); if (audioRef.current) { audioRef.current.currentTime = v; setCurrent(v); } }} className="peep-range flex-1" />
              <span className="text-[10px] text-muted-foreground tabular-nums hidden md:inline">{fmtTime(duration)}</span>
            </div>
            <div className="hidden md:flex items-center gap-1">
              <button onClick={() => setShuffle(!shuffle)} className={cn("h-9 w-9 flex items-center justify-center rounded-full hover:bg-white/10 transition", shuffle && "text-accent")} aria-label="بُر زدن"><Shuffle className="h-4 w-4" /></button>
              <button onClick={() => setRepeat(!repeat)} className={cn("h-9 w-9 flex items-center justify-center rounded-full hover:bg-white/10 transition", repeat && "text-accent")} aria-label="تکرار"><Repeat className="h-4 w-4" /></button>
              <button onClick={() => setLiked((s) => { const n = new Set(s); if (n.has(track.id)) n.delete(track.id); else n.add(track.id); return n; })} className="h-9 w-9 flex items-center justify-center rounded-full hover:bg-white/10 transition" aria-label="علاقه‌مندی">
                <Heart className={cn("h-4 w-4", liked.has(track.id) ? "fill-secondary text-secondary" : "text-muted-foreground")} />
              </button>
              <div className="flex items-center gap-1">
                <button onClick={() => setMuted(!muted)} className="h-9 w-9 flex items-center justify-center rounded-full hover:bg-white/10 transition" aria-label="بی‌صدا">
                  {muted || volume === 0 ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
                </button>
                <input type="range" min={0} max={1} step={0.05} value={muted ? 0 : volume} onChange={(e) => { setVolume(Number(e.target.value)); setMuted(false); }} className="peep-range w-20" />
              </div>
            </div>
          </div>
        </div>
      )}

      <audio ref={audioRef} onTimeUpdate={(e) => setCurrent(e.currentTarget.currentTime)} onLoadedMetadata={(e) => setDuration(e.currentTarget.duration)} onEnded={onEnded} />
    </div>
  );
}
