"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import {
  X, Play, Loader2, Pencil, Trash2, Check, ListPlus,
} from "lucide-react";
import { playlistService, type Playlist, type PlaylistContentItem } from "@/services/playlistService";
import { DeleteConfirmModal } from "@/components/shared/DeleteConfirmModal";

interface Props {
  playlist: Playlist;
  onClose: () => void;
  onDeleted: (id: string) => void;
  onEdited: (id: string, title: string) => void;
}

export function PlaylistDetailModal({ playlist, onClose, onDeleted, onEdited }: Props) {
  const router = useRouter();
  const [items, setItems] = useState<PlaylistContentItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [isEditing, setIsEditing] = useState(false);
  const [editTitle, setEditTitle] = useState(playlist.title);
  const [saving, setSaving] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  useEffect(() => {
    document.body.style.overflow = "hidden";
    playlistService.getPlaylistContent(playlist.id, playlist.playlistType)
      .then(setItems)
      .catch(() => {})
      .finally(() => setLoading(false));
    return () => { document.body.style.overflow = ""; };
  }, [playlist.id, playlist.playlistType]);

  const handleSaveEdit = async () => {
    if (!editTitle.trim() || saving) return;
    setSaving(true);
    try {
      await playlistService.editPlaylist({
        playlistId: playlist.id,
        title: editTitle.trim(),
        playlistType: playlist.playlistType,
      });
      onEdited(playlist.id, editTitle.trim());
      setIsEditing(false);
    } catch { /* */ }
    setSaving(false);
  };

  const handleDelete = async () => {
    await playlistService.deletePlaylist(playlist.id);
    onDeleted(playlist.id);
    onClose();
  };

  const goToContent = (item: PlaylistContentItem) => {
    if (item.contentType === 3) router.push(`/reel/${item.id}`);
    else if (item.contentType === 4) router.push(`/content/4/${item.id}`);
    else router.push(`/video/${item.id}`);
  };

  return (
    <>
      <div className="fixed inset-0 z-[200]" style={{ background: "rgba(0,0,0,0.8)", backdropFilter: "blur(12px)", animation: "pdm-fade 0.2s ease both" }} onClick={onClose} />
      <div className="fixed z-[201] bottom-0 left-0 right-0 flex flex-col" style={{ maxWidth: "680px", margin: "0 auto", maxHeight: "88vh", background: "var(--sheet-bg)", borderRadius: "22px 22px 0 0", border: "1px solid var(--sheet-border)", borderBottom: "none", boxShadow: "0 -24px 64px rgba(0,0,0,0.8)", animation: "pdm-up 0.38s cubic-bezier(0.32,1.2,0.56,1) both" }}>

        {/* Drag handle */}
        <div className="flex justify-center pt-3"><div className="w-9 h-[3px] rounded-full" style={{ background: "var(--sheet-handle)" }} /></div>

        {/* Header */}
        <div className="flex items-center gap-3 px-5 py-3 shrink-0" style={{ borderBottom: "1px solid var(--border)" }}>
          <ListPlus size={16} color="var(--accent)" strokeWidth={2} />
          {isEditing ? (
            <div className="flex-1 flex items-center gap-2">
              <input
                className="flex-1 bg-transparent text-sm font-bold outline-none"
                style={{ color: "var(--text-primary)", borderBottom: "1.5px solid rgba(var(--accent-rgb),0.5)" }}
                value={editTitle}
                onChange={(e) => setEditTitle(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") handleSaveEdit(); if (e.key === "Escape") setIsEditing(false); }}
                autoFocus
              />
              <button onClick={handleSaveEdit} disabled={saving} className="w-7 h-7 rounded-full flex items-center justify-center active:scale-90" style={{ background: "rgba(var(--accent-rgb),0.15)" }}>
                {saving ? <Loader2 size={12} className="animate-spin" color="var(--accent)" /> : <Check size={12} color="var(--accent)" strokeWidth={2.5} />}
              </button>
            </div>
          ) : (
            <span className="flex-1 text-sm font-bold truncate" style={{ color: "var(--text-primary)" }}>{playlist.title}</span>
          )}

          <div className="flex items-center gap-1.5 shrink-0">
            {!isEditing && (
              <button onClick={() => setIsEditing(true)} className="w-7 h-7 rounded-full flex items-center justify-center transition-all hover:bg-white/10 active:scale-90" style={{ background: "var(--btn-ghost-hover)" }}>
                <Pencil size={12} color="#aaa" strokeWidth={2} />
              </button>
            )}
            <button onClick={() => setShowDeleteConfirm(true)} className="w-7 h-7 rounded-full flex items-center justify-center transition-all hover:bg-red-500/20 active:scale-90" style={{ background: "var(--btn-ghost-hover)" }}>
              <Trash2 size={12} color="#f43f5e" strokeWidth={2} />
            </button>
            <button onClick={onClose} className="w-7 h-7 rounded-full flex items-center justify-center" style={{ background: "var(--btn-ghost-hover)" }}>
              <X size={13} color="#888" />
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto pb-8">
          {loading ? (
            <div className="flex justify-center py-12"><Loader2 size={22} className="animate-spin" color="rgba(var(--accent-rgb),0.6)" /></div>
          ) : items.length === 0 ? (
            <div className="flex flex-col items-center gap-3 py-14">
              <ListPlus size={28} color="#333" strokeWidth={1.2} />
              <p className="text-xs" style={{ color: "var(--text-muted)" }}>This playlist is empty</p>
            </div>
          ) : (
            items.map((item, i) => (
              <button
                key={item.id}
                onClick={() => goToContent(item)}
                className="flex items-center gap-3 px-5 py-3 w-full text-left transition-all hover:bg-white/3 active:scale-[0.99]"
                style={{ animation: `pdm-item 0.25s ease both ${i * 45}ms`, borderBottom: "1px solid var(--border)" }}
              >
                <div className="relative w-14 h-14 rounded-xl overflow-hidden shrink-0" style={{ background: "var(--deep)" }}>
                  {item.thumbnail && <Image src={item.thumbnail} alt={item.title} fill className="object-cover" unoptimized sizes="56px" />}
                  <div className="absolute inset-0 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity" style={{ background: "rgba(0,0,0,0.4)" }}>
                    <Play size={16} fill="white" strokeWidth={0} />
                  </div>
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-[13px] font-semibold truncate" style={{ color: "var(--text-primary)" }}>{item.title}</p>
                  <p className="text-[10px] mt-0.5 truncate" style={{ color: "var(--text-muted)" }}>{item.channelName}</p>
                </div>
                {item.duration && (
                  <span className="text-[10px] tabular-nums shrink-0" style={{ color: "var(--text-muted)" }}>{item.duration}</span>
                )}
              </button>
            ))
          )}
        </div>
      </div>

      {showDeleteConfirm && (
        <DeleteConfirmModal
          title="Delete Playlist"
          description={`"${playlist.title}" and all its contents will be removed permanently.`}
          confirmLabel="Delete Playlist"
          onConfirm={handleDelete}
          onCancel={() => setShowDeleteConfirm(false)}
        />
      )}

      <style>{`
        @keyframes pdm-fade { from{opacity:0} to{opacity:1} }
        @keyframes pdm-up   { from{transform:translateY(100%)} to{transform:translateY(0)} }
        @keyframes pdm-item { from{opacity:0;transform:translateX(-6px)} to{opacity:1;transform:none} }
      `}</style>
    </>
  );
}
