"use client";

import { useState } from "react";
import { X, ListPlus, Loader2, Lock, Globe } from "lucide-react";
import { playlistService } from "@/services/playlistService";

interface Props {
  channelId: string;
  onClose: () => void;
  onCreated: () => void;
}

export function CreatePlaylistModal({ channelId, onClose, onCreated }: Props) {
  const [title, setTitle] = useState("");
  const [playlistType, setPlaylistType] = useState<1 | 2>(1); // 1=public, 2=private
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const handleCreate = async () => {
    if (!title.trim() || loading) return;
    setLoading(true);
    setError("");
    try {
      const res = await playlistService.create({
        channelId,
        playlistType,
        title: title.trim(),
      });
      if (res.status === 200 || res.status === 1) {
        onCreated();
        onClose();
      } else {
        setError(res.message || "Failed to create playlist");
      }
    } catch {
      setError("Something went wrong. Please try again.");
    }
    setLoading(false);
  };

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 z-[200]"
        style={{ background: "rgba(0,0,0,0.8)", backdropFilter: "blur(12px)", animation: "cpm-fade 0.2s ease both" }}
        onClick={onClose}
      />

      {/* Sheet */}
      <div
        className="fixed z-[201] bottom-0 left-0 right-0 flex flex-col"
        style={{
          maxWidth: "560px",
          margin: "0 auto",
          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: "cpm-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-4 shrink-0"
          style={{ borderBottom: "1px solid var(--border)" }}
        >
          <div
            className="w-8 h-8 rounded-full flex items-center justify-center shrink-0"
            style={{ background: "rgba(var(--accent-rgb),0.15)" }}
          >
            <ListPlus size={16} color="var(--accent)" strokeWidth={2} />
          </div>
          <span className="flex-1 text-sm font-bold" style={{ color: "var(--text-primary)" }}>New Playlist</span>
          <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>

        {/* Body */}
        <div className="px-5 py-6 flex flex-col gap-5">
          {/* Title input */}
          <div className="flex flex-col gap-2">
            <label className="text-xs font-semibold" style={{ color: "var(--text-muted)" }}>
              Playlist Name
            </label>
            <input
              className="w-full bg-transparent text-sm font-semibold outline-none px-0 py-2"
              style={{
                color: "var(--text-primary)",
                borderBottom: "1.5px solid rgba(var(--accent-rgb),0.4)",
                caretColor: "var(--accent)",
              }}
              placeholder="Enter playlist name…"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") handleCreate(); }}
              autoFocus
              maxLength={80}
            />
            <div className="flex justify-end">
              <span className="text-[10px]" style={{ color: title.length > 70 ? "#f43f5e" : "#444" }}>
                {title.length}/80
              </span>
            </div>
          </div>

          {/* Visibility toggle */}
          <div className="flex flex-col gap-2">
            <label className="text-xs font-semibold" style={{ color: "var(--text-muted)" }}>
              Visibility
            </label>
            <div className="flex gap-2">
              {([
                { value: 1, label: "Public", icon: Globe },
                { value: 2, label: "Private", icon: Lock },
              ] as const).map(({ value, label, icon: Icon }) => (
                <button
                  key={value}
                  onClick={() => setPlaylistType(value)}
                  className="flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-semibold transition-all duration-150 active:scale-95"
                  style={{
                    background: playlistType === value ? "rgba(var(--accent-rgb),0.15)" : "var(--border-soft)",
                    border: playlistType === value ? "1px solid rgba(var(--accent-rgb),0.4)" : "1px solid var(--border)",
                    color: playlistType === value ? "var(--accent)" : "#666",
                  }}
                >
                  <Icon size={12} strokeWidth={2} />
                  {label}
                </button>
              ))}
            </div>
          </div>

          {error && (
            <p className="text-xs text-red-400 font-medium">{error}</p>
          )}

          {/* Actions */}
          <div className="flex gap-3 mt-1 pb-safe">
            <button
              onClick={onClose}
              className="flex-1 py-3 rounded-xl text-sm font-semibold transition-all duration-150 active:scale-95"
              style={{
                background: "var(--btn-ghost)",
                color: "#888",
                border: "1px solid var(--border)",
              }}
            >
              Cancel
            </button>
            <button
              onClick={handleCreate}
              disabled={!title.trim() || loading}
              className="flex-1 py-3 rounded-xl text-sm font-bold transition-all duration-150 active:scale-95 flex items-center justify-center gap-2"
              style={{
                background: !title.trim() || loading
                  ? "rgba(var(--accent-rgb),0.2)"
                  : "linear-gradient(135deg, var(--accent), var(--accent-light))",
                color: !title.trim() || loading ? "rgba(255,255,255,0.3)" : "#fff",
                boxShadow: !title.trim() || loading ? "none" : "0 4px 16px rgba(var(--accent-rgb),0.35)",
              }}
            >
              {loading ? <Loader2 size={15} className="animate-spin" /> : null}
              {loading ? "Creating…" : "Create Playlist"}
            </button>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes cpm-fade { from{opacity:0} to{opacity:1} }
        @keyframes cpm-up   { from{transform:translateY(100%)} to{transform:translateY(0)} }
      `}</style>
    </>
  );
}
