import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import api from "../lib/api";
import { Tv } from "lucide-react";

export default function Shows() {
  const [shows, setShows] = useState([]);
  const [featured, setFeatured] = useState(null);
  const [continueEps, setContinueEps] = useState([]);
  const nav = useNavigate();

  useEffect(() => {
    (async () => {
      const [s, f, c] = await Promise.all([
        api.get("/shows"),
        api.get("/shows/featured").catch(() => ({ data: null })),
        api.get("/progress/episodes/continue").catch(() => ({ data: [] })),
      ]);
      setShows(s.data); setFeatured(f.data); setContinueEps(c.data);
    })();
  }, []);

  if (shows.length === 0) {
    return (
      <div className="min-h-screen bg-[#050505] pt-32 pb-24" data-testid="shows-empty-page">
        <div className="px-6 md:px-12 max-w-[1500px] mx-auto text-center">
          <Tv size={48} strokeWidth={1.5} className="mx-auto text-[#8A8A8A]" />
          <h1 className="mt-6 font-display text-4xl font-bold tracking-tight text-white">No TV shows yet</h1>
          <p className="text-[#8A8A8A] mt-3 max-w-md mx-auto">Configure Sonarr in Settings and import your library.</p>
          <a href="/admin/sonarr" className="inline-block mt-6 bg-[#D9381E] hover:bg-[#ED4B32] text-white px-6 py-3 text-sm uppercase tracking-[0.2em]" data-testid="go-to-sonarr-import">
            Sonarr Import
          </a>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#050505] pt-32 pb-24" data-testid="shows-page">
      <div className="px-6 md:px-12 max-w-[1500px] mx-auto">
        <span className="text-xs uppercase tracking-[0.3em] text-[#D9381E]">Series</span>
        <h1 className="font-display text-5xl md:text-6xl font-black tracking-tighter text-white mt-3">Your Series</h1>

        {continueEps.length > 0 && (
          <div className="mt-12">
            <h2 className="font-display text-2xl font-bold tracking-tight text-white mb-4">Resume</h2>
            <div className="flex gap-4 overflow-x-auto no-scrollbar pb-4">
              {continueEps.map(({ episode, show, progress }) => {
                const pct = progress.duration_seconds ? Math.min(100, (progress.position_seconds / progress.duration_seconds) * 100) : 0;
                return (
                  <button key={episode.id} onClick={() => nav(`/watch/episode/${episode.id}`)}
                    className="relative shrink-0 w-[260px] group focus:outline-none" data-testid={`continue-ep-${episode.id}`}>
                    <div className="aspect-video overflow-hidden bg-[#0F0F0F] transition-transform duration-300 group-hover:scale-105">
                      <img src={show.backdrop_url || show.poster_url} alt="" className="w-full h-full object-cover" />
                    </div>
                    <div className="absolute bottom-0 left-0 right-0 h-[3px] bg-white/10">
                      <div className="h-full bg-[#D9381E]" style={{ width: `${pct}%` }} />
                    </div>
                    <p className="mt-2 text-white text-sm truncate">{show.title}</p>
                    <p className="text-[10px] uppercase tracking-[0.2em] text-[#8A8A8A]">S{episode.season_number}·E{episode.episode_number} · {episode.title}</p>
                  </button>
                );
              })}
            </div>
          </div>
        )}

        <div className="mt-16 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4 md:gap-6">
          {shows.map((s) => (
            <button key={s.id} onClick={() => nav(`/show/${s.id}`)}
              className="group shrink-0 aspect-[2/3] overflow-hidden bg-[#0F0F0F] transition-transform duration-300 hover:scale-105 focus:outline-none focus:ring-2 focus:ring-[#D9381E]"
              data-testid={`show-card-${s.id}`}>
              <img src={s.poster_url || s.backdrop_url} alt={s.title} loading="lazy" className="w-full h-full object-cover" />
              <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black to-transparent p-3 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                <p className="text-white text-sm truncate">{s.title}</p>
                <p className="text-[10px] uppercase tracking-[0.2em] text-[#8A8A8A]">{s.season_count} seasons · {s.episode_count} eps</p>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
