"use client";
import { useState } from "react";
import { useMusicContext } from "@/components/providers/MusicProvider";
import SongRow from "./SongRow";
import ImportPlaylistDialog from "./ImportPlaylistDialog";
import { ArrowLeft, Check, Download, Loader2, Plus, Trash2 } from "lucide-react";

export default function PlaylistsView() {
  const { playlists, selectedPlaylist, fetchPlaylistDetail, setSelectedPlaylist, queueSongs, deletePlaylist, createPlaylist } = useMusicContext();
  const [importOpen, setImportOpen] = useState(false);
  const [captureLoading, setCaptureLoading] = useState(false);
  const [captureDone, setCaptureDone] = useState(false);
  const [capturingSongs, setCapturingSongs] = useState<Set<string>>(new Set());

  if (selectedPlaylist) {
    const pending = selectedPlaylist.songs?.filter((s) => s.status === "pending") || [];
    return (
      <div className="p-4">
        <button
          onClick={() => setSelectedPlaylist(null)}
          className="flex items-center gap-1 text-sm text-zinc-500 hover:text-zinc-700 mb-4"
        >
          <ArrowLeft className="w-4 h-4" /> All Playlists
        </button>
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100">{selectedPlaylist.name}</h2>
            <p className="text-sm text-zinc-500">
              {selectedPlaylist.source === "apple_music" ? "Apple Music" : "Custom"} — {selectedPlaylist.songs?.length || 0} songs
            </p>
          </div>
          {pending.length > 0 && (
            <button
              disabled={captureLoading || captureDone}
              onClick={async () => {
                setCaptureLoading(true);
                try {
                  await queueSongs(pending.map((s) => s.isrc), selectedPlaylist.id);
                  setCaptureDone(true);
                  setTimeout(() => setCaptureDone(false), 3000);
                } finally {
                  setCaptureLoading(false);
                }
              }}
              className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
                captureDone
                  ? "bg-green-600 text-white"
                  : captureLoading
                  ? "bg-zinc-600 text-white cursor-wait"
                  : "bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900"
              }`}
            >
              {captureDone ? (
                <><Check className="w-4 h-4" /> Queued!</>
              ) : captureLoading ? (
                <><Loader2 className="w-4 h-4 animate-spin" /> Queuing...</>
              ) : (
                <><Download className="w-4 h-4" /> Capture {pending.length} Missing</>
              )}
            </button>
          )}
        </div>
        <div className="space-y-0.5">
          {selectedPlaylist.songs?.map((song, i) => (
            <SongRow
              key={song.isrc}
              song={song}
              position={i + 1}
              action={
                song.status === "pending" ? (
                  <button
                    disabled={capturingSongs.has(song.isrc)}
                    onClick={async () => {
                      setCapturingSongs((prev) => new Set(prev).add(song.isrc));
                      try {
                        await queueSongs([song.isrc], selectedPlaylist.id);
                      } finally {
                        // Keep showing check for a moment
                        setTimeout(() => setCapturingSongs((prev) => {
                          const next = new Set(prev);
                          next.delete(song.isrc);
                          return next;
                        }), 2000);
                      }
                    }}
                    className={`p-1 transition-colors ${
                      capturingSongs.has(song.isrc)
                        ? "text-green-500"
                        : "text-zinc-400 hover:text-zinc-600"
                    }`}
                    title="Capture this song"
                  >
                    {capturingSongs.has(song.isrc) ? (
                      <Check className="w-4 h-4" />
                    ) : (
                      <Download className="w-4 h-4" />
                    )}
                  </button>
                ) : null
              }
            />
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="p-4">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">Playlists</h2>
        <div className="flex items-center gap-2">
          <button
            onClick={() => {
              const name = prompt("Playlist name:");
              if (name) createPlaylist(name);
            }}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium border border-zinc-200 dark:border-zinc-700 text-zinc-700 dark:text-zinc-300 rounded-lg hover:bg-zinc-50 dark:hover:bg-zinc-800"
          >
            <Plus className="w-4 h-4" /> New Playlist
          </button>
          <button
            onClick={() => setImportOpen(true)}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900 rounded-lg"
          >
            <Plus className="w-4 h-4" /> Import Playlist
          </button>
        </div>
      </div>
      <div className="space-y-2">
        {playlists.map((pl) => (
          <div
            key={pl.id}
            onClick={() => fetchPlaylistDetail(pl.id)}
            className="flex items-center justify-between p-4 rounded-lg border border-zinc-200 dark:border-zinc-800 hover:bg-zinc-50 dark:hover:bg-zinc-900 cursor-pointer group"
          >
            <div>
              <div className="font-medium text-zinc-900 dark:text-zinc-100">{pl.name}</div>
              <div className="text-xs text-zinc-500">
                {pl.source === "apple_music" ? "Apple Music" : "Custom"} — {pl.captured_songs}/{pl.total_songs} captured
              </div>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-24 h-2 bg-zinc-200 dark:bg-zinc-700 rounded-full overflow-hidden">
                <div
                  className="h-full bg-green-500 rounded-full"
                  style={{ width: `${pl.total_songs ? (pl.captured_songs / pl.total_songs) * 100 : 0}%` }}
                />
              </div>
              <button
                onClick={(e) => { e.stopPropagation(); deletePlaylist(pl.id); }}
                className="p-1 text-zinc-400 hover:text-red-500 opacity-0 group-hover:opacity-100"
              >
                <Trash2 className="w-4 h-4" />
              </button>
            </div>
          </div>
        ))}
        {playlists.length === 0 && (
          <div className="text-center text-zinc-400 py-12">No playlists yet. Import one from Apple Music.</div>
        )}
      </div>
      <ImportPlaylistDialog open={importOpen} onClose={() => setImportOpen(false)} />
    </div>
  );
}
