"use client";
import { useState } from "react";
import { useMusicContext } from "@/components/providers/MusicProvider";
import { X, Loader2 } from "lucide-react";

interface Props {
  open: boolean;
  onClose: () => void;
}

export default function ImportPlaylistDialog({ open, onClose }: Props) {
  const [url, setUrl] = useState("");
  const [importing, setImporting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { importPlaylist } = useMusicContext();

  if (!open) return null;

  async function handleImport() {
    setImporting(true);
    setError(null);
    try {
      await importPlaylist(url);
      setUrl("");
      onClose();
    } catch (e: any) {
      setError(e.message);
    } finally {
      setImporting(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white dark:bg-zinc-900 rounded-xl shadow-xl p-6 w-full max-w-md">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">Import Playlist</h2>
          <button onClick={onClose} className="text-zinc-400 hover:text-zinc-600"><X className="w-5 h-5" /></button>
        </div>
        <p className="text-sm text-zinc-500 mb-3">Paste an Apple Music playlist URL</p>
        <input
          type="text"
          placeholder="https://music.apple.com/us/playlist/..."
          value={url}
          onChange={(e) => setUrl(e.target.value)}
          className="w-full px-3 py-2 rounded-lg border border-zinc-200 dark:border-zinc-700 bg-white dark:bg-zinc-800 text-sm text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-zinc-500 mb-3"
          onKeyDown={(e) => e.key === "Enter" && !importing && url && handleImport()}
        />
        {error && <p className="text-sm text-red-500 mb-3">{error}</p>}
        <div className="flex justify-end gap-2">
          <button onClick={onClose} className="px-4 py-2 text-sm text-zinc-500 hover:text-zinc-700">Cancel</button>
          <button
            onClick={handleImport}
            disabled={!url || importing}
            className="px-4 py-2 text-sm font-medium bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900 rounded-lg disabled:opacity-50"
          >
            {importing ? <Loader2 className="w-4 h-4 animate-spin" /> : "Import"}
          </button>
        </div>
      </div>
    </div>
  );
}
