import { useState, useEffect, useCallback, useMemo } from "react";
import { useParams, Link, useNavigate } from "react-router-dom";
import toast from "react-hot-toast";
import {
  GripVertical,
  Music,
  Calendar,
  User,
  ListMusic,
  Plus,
  Trash2,
  X,
  Search,
} from "lucide-react";
import { motion, AnimatePresence, Reorder } from "framer-motion";
import api from "@utils/api";
import { useTheme } from "@context/ThemeContext";
import {
  useLists,
  useProfiles,
  useSongs,
  useListSongs,
  useDataMutations,
} from "@hooks/useDataFetch";

// Helper function to extract just the primary key chord
const getKeyChord = (chordString) => {
  if (!chordString) return null;
  // Take first chord before comma, slash, or space
  return chordString.trim().split(/[,\/\s]/)[0];
};

export default function WorshipListsPage() {
  const { listId } = useParams();
  const navigate = useNavigate();
  const { isDark } = useTheme();

  // Use cached data from global store
  const { lists, loading: listsLoading, refetch: refetchLists } = useLists();
  const { profiles } = useProfiles();
  const { songs: allSongs } = useSongs();
  const { removeListFromCache, addListToCache, invalidateListDetail } =
    useDataMutations();

  const [selectedList, setSelectedList] = useState(null);
  const [listSongs, setListSongs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isReordering, setIsReordering] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editSearchQuery, setEditSearchQuery] = useState("");

  // New list modal state
  const [showNewListModal, setShowNewListModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [newListDate, setNewListDate] = useState("");
  const [newListLeader, setNewListLeader] = useState("");
  const [newListNotes, setNewListNotes] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedSongs, setSelectedSongs] = useState([]);

  // Local search on cached songs (no API call)
  const searchResults = useMemo(() => {
    if (!searchQuery.trim()) return [];
    const query = searchQuery.toLowerCase();
    return allSongs
      .filter(
        (song) =>
          song.title?.toLowerCase().includes(query) ||
          song.artist?.toLowerCase().includes(query) ||
          song.singer?.toLowerCase().includes(query),
      )
      .slice(0, 20);
  }, [searchQuery, allSongs]);

  // Search results for editing existing list
  const editSearchResults = useMemo(() => {
    if (!editSearchQuery.trim()) return [];
    const query = editSearchQuery.toLowerCase();
    return allSongs
      .filter(
        (song) =>
          (song.title?.toLowerCase().includes(query) ||
            song.artist?.toLowerCase().includes(query) ||
            song.singer?.toLowerCase().includes(query)) &&
          !listSongs.find((ls) => ls.id === song.id), // Exclude already added songs
      )
      .slice(0, 10);
  }, [editSearchQuery, allSongs, listSongs]);

  // Theme-aware classes
  const textPrimary = isDark ? "text-white" : "text-gray-900";
  const textSecondary = isDark ? "text-white/70" : "text-gray-600";
  const textMuted = isDark ? "text-white/50" : "text-gray-500";
  const bgCard = isDark
    ? "bg-white/10 border-white/20"
    : "bg-white border-gray-200 shadow-sm";
  const bgCardHover = isDark ? "hover:bg-white/15" : "hover:bg-gray-50";
  const bgSongItem = isDark ? "bg-white/5" : "bg-gray-50";

  // Update loading state based on cached data
  useEffect(() => {
    if (!listsLoading) {
      setLoading(false);
    }
  }, [listsLoading]);

  const handleSelectList = async (list) => {
    setSelectedList(list);
    try {
      const response = await api.get(`/lists/${list.id}`);
      if (response.data.success) {
        setListSongs(response.data.songs || []);
      }
    } catch (err) {
      setListSongs([]);
      toast.error("Failed to load list songs");
    }
  };

  // Handle song reordering
  const handleReorder = useCallback((newOrder) => {
    setListSongs(newOrder);
  }, []);

  // Save reordered songs to server
  const saveReorder = async () => {
    if (!selectedList) return;
    try {
      const songs = listSongs.map((song) => song.id);
      const res = await api.put(`/lists/${selectedList.id}/reorder`, { songs });
      if (res.data.success) {
        setIsReordering(false);
        invalidateListDetail(selectedList.id); // Refresh cache
        toast.success("Song order saved!");
      }
    } catch (err) {
      toast.error(
        "Failed to save order: " + (err.response?.data?.message || err.message),
      );
    }
  };

  // Add song to list (local state only - saved on "Save Changes")
  const handleAddSongToList = (song) => {
    if (!selectedList || listSongs.find((s) => s.id === song.id)) {
      toast.error("Song already in list");
      return;
    }
    setListSongs([...listSongs, song]);
    setEditSearchQuery("");
    toast.success(`Added "${song.title}" to list`);
  };

  // Remove song from list (local state only - saved on "Save Changes")
  const handleRemoveSongFromList = (songId) => {
    if (!selectedList) return;
    const song = listSongs.find((s) => s.id === songId);
    setListSongs(listSongs.filter((s) => s.id !== songId));
    toast.success(`Removed "${song?.title || "song"}" from list`);
  };

  // Save all edits to server (updates the entire list at once)
  const handleSaveEdits = async () => {
    if (!selectedList) return;

    // Check if user is logged in
    const token = localStorage.getItem("authToken");
    if (!token) {
      toast.error("You must be logged in to save changes");
      window.location.href = "/login";
      return;
    }

    try {
      const songIds = listSongs.map((song) => song.id);
      console.log("Saving worship list:", {
        listId: selectedList.id,
        songCount: songIds.length,
        hasToken: !!token,
      });

      const res = await api.put(`/lists/${selectedList.id}`, {
        date: selectedList.date,
        profile_id: selectedList.profile_id,
        notes: selectedList.notes,
        songs: songIds,
      });

      if (res.data.success) {
        setIsEditing(false);
        setEditSearchQuery("");
        invalidateListDetail(selectedList.id);
        refetchLists(); // Refresh the lists cache
        toast.success("Changes saved successfully!");
      } else {
        toast.error("Save failed: " + (res.data.message || "Unknown error"));
      }
    } catch (err) {
      console.error("Save error:", err);
      const errorMsg =
        err.response?.data?.message || err.message || "Unknown error";
      toast.error("Failed to save changes: " + errorMsg);

      // If 401, redirect to login
      if (err.response?.status === 401) {
        localStorage.removeItem("authToken");
        setTimeout(() => (window.location.href = "/login"), 1500);
      }
    }
  };

  // Cancel editing and revert changes
  const handleCancelEdit = async () => {
    if (!selectedList) return;
    setIsEditing(false);
    setEditSearchQuery("");
    // Reload the original songs
    try {
      const response = await api.get(`/lists/${selectedList.id}`);
      if (response.data.success) {
        setListSongs(response.data.songs || []);
      }
    } catch (err) {
      toast.error("Failed to reload list");
    }
  };

  // Auto-select list from URL
  useEffect(() => {
    if (listId && lists.length > 0) {
      const list = lists.find((l) => l.id === listId);
      if (list) {
        handleSelectList(list);
      }
    }
  }, [listId, lists]);

  // Delete worship list
  const handleDeleteList = async () => {
    if (!selectedList) return;
    setShowDeleteModal(false);

    try {
      const res = await api.delete(`/lists/${selectedList.id}`);
      if (res.data.success) {
        // Remove from cache and clear selection
        removeListFromCache(selectedList.id);
        setSelectedList(null);
        setListSongs([]);
        toast.success("Worship list deleted successfully!");
      }
    } catch (err) {
      console.error("Failed to delete list:", err);
      toast.error(
        "Failed to delete worship list: " +
          (err.response?.data?.message || err.message),
      );
    }
  };

  // Add song to new list
  const handleAddSongToNewList = (song) => {
    if (!selectedSongs.find((s) => s.id === song.id)) {
      setSelectedSongs([...selectedSongs, song]);
      setSearchQuery("");
    }
  };

  // Remove song from new list
  const handleRemoveSongFromNewList = (songId) => {
    setSelectedSongs(selectedSongs.filter((s) => s.id !== songId));
  };

  // Save new worship list
  const handleSaveNewList = async () => {
    if (!newListDate) {
      toast.error("Please select a date for this worship list");
      return;
    }

    try {
      const newList = {
        date: newListDate,
        profile_id: newListLeader || null,
        notes: newListNotes || "",
        songs: selectedSongs.map((s) => s.id),
      };

      const res = await api.post("/lists", newList);
      if (res.data.success) {
        // Add to lists and close modal
        setLists([...lists, res.data.list]);
        setShowNewListModal(false);
        setNewListDate("");
        setNewListLeader("");
        setNewListNotes("");
        setSelectedSongs([]);
        toast.success("Worship list created successfully!");

        // Select the newly created list
        if (res.data.list) {
          handleSelectList(res.data.list);
        }
      }
    } catch (err) {
      console.error("Failed to create list:", err);
      toast.error(
        "Failed to create worship list: " +
          (err.response?.data?.message || err.message),
      );
    }
  };

  // Reorder songs in new list modal
  const handleReorderNewListSongs = useCallback((newOrder) => {
    setSelectedSongs(newOrder);
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className={`text-xl ${textMuted}`}>Loading worship lists...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h1 className={`text-2xl sm:text-3xl font-bold ${textPrimary}`}>
            Worship Lists
          </h1>
          <p className={`text-sm sm:text-base ${textMuted}`}>
            {lists.length} service plans
          </p>
        </div>
        <button
          onClick={() => setShowNewListModal(true)}
          className="w-full sm:w-auto flex items-center justify-center gap-2 px-5 py-3 sm:py-2.5 bg-blue-500 active:bg-blue-600 text-white font-medium rounded-xl transition-colors touch-manipulation"
        >
          <Plus size={20} className="sm:w-[18px] sm:h-[18px]" />
          <span>New List</span>
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6">
        {/* Lists */}
        <div className="lg:col-span-1 space-y-2 sm:space-y-3">
          {lists.length === 0 ? (
            <div
              className={`backdrop-blur-lg rounded-xl p-6 border text-center ${bgCard}`}
            >
              <ListMusic size={40} className={`mx-auto mb-3 ${textMuted}`} />
              <p className={textMuted}>No worship lists yet</p>
              <button className="mt-4 px-5 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors">
                Create First List
              </button>
            </div>
          ) : (
            lists.map((list) => (
              <button
                key={list.id}
                onClick={() => handleSelectList(list)}
                className={`w-full text-left backdrop-blur-lg rounded-xl p-3 sm:p-4 
                  border transition-all touch-manipulation active:scale-[0.98] ${
                    selectedList?.id === list.id
                      ? `border-blue-400 ${isDark ? "bg-blue-500/20" : "bg-blue-50"}`
                      : `${bgCard} ${bgCardHover}`
                  }`}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div
                      className={`w-10 h-10 rounded-lg flex items-center justify-center ${isDark ? "bg-violet-500/20" : "bg-violet-100"}`}
                    >
                      <Calendar size={18} className="text-violet-500" />
                    </div>
                    <div>
                      <h3 className={`text-base font-semibold ${textPrimary}`}>
                        {list.date}
                      </h3>
                      <p className={`text-sm ${textMuted}`}>
                        {list.profile_name || "No leader assigned"}
                      </p>
                    </div>
                  </div>
                  <span
                    className={`px-2 py-1 rounded-lg text-xs font-medium ${isDark ? "bg-white/10 text-white/60" : "bg-gray-100 text-gray-600"}`}
                  >
                    {list.song_count || 0} songs
                  </span>
                </div>
              </button>
            ))
          )}
        </div>

        {/* List Details */}
        <div className="lg:col-span-2">
          {selectedList ? (
            <div className={`backdrop-blur-lg rounded-xl p-6 border ${bgCard}`}>
              <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6 gap-4">
                <div className="flex items-center gap-4">
                  <div
                    className={`w-14 h-14 rounded-xl flex items-center justify-center ${isDark ? "bg-violet-500/20" : "bg-violet-100"}`}
                  >
                    <ListMusic size={28} className="text-violet-500" />
                  </div>
                  <div>
                    <h2
                      className={`text-xl sm:text-2xl font-bold ${textPrimary}`}
                    >
                      {selectedList.date}
                    </h2>
                    <p className={`text-sm ${textSecondary}`}>
                      <User className="inline mr-1" size={14} />
                      {selectedList.profile_name || "Not assigned"}
                    </p>
                  </div>
                </div>
                <div className="flex gap-2 w-full sm:w-auto flex-wrap">
                  {isEditing ? (
                    <>
                      <button
                        onClick={handleCancelEdit}
                        className="flex-1 sm:flex-initial px-3 sm:px-4 py-2.5 sm:py-2 rounded-lg text-sm sm:text-base font-medium transition-colors touch-manipulation bg-gray-500 hover:bg-gray-600 text-white"
                      >
                        Cancel
                      </button>
                      <button
                        onClick={handleSaveEdits}
                        className="flex-1 sm:flex-initial px-3 sm:px-4 py-2.5 sm:py-2 rounded-lg text-sm sm:text-base font-medium transition-colors touch-manipulation bg-emerald-500 hover:bg-emerald-600 text-white"
                      >
                        Save Changes
                      </button>
                    </>
                  ) : isReordering ? (
                    <>
                      <button
                        onClick={() => setIsReordering(false)}
                        className="flex-1 sm:flex-initial px-3 sm:px-4 py-2.5 sm:py-2 rounded-lg text-sm sm:text-base font-medium transition-colors touch-manipulation bg-gray-500 hover:bg-gray-600 text-white"
                      >
                        Cancel
                      </button>
                      <button
                        onClick={saveReorder}
                        className="flex-1 sm:flex-initial px-3 sm:px-4 py-2.5 sm:py-2 rounded-lg text-sm sm:text-base font-medium transition-colors touch-manipulation bg-amber-500 hover:bg-amber-600 text-white"
                      >
                        Save Order
                      </button>
                    </>
                  ) : (
                    <>
                      <button
                        onClick={() => {
                          setIsEditing(true);
                          setIsReordering(false);
                        }}
                        className="flex-1 sm:flex-initial px-3 sm:px-4 py-2.5 sm:py-2 rounded-lg text-sm sm:text-base font-medium transition-colors touch-manipulation bg-blue-500 hover:bg-blue-600 text-white"
                      >
                        Edit List
                      </button>
                      <button
                        onClick={() => setShowDeleteModal(true)}
                        className="flex-1 sm:flex-initial px-3 sm:px-4 py-2.5 sm:py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg text-sm sm:text-base font-medium transition-colors flex items-center justify-center gap-2 touch-manipulation"
                        title="Delete this worship list"
                      >
                        <Trash2 size={16} />
                        <span className="hidden sm:inline">Delete</span>
                      </button>
                    </>
                  )}
                </div>
              </div>

              {selectedList.notes && (
                <div
                  className={`rounded-lg p-4 mb-6 ${isDark ? "bg-white/5" : "bg-gray-50"}`}
                >
                  <h4 className={`text-sm mb-2 font-medium ${textSecondary}`}>
                    Notes
                  </h4>
                  <p className={textMuted}>{selectedList.notes}</p>
                </div>
              )}

              {/* Songs in List */}
              <div>
                <div className="flex items-center justify-between mb-4">
                  <h3 className={`text-lg font-semibold ${textPrimary}`}>
                    Songs ({listSongs.length})
                  </h3>
                </div>

                {/* Add Song Search in Edit Mode */}
                {isEditing && (
                  <div className="mb-4">
                    <div className="relative">
                      <Search
                        className={`absolute left-3 top-1/2 -translate-y-1/2 ${textMuted}`}
                        size={18}
                      />
                      <input
                        type="text"
                        placeholder="Search songs to add..."
                        value={editSearchQuery}
                        onChange={(e) => setEditSearchQuery(e.target.value)}
                        className={`w-full pl-10 pr-4 py-2.5 rounded-lg border ${
                          isDark
                            ? "bg-white/5 border-white/10 text-white placeholder-white/40 focus:border-blue-500/50"
                            : "bg-white border-gray-300 text-gray-900 placeholder-gray-400 focus:border-blue-500"
                        } focus:outline-none focus:ring-2 focus:ring-blue-500/20 touch-manipulation`}
                      />
                    </div>
                    {editSearchResults.length > 0 && (
                      <div
                        className={`mt-2 max-h-48 overflow-y-auto rounded-lg border ${isDark ? "bg-white/5 border-white/10" : "bg-white border-gray-200"}`}
                      >
                        {editSearchResults.map((song) => (
                          <button
                            key={song.id}
                            onClick={() => handleAddSongToList(song)}
                            className={`w-full text-left px-3 py-2.5 flex items-center gap-3 transition-colors touch-manipulation ${
                              isDark ? "hover:bg-white/10" : "hover:bg-gray-100"
                            }`}
                          >
                            <Plus size={16} className="text-green-500" />
                            <div className="flex-1 min-w-0">
                              <p
                                className={`text-sm font-medium truncate ${textPrimary}`}
                              >
                                {song.title}
                              </p>
                              <p className={`text-xs truncate ${textMuted}`}>
                                {song.artist}
                              </p>
                            </div>
                            {song.key_chord && (
                              <span
                                className={`text-xs px-2 py-0.5 rounded ${isDark ? "bg-amber-500/20 text-amber-400" : "bg-amber-100 text-amber-700"}`}
                              >
                                {getKeyChord(song.key_chord)}
                              </span>
                            )}
                          </button>
                        ))}
                      </div>
                    )}
                    <p className={`text-xs mt-2 ${textMuted}`}>
                      💡 You can also drag songs to reorder them below
                    </p>
                  </div>
                )}

                {/* Song List - with drag-to-reorder in Edit mode */}
                {listSongs.length > 0 ? (
                  isEditing ? (
                    // EDIT MODE: Draggable + Remove button
                    <Reorder.Group
                      axis="y"
                      values={listSongs}
                      onReorder={handleReorder}
                      className="space-y-2"
                    >
                      {listSongs.map((song, index) => (
                        <Reorder.Item
                          key={song.id}
                          value={song}
                          className={`flex items-center rounded-lg p-3 sm:p-4 cursor-grab active:cursor-grabbing ${bgSongItem} ${isDark ? "hover:bg-white/10" : "hover:bg-gray-100"}`}
                        >
                          <GripVertical
                            size={20}
                            className={`mr-2 sm:mr-3 ${textMuted} flex-shrink-0`}
                          />
                          <span
                            className={`w-7 h-7 sm:w-8 sm:h-8 flex items-center justify-center rounded-full mr-3 sm:mr-4 text-xs sm:text-sm font-medium flex-shrink-0 ${isDark ? "bg-white/10 text-white/60" : "bg-gray-200 text-gray-600"}`}
                          >
                            {index + 1}
                          </span>
                          <div className="flex-1 min-w-0">
                            <p
                              className={`font-medium text-sm sm:text-base truncate ${textPrimary}`}
                            >
                              {song.title}
                            </p>
                            <p
                              className={`text-xs sm:text-sm truncate ${textMuted}`}
                            >
                              {song.artist}
                            </p>
                          </div>
                          {song.key_chord && (
                            <span
                              className={`px-2 py-1 rounded text-xs font-bold flex-shrink-0 ml-2 ${isDark ? "bg-amber-500/20 text-amber-400" : "bg-amber-100 text-amber-700"}`}
                            >
                              {getKeyChord(song.key_chord)}
                            </span>
                          )}
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleRemoveSongFromList(song.id);
                            }}
                            className={`ml-2 p-2 rounded-lg transition-colors touch-manipulation flex-shrink-0 ${
                              isDark
                                ? "hover:bg-red-500/20 text-red-400"
                                : "hover:bg-red-100 text-red-600"
                            }`}
                            title="Remove from list"
                          >
                            <X size={18} />
                          </button>
                        </Reorder.Item>
                      ))}
                    </Reorder.Group>
                  ) : isReordering ? (
                    // ARRANGE MODE: Just draggable
                    <Reorder.Group
                      axis="y"
                      values={listSongs}
                      onReorder={handleReorder}
                      className="space-y-2"
                    >
                      {listSongs.map((song, index) => (
                        <Reorder.Item
                          key={song.id}
                          value={song}
                          className={`flex items-center rounded-lg p-3 sm:p-4 cursor-grab active:cursor-grabbing ${bgSongItem} ${isDark ? "hover:bg-white/10" : "hover:bg-gray-100"}`}
                        >
                          <GripVertical
                            size={20}
                            className={`mr-2 sm:mr-3 ${textMuted} flex-shrink-0`}
                          />
                          <span
                            className={`w-7 h-7 sm:w-8 sm:h-8 flex items-center justify-center rounded-full mr-3 sm:mr-4 text-xs sm:text-sm font-medium flex-shrink-0 ${isDark ? "bg-white/10 text-white/60" : "bg-gray-200 text-gray-600"}`}
                          >
                            {index + 1}
                          </span>
                          <div className="flex-1 min-w-0">
                            <p
                              className={`font-medium text-sm sm:text-base truncate ${textPrimary}`}
                            >
                              {song.title}
                            </p>
                            <p
                              className={`text-xs sm:text-sm truncate ${textMuted}`}
                            >
                              {song.artist}
                            </p>
                          </div>
                          {song.key_chord && (
                            <span
                              className={`px-2 py-1 rounded text-xs font-bold flex-shrink-0 ml-2 ${isDark ? "bg-amber-500/20 text-amber-400" : "bg-amber-100 text-amber-700"}`}
                            >
                              {getKeyChord(song.key_chord)}
                            </span>
                          )}
                        </Reorder.Item>
                      ))}
                    </Reorder.Group>
                  ) : (
                    // VIEW MODE: Clickable to view lyrics
                    <div className="space-y-2">
                      {listSongs.map((song, index) => (
                        <div
                          key={song.id}
                          className={`flex items-center rounded-lg p-3 sm:p-4 transition-all cursor-pointer ${bgSongItem} ${isDark ? "hover:bg-white/10 hover:border-cyan-500/30" : "hover:bg-gray-100 hover:shadow-sm"} border ${isDark ? "border-transparent" : "border-gray-200"}`}
                          onClick={() => navigate(`/song/${song.id}`)}
                        >
                          <span
                            className={`w-7 h-7 sm:w-8 sm:h-8 flex items-center justify-center rounded-full mr-3 sm:mr-4 text-xs sm:text-sm font-medium flex-shrink-0 ${isDark ? "bg-white/10 text-white/60" : "bg-gray-200 text-gray-600"}`}
                          >
                            {index + 1}
                          </span>
                          <div
                            className={`w-8 h-8 sm:w-10 sm:h-10 rounded-lg flex items-center justify-center mr-2 sm:mr-3 flex-shrink-0 ${isDark ? "bg-cyan-500/20" : "bg-cyan-100"}`}
                          >
                            <Music
                              size={16}
                              className="text-cyan-500 sm:w-[18px] sm:h-[18px]"
                            />
                          </div>
                          <div className="flex-1 min-w-0">
                            <p
                              className={`font-medium text-sm sm:text-base truncate ${textPrimary}`}
                            >
                              {song.title}
                            </p>
                            <p
                              className={`text-xs sm:text-sm truncate ${textMuted}`}
                            >
                              {song.artist}
                            </p>
                          </div>
                          {song.key_chord && (
                            <span
                              className={`px-2 sm:px-3 py-1 sm:py-1.5 rounded-lg text-xs sm:text-sm font-bold flex-shrink-0 ml-2 ${isDark ? "bg-amber-500/20 text-amber-400" : "bg-amber-100 text-amber-700"}`}
                            >
                              {getKeyChord(song.key_chord)}
                            </span>
                          )}
                        </div>
                      ))}
                    </div>
                  )
                ) : (
                  <div className={`text-center py-8 ${textMuted}`}>
                    <Music size={40} className="mx-auto mb-2 opacity-50" />
                    <p>No songs in this list</p>
                    {isEditing && (
                      <p className="text-sm mt-1">Search above to add songs</p>
                    )}
                  </div>
                )}
              </div>
            </div>
          ) : (
            <div
              className={`backdrop-blur-lg rounded-xl p-12 border flex items-center justify-center ${bgCard}`}
            >
              <div className="text-center">
                <ListMusic size={48} className={`mx-auto mb-4 ${textMuted}`} />
                <p className={`text-lg ${textMuted}`}>
                  Select a worship list to view details
                </p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* New List Modal */}
      <AnimatePresence>
        {showNewListModal && (
          <div
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={(e) => {
              if (e.target === e.currentTarget) {
                setShowNewListModal(false);
              }
            }}
          >
            <motion.div
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.9 }}
              className={`max-w-3xl w-full rounded-2xl p-6 shadow-2xl max-h-[90vh] overflow-y-auto ${isDark ? "bg-gray-800" : "bg-white"}`}
            >
              <div className="flex justify-between items-center mb-6">
                <h2 className={`text-2xl font-bold ${textPrimary}`}>
                  Create New Worship List
                </h2>
                <button
                  onClick={() => setShowNewListModal(false)}
                  className={`p-2 rounded-lg transition-colors ${isDark ? "hover:bg-white/10" : "hover:bg-gray-100"}`}
                >
                  <X size={20} className={textMuted} />
                </button>
              </div>

              {/* Date and Leader Selection */}
              <div className="grid md:grid-cols-2 gap-4 mb-6">
                <div>
                  <label
                    className={`block text-sm font-medium mb-2 ${textSecondary}`}
                  >
                    Service Date *
                  </label>
                  <input
                    type="date"
                    value={newListDate}
                    onChange={(e) => setNewListDate(e.target.value)}
                    className={`w-full px-4 py-2 rounded-lg border ${isDark ? "bg-white/5 border-white/10 text-white" : "bg-white border-gray-200 text-gray-900"}`}
                  />
                </div>
                <div>
                  <label
                    className={`block text-sm font-medium mb-2 ${textSecondary}`}
                  >
                    Worship Leader
                  </label>
                  <select
                    value={newListLeader}
                    onChange={(e) => setNewListLeader(e.target.value)}
                    className={`w-full px-4 py-2 rounded-lg border ${isDark ? "bg-white/5 border-white/10 text-white" : "bg-white border-gray-200 text-gray-900"}`}
                  >
                    <option value="">Select leader...</option>
                    {profiles.map((profile) => (
                      <option key={profile.id} value={profile.id}>
                        {profile.name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Notes */}
              <div className="mb-6">
                <label
                  className={`block text-sm font-medium mb-2 ${textSecondary}`}
                >
                  Notes (Optional)
                </label>
                <textarea
                  value={newListNotes}
                  onChange={(e) => setNewListNotes(e.target.value)}
                  rows={3}
                  placeholder="Add any notes or special instructions..."
                  className={`w-full px-4 py-2 rounded-lg border ${isDark ? "bg-white/5 border-white/10 text-white" : "bg-white border-gray-200 text-gray-900"}`}
                />
              </div>

              {/* Search Songs */}
              <div className="mb-6">
                <label
                  className={`block text-sm font-medium mb-2 ${textSecondary}`}
                >
                  Add Songs
                </label>
                <div className="relative mb-4">
                  <Search
                    className={`absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 ${textMuted}`}
                  />
                  <input
                    type="text"
                    value={searchQuery}
                    onChange={(e) => handleSearchSongs(e.target.value)}
                    placeholder="Search by song title or artist..."
                    className={`w-full pl-10 pr-4 py-2 rounded-lg border ${isDark ? "bg-white/5 border-white/10 text-white" : "bg-white border-gray-200 text-gray-900"}`}
                  />
                </div>

                {/* Search Results */}
                {searchResults.length > 0 && (
                  <div
                    className={`rounded-lg border p-2 mb-4 max-h-48 overflow-y-auto ${isDark ? "bg-white/5 border-white/10" : "bg-gray-50 border-gray-200"}`}
                  >
                    {searchResults.map((song) => (
                      <button
                        key={song.id}
                        onClick={() => handleAddSongToNewList(song)}
                        className={`w-full flex items-center gap-3 p-2 rounded-lg transition-colors ${isDark ? "hover:bg-white/10" : "hover:bg-white"}`}
                      >
                        <Music size={16} className={textMuted} />
                        <div className="flex-1 text-left">
                          <p className={`font-medium ${textPrimary}`}>
                            {song.title}
                          </p>
                          <p className={`text-sm ${textMuted}`}>
                            {song.artist}
                          </p>
                        </div>
                        {song.key_chord && (
                          <span
                            className={`px-3 py-1.5 rounded-lg text-sm font-bold ${isDark ? "bg-amber-500/20 text-amber-400" : "bg-amber-100 text-amber-700"}`}
                          >
                            {getKeyChord(song.key_chord)}
                          </span>
                        )}
                      </button>
                    ))}
                  </div>
                )}
              </div>

              {/* Selected Songs - Reorderable */}
              <div className="mb-6">
                <h3 className={`text-lg font-semibold ${textPrimary} mb-3`}>
                  Selected Songs ({selectedSongs.length})
                </h3>
                {selectedSongs.length > 0 ? (
                  <Reorder.Group
                    axis="y"
                    values={selectedSongs}
                    onReorder={handleReorderNewListSongs}
                    className="space-y-2"
                  >
                    {selectedSongs.map((song, index) => (
                      <Reorder.Item
                        key={song.id}
                        value={song}
                        className={`flex items-center rounded-lg p-3 cursor-grab active:cursor-grabbing ${isDark ? "bg-white/5" : "bg-gray-50"}`}
                      >
                        <GripVertical
                          size={18}
                          className={`mr-2 ${textMuted}`}
                        />
                        <span
                          className={`w-6 h-6 flex items-center justify-center rounded-full mr-3 text-sm font-medium ${isDark ? "bg-white/10 text-white/60" : "bg-gray-200 text-gray-600"}`}
                        >
                          {index + 1}
                        </span>
                        <div className="flex-1">
                          <p className={`font-medium ${textPrimary}`}>
                            {song.title}
                          </p>
                          <p className={`text-sm ${textMuted}`}>
                            {song.artist}
                          </p>
                        </div>
                        {song.key_chord && (
                          <span
                            className={`px-3 py-1.5 rounded-lg text-sm font-bold mr-2 ${isDark ? "bg-amber-500/20 text-amber-400" : "bg-amber-100 text-amber-700"}`}
                          >
                            {getKeyChord(song.key_chord)}
                          </span>
                        )}
                        <button
                          onClick={() => handleRemoveSongFromNewList(song.id)}
                          className={`p-1 rounded transition-colors ${isDark ? "hover:bg-red-500/20 text-red-400" : "hover:bg-red-100 text-red-600"}`}
                        >
                          <X size={16} />
                        </button>
                      </Reorder.Item>
                    ))}
                  </Reorder.Group>
                ) : (
                  <p className={`text-center py-4 ${textMuted}`}>
                    No songs added yet. Search and add songs above.
                  </p>
                )}
              </div>

              {/* Actions */}
              <div className="flex justify-end gap-3">
                <button
                  onClick={() => setShowNewListModal(false)}
                  className={`px-6 py-2 rounded-lg font-medium transition-colors ${isDark ? "bg-white/10 hover:bg-white/20 text-white" : "bg-gray-100 hover:bg-gray-200 text-gray-700"}`}
                >
                  Cancel
                </button>
                <button
                  onClick={handleSaveNewList}
                  disabled={!newListDate}
                  className={`px-6 py-2 rounded-lg font-medium transition-colors ${
                    newListDate
                      ? "bg-blue-500 hover:bg-blue-600 text-white"
                      : "bg-gray-300 text-gray-500 cursor-not-allowed"
                  }`}
                >
                  Create List
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Delete Confirmation Modal */}
      <AnimatePresence>
        {showDeleteModal && selectedList && (
          <div
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={(e) => {
              if (e.target === e.currentTarget) {
                setShowDeleteModal(false);
              }
            }}
          >
            <motion.div
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.9 }}
              className={`max-w-md w-full rounded-2xl p-6 shadow-2xl ${isDark ? "bg-gray-800" : "bg-white"}`}
            >
              <div className="flex items-center gap-3 mb-4">
                <div className="w-12 h-12 rounded-full bg-red-500/20 flex items-center justify-center">
                  <Trash2 size={24} className="text-red-500" />
                </div>
                <div>
                  <h3
                    className={`text-xl font-bold ${isDark ? "text-white" : "text-gray-900"}`}
                  >
                    Delete Worship List
                  </h3>
                  <p className={isDark ? "text-white/60" : "text-gray-600"}>
                    This action cannot be undone
                  </p>
                </div>
              </div>

              <p
                className={`mb-6 ${isDark ? "text-white/80" : "text-gray-700"}`}
              >
                Are you sure you want to delete the worship list for{" "}
                <strong>{selectedList.date}</strong>?
              </p>

              <div className="flex gap-3">
                <button
                  onClick={() => setShowDeleteModal(false)}
                  className={`flex-1 px-4 py-2 rounded-lg font-medium transition-colors ${
                    isDark
                      ? "bg-white/10 hover:bg-white/20 text-white"
                      : "bg-gray-100 hover:bg-gray-200 text-gray-700"
                  }`}
                >
                  Cancel
                </button>
                <button
                  onClick={handleDeleteList}
                  className="flex-1 px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg font-medium transition-colors"
                >
                  Delete
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
}
