import { useState, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { Search, Music, Mic2, Filter, Grid, List } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { useTheme } from "@context/ThemeContext";
import { useSongs } from "@hooks/useDataFetch";

export default function DatabasePage() {
  const navigate = useNavigate();
  const { isDark } = useTheme();
  const { songs, loading } = useSongs();
  const [searchQuery, setSearchQuery] = useState("");
  const [viewMode, setViewMode] = useState("grid"); // grid or list

  const filteredSongs = useMemo(() => {
    if (!searchQuery.trim()) return songs;
    const query = searchQuery.toLowerCase();
    return songs.filter(
      (song) =>
        song.title?.toLowerCase().includes(query) ||
        song.artist?.toLowerCase().includes(query) ||
        song.singer?.toLowerCase().includes(query) ||
        song.key_chord?.toLowerCase().includes(query),
    );
  }, [songs, searchQuery]);

  // 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";

  return (
    <div className="max-w-7xl mx-auto">
      {/* Header */}
      <div className="mb-8">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
          <div>
            <h1 className={`text-3xl font-bold ${textPrimary} mb-2`}>
              Song Database
            </h1>
            <p className={textMuted}>{songs.length} songs available</p>
          </div>

          {/* View Toggle */}
          <div
            className={`flex items-center gap-1 p-1 rounded-lg ${isDark ? "bg-white/5" : "bg-gray-100"}`}
          >
            <button
              onClick={() => setViewMode("grid")}
              className={`p-2 rounded-md transition-colors ${
                viewMode === "grid"
                  ? isDark
                    ? "bg-white/10 text-white"
                    : "bg-white text-gray-900 shadow-sm"
                  : textMuted
              }`}
            >
              <Grid size={18} />
            </button>
            <button
              onClick={() => setViewMode("list")}
              className={`p-2 rounded-md transition-colors ${
                viewMode === "list"
                  ? isDark
                    ? "bg-white/10 text-white"
                    : "bg-white text-gray-900 shadow-sm"
                  : textMuted
              }`}
            >
              <List size={18} />
            </button>
          </div>
        </div>

        {/* Search Bar */}
        <div className="relative">
          <Search
            className={`absolute left-4 top-1/2 -translate-y-1/2 ${textMuted}`}
            size={20}
          />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search by title, artist, or key..."
            className={`w-full pl-12 pr-4 py-4 rounded-xl text-lg outline-none transition-all
              ${
                isDark
                  ? "bg-white/5 border border-white/10 focus:border-cyan-500/50 focus:bg-white/10 text-white placeholder-white/40"
                  : "bg-gray-50 border border-gray-200 focus:border-cyan-500 focus:bg-white text-gray-900 placeholder-gray-400"
              }`}
          />
        </div>
      </div>

      {/* Loading State */}
      {loading && (
        <div className={`text-center py-20 ${textMuted}`}>
          <div className="w-12 h-12 border-2 border-t-cyan-500 border-cyan-500/20 rounded-full animate-spin mx-auto mb-4"></div>
          <p>Loading songs...</p>
        </div>
      )}

      {/* No Results */}
      {!loading && filteredSongs.length === 0 && (
        <div className={`text-center py-20 ${textMuted}`}>
          <Music size={48} className="mx-auto mb-4 opacity-50" />
          <p className="text-lg mb-2">No songs found</p>
          <p className="text-sm">Try a different search term</p>
        </div>
      )}

      {/* Grid View */}
      {!loading && viewMode === "grid" && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
        >
          <AnimatePresence mode="popLayout">
            {filteredSongs.map((song, index) => (
              <motion.div
                key={song.id}
                layout
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.9 }}
                transition={{ delay: index * 0.02, duration: 0.3 }}
                onClick={() => navigate(`/song/${song.id}`)}
                className={`group cursor-pointer p-5 rounded-xl transition-all
                  ${
                    isDark
                      ? "bg-gradient-to-br from-white/5 to-white/[0.02] border border-white/10 hover:border-cyan-500/40 hover:bg-white/10"
                      : "bg-gradient-to-br from-slate-50 to-stone-100 border border-gray-200 hover:border-cyan-400 hover:shadow-lg shadow-sm"
                  }`}
              >
                {/* Icon & Key Badge */}
                <div className="flex items-start justify-between mb-4">
                  <div
                    className={`w-12 h-12 rounded-xl ${isDark ? "bg-cyan-500/20" : "bg-cyan-100"} flex items-center justify-center group-hover:scale-110 transition-transform`}
                  >
                    <Music size={22} className="text-cyan-500" />
                  </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"
                      }`}
                    >
                      {song.key_chord}
                    </span>
                  )}
                </div>

                {/* Title */}
                <h3
                  className={`text-lg font-semibold ${textPrimary} mb-2 truncate group-hover:text-cyan-500 transition-colors`}
                >
                  {song.title}
                </h3>

                {/* Artist */}
                <div
                  className={`flex items-center gap-2 ${textSecondary} text-sm mb-3`}
                >
                  <Mic2 size={14} />
                  <span className="truncate">
                    {song.artist || song.singer || "Unknown artist"}
                  </span>
                </div>

                {/* Band / Additional Info */}
                {song.band && (
                  <p className={`text-xs ${textMuted} truncate`}>{song.band}</p>
                )}
              </motion.div>
            ))}
          </AnimatePresence>
        </motion.div>
      )}

      {/* List View */}
      {!loading && viewMode === "list" && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="space-y-2"
        >
          {/* Header Row */}
          <div
            className={`grid grid-cols-12 gap-4 px-4 py-2 text-sm font-medium ${textMuted}`}
          >
            <div className="col-span-5 sm:col-span-4">Title</div>
            <div className="col-span-4 sm:col-span-3">Artist</div>
            <div className="col-span-3 sm:col-span-2">Key</div>
            <div className="hidden sm:block sm:col-span-3">Band</div>
          </div>

          <AnimatePresence mode="popLayout">
            {filteredSongs.map((song, index) => (
              <motion.div
                key={song.id}
                layout
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: 20 }}
                transition={{ delay: index * 0.015, duration: 0.25 }}
                onClick={() => navigate(`/song/${song.id}`)}
                className={`grid grid-cols-12 gap-4 px-4 py-4 rounded-xl cursor-pointer transition-all
                  ${
                    isDark
                      ? "bg-white/5 hover:bg-white/10 border border-white/5 hover:border-cyan-500/30"
                      : "bg-slate-50 hover:bg-slate-100 border border-gray-200 hover:border-cyan-400 shadow-sm"
                  }`}
              >
                <div
                  className={`col-span-5 sm:col-span-4 font-medium ${textPrimary} truncate`}
                >
                  {song.title}
                </div>
                <div
                  className={`col-span-4 sm:col-span-3 ${textSecondary} truncate`}
                >
                  {song.artist || song.singer || "—"}
                </div>
                <div className="col-span-3 sm:col-span-2">
                  {song.key_chord ? (
                    <span
                      className={`inline-block px-2 py-1 rounded text-xs font-bold
                      ${
                        isDark
                          ? "bg-amber-500/20 text-amber-400"
                          : "bg-amber-100 text-amber-700"
                      }`}
                    >
                      {song.key_chord}
                    </span>
                  ) : (
                    <span className={textMuted}>—</span>
                  )}
                </div>
                <div
                  className={`hidden sm:block sm:col-span-3 ${textMuted} truncate`}
                >
                  {song.band || "—"}
                </div>
              </motion.div>
            ))}
          </AnimatePresence>
        </motion.div>
      )}
    </div>
  );
}
