import { useState, useEffect, useMemo } from "react";
import { Link, useNavigate } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import {
  Music,
  Search,
  Plus,
  X,
  FileText,
  Upload,
  Mic2,
  ListMusic,
  Sparkles,
  ChevronRight,
  Calendar,
} from "lucide-react";
import { useTheme } from "@context/ThemeContext";
import { parseDocument } from "@utils/documentParser";
import {
  useSongs,
  useLists,
  useStats,
  useDataMutations,
} from "@hooks/useDataFetch";

// Smooth animation variants
const containerVariants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: { staggerChildren: 0.08, delayChildren: 0.05, duration: 0.4 },
  },
};

const tileVariants = {
  hidden: { opacity: 0, y: 15 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { type: "tween", ease: "easeOut", duration: 0.4 },
  },
};

const modalVariants = {
  hidden: { opacity: 0, scale: 0.95 },
  visible: {
    opacity: 1,
    scale: 1,
    transition: { type: "tween", ease: "easeOut", duration: 0.2 },
  },
  exit: { opacity: 0, scale: 0.95, transition: { duration: 0.15 } },
};

export default function HomePage() {
  const navigate = useNavigate();
  const { isDark } = useTheme();

  // Use cached data from the global store
  const { stats, loading: statsLoading } = useStats();
  const { songs, loading: songsLoading } = useSongs();
  const { lists: worshipLists, loading: listsLoading } = useLists();

  const [searchQuery, setSearchQuery] = useState("");
  const [activeModal, setActiveModal] = useState(null);
  const [uploading, setUploading] = useState(false);

  // Combined loading state
  const loading = statsLoading && songsLoading && listsLoading;

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

  const handleFileUpload = async (event) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setUploading(true);
    try {
      const parsed = await parseDocument(file);

      // Navigate to create page with parsed data
      navigate("/song/new", {
        state: {
          uploadedData: {
            title: parsed.title || file.name.replace(/\.[^/.]+$/, ""),
            lyrics: parsed.lyrics,
            chords: parsed.chords,
            key_chord: parsed.key,
            artist: parsed.artist,
          },
        },
      });
    } catch (error) {
      console.error("Failed to parse document:", error);
      alert(error.message || "Failed to parse document");
    } finally {
      setUploading(false);
      event.target.value = ""; // Reset input
    }
  };

  const closeModal = () => {
    setActiveModal(null);
    setSearchQuery("");
    setSearchResults([]);
  };

  // Theme-aware classes
  const textPrimary = isDark ? "text-white" : "text-gray-900";
  const textSecondary = isDark ? "text-white/60" : "text-gray-600";
  const textMuted = isDark ? "text-white/50" : "text-gray-500";

  return (
    <div className="min-h-[calc(100vh-12rem)]">
      {/* Stats Bar */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ duration: 0.5 }}
        className="flex justify-center gap-8 sm:gap-12 mb-10"
      >
        {[
          { label: "Songs", value: stats.songs, color: "text-cyan-500" },
          {
            label: "Profiles",
            value: stats.profiles,
            color: "text-violet-500",
          },
          { label: "Lists", value: stats.lists, color: "text-amber-500" },
        ].map((stat) => (
          <div key={stat.label} className="text-center">
            <div className={`text-3xl sm:text-4xl font-bold ${stat.color}`}>
              {loading ? "—" : stat.value}
            </div>
            <div className={`${textSecondary} text-sm mt-1`}>{stat.label}</div>
          </div>
        ))}
      </motion.div>

      {/* Main Tiles Grid */}
      <motion.div
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        className="grid grid-cols-1 lg:grid-cols-2 gap-5 mb-5"
      >
        {/* Left Tile: Worship Lists */}
        <motion.div
          variants={tileVariants}
          onClick={() => setActiveModal("worship")}
          className={`group cursor-pointer relative overflow-hidden rounded-2xl 
            ${
              isDark
                ? "bg-gradient-to-br from-violet-600/25 via-purple-600/20 to-fuchsia-600/25 border-white/10 hover:border-violet-400/50"
                : "bg-gradient-to-br from-violet-200 via-purple-100 to-fuchsia-200 border-violet-300 hover:border-violet-500"
            }
            border backdrop-blur-xl p-6 sm:p-8 min-h-[240px]
            hover:shadow-xl hover:shadow-violet-500/20
            transition-all duration-300 ease-out`}
        >
          <div className="relative z-10">
            <div className="flex items-start justify-between mb-5">
              <div
                className={`w-14 h-14 rounded-xl ${isDark ? "bg-violet-500/30" : "bg-violet-500/25"} flex items-center justify-center`}
              >
                <ListMusic className="text-violet-600" size={28} />
              </div>
              <div
                className={`flex items-center gap-2 px-3 py-1.5 rounded-full ${isDark ? "bg-violet-500/20 text-violet-300" : "bg-violet-500/20 text-violet-800"} text-base font-semibold`}
              >
                <span>{stats.lists} lists</span>
              </div>
            </div>
            <h2
              className={`text-2xl sm:text-3xl font-bold ${textPrimary} mb-3`}
            >
              Worship Lists
            </h2>
            <p className={`${textMuted} mb-5 text-base sm:text-lg`}>
              Create and manage your Sunday service setlists
            </p>
            <div className="flex items-center text-violet-600 font-semibold text-base">
              <span>Open Manager</span>
              <ChevronRight
                size={20}
                className="ml-1 group-hover:translate-x-1 transition-transform"
              />
            </div>
          </div>
        </motion.div>

        {/* Right Tile: Search Songs */}
        <motion.div
          variants={tileVariants}
          onClick={() => setActiveModal("search")}
          className={`group cursor-pointer relative overflow-hidden rounded-2xl 
            ${
              isDark
                ? "bg-gradient-to-br from-cyan-600/25 via-blue-600/20 to-sky-600/25 border-white/10 hover:border-cyan-400/50"
                : "bg-gradient-to-br from-cyan-200 via-blue-100 to-sky-200 border-cyan-300 hover:border-cyan-500"
            }
            border backdrop-blur-xl p-6 sm:p-8 min-h-[240px]
            hover:shadow-xl hover:shadow-cyan-500/20
            transition-all duration-300 ease-out`}
        >
          <div className="relative z-10">
            <div className="flex items-start justify-between mb-5">
              <div
                className={`w-14 h-14 rounded-xl ${isDark ? "bg-cyan-500/30" : "bg-cyan-500/25"} flex items-center justify-center`}
              >
                <Search className="text-cyan-600" size={28} />
              </div>
              <div
                className={`flex items-center gap-2 px-3 py-1.5 rounded-full ${isDark ? "bg-cyan-500/20 text-cyan-300" : "bg-cyan-500/20 text-cyan-800"} text-base font-semibold`}
              >
                <span>{stats.songs} songs</span>
              </div>
            </div>
            <h2
              className={`text-2xl sm:text-3xl font-bold ${textPrimary} mb-3`}
            >
              Search Songs
            </h2>
            <p className={`${textMuted} mb-5 text-base sm:text-lg`}>
              Find songs by title, artist, or lyrics
            </p>
            <div className="flex items-center text-cyan-600 font-semibold text-base">
              <span>Start Searching</span>
              <ChevronRight
                size={20}
                className="ml-1 group-hover:translate-x-1 transition-transform"
              />
            </div>
          </div>
        </motion.div>
      </motion.div>

      {/* Bottom Tile: Add New Song */}
      <motion.div
        variants={tileVariants}
        initial="hidden"
        animate="visible"
        onClick={() => setActiveModal("upload")}
        className={`group cursor-pointer relative overflow-hidden rounded-2xl 
          ${
            isDark
              ? "bg-gradient-to-r from-emerald-600/25 via-teal-600/20 to-green-600/25 border-white/10 hover:border-emerald-400/50"
              : "bg-gradient-to-r from-emerald-200 via-teal-100 to-green-200 border-emerald-300 hover:border-emerald-500"
          }
          border backdrop-blur-xl p-6 sm:p-8
          hover:shadow-xl hover:shadow-emerald-500/20
          transition-all duration-300 ease-out`}
      >
        <div className="relative z-10 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div className="flex items-center gap-5">
            <div
              className={`w-14 h-14 rounded-xl ${isDark ? "bg-emerald-500/30" : "bg-emerald-500/25"} flex items-center justify-center`}
            >
              <Plus className="text-emerald-600" size={28} />
            </div>
            <div>
              <h2
                className={`text-2xl sm:text-3xl font-bold ${textPrimary} mb-1`}
              >
                Add New Song
              </h2>
              <p className={`${textMuted} text-base sm:text-lg`}>
                Create a new song or upload lyrics
              </p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <div className={`hidden sm:flex items-center gap-3 ${textMuted}`}>
              <div
                className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-base ${isDark ? "bg-white/5" : "bg-white/80"}`}
              >
                <Upload size={18} />
                <span>Upload</span>
              </div>
              <div
                className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-base ${isDark ? "bg-white/5" : "bg-white/80"}`}
              >
                <FileText size={18} />
                <span>Create</span>
              </div>
            </div>
            <div
              className={`w-12 h-12 rounded-full ${isDark ? "bg-emerald-500/30" : "bg-emerald-500/25"} flex items-center justify-center group-hover:bg-emerald-500/40 transition-colors`}
            >
              <ChevronRight className="text-emerald-600" size={24} />
            </div>
          </div>
        </div>
      </motion.div>

      {/* Modals */}
      <AnimatePresence>
        {activeModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm"
            onClick={closeModal}
          >
            <motion.div
              variants={modalVariants}
              initial="hidden"
              animate="visible"
              exit="exit"
              onClick={(e) => e.stopPropagation()}
              className={`w-full max-w-2xl max-h-[80vh] overflow-hidden rounded-2xl shadow-2xl
                ${isDark ? "bg-slate-900 border border-white/20" : "bg-white border border-gray-200"}`}
            >
              <div
                className={`flex items-center justify-between p-5 border-b ${isDark ? "border-white/10" : "border-gray-200"}`}
              >
                <h3
                  className={`text-lg font-bold ${textPrimary} flex items-center gap-3`}
                >
                  {activeModal === "worship" && (
                    <>
                      <ListMusic className="text-violet-500" size={20} />{" "}
                      Worship Lists
                    </>
                  )}
                  {activeModal === "search" && (
                    <>
                      <Search className="text-cyan-500" size={20} /> Search
                      Songs
                    </>
                  )}
                  {activeModal === "upload" && (
                    <>
                      <Plus className="text-emerald-500" size={20} /> Add New
                      Song
                    </>
                  )}
                </h3>
                <button
                  onClick={closeModal}
                  className={`p-2 rounded-lg transition-colors ${isDark ? "hover:bg-white/10" : "hover:bg-gray-100"}`}
                >
                  <X className={textSecondary} size={18} />
                </button>
              </div>
              <div className="p-5 overflow-y-auto max-h-[calc(80vh-80px)]">
                {activeModal === "worship" && (
                  <div className="space-y-3">
                    {worshipLists.length === 0 ? (
                      <div className={`text-center py-10 ${textMuted}`}>
                        <ListMusic
                          size={40}
                          className="mx-auto mb-3 opacity-50"
                        />
                        <p>No worship lists yet</p>
                        <Link
                          to="/worship-lists"
                          className={`inline-block mt-4 px-5 py-2 rounded-lg transition-colors text-sm
                          ${isDark ? "bg-violet-500/20 hover:bg-violet-500/30 text-violet-300" : "bg-violet-100 hover:bg-violet-200 text-violet-700"}`}
                        >
                          Create First List
                        </Link>
                      </div>
                    ) : (
                      worshipLists.map((list) => (
                        <div
                          key={list.id}
                          className={`flex items-center justify-between p-4 rounded-xl transition-all cursor-pointer
                            ${
                              isDark
                                ? "bg-white/5 hover:bg-white/10 border border-white/5 hover:border-violet-500/30"
                                : "bg-gray-50 hover:bg-gray-100 border border-gray-200 hover:border-violet-400"
                            }`}
                          onClick={() => navigate(`/worship-lists/${list.id}`)}
                        >
                          <div className="flex items-center gap-4">
                            <div
                              className={`w-10 h-10 rounded-lg ${isDark ? "bg-violet-500/20" : "bg-violet-100"} flex items-center justify-center`}
                            >
                              <Calendar size={18} className="text-violet-500" />
                            </div>
                            <div>
                              <h4 className={`font-medium ${textPrimary}`}>
                                {list.date}
                              </h4>
                              <p className={`text-sm ${textMuted}`}>
                                {list.profile_name || "No leader"} •{" "}
                                {list.song_count || 0} songs
                              </p>
                            </div>
                          </div>
                          <ChevronRight size={18} className={textMuted} />
                        </div>
                      ))
                    )}
                    <Link
                      to="/worship-lists"
                      className={`block text-center py-3 rounded-xl transition-colors text-sm
                      ${isDark ? "bg-violet-500/15 hover:bg-violet-500/25 text-violet-300" : "bg-violet-100 hover:bg-violet-200 text-violet-700"}`}
                    >
                      View All Lists
                    </Link>
                  </div>
                )}
                {activeModal === "search" && (
                  <div className="space-y-4">
                    <div className="relative">
                      <Search
                        className={`absolute left-4 top-1/2 -translate-y-1/2 ${textMuted}`}
                        size={18}
                      />
                      <input
                        type="text"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        placeholder="Search by title, artist, or lyrics..."
                        className={`w-full pl-11 pr-4 py-3.5 rounded-xl outline-none transition-all text-sm
                          ${
                            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"
                          }`}
                        autoFocus
                      />
                    </div>
                    {searchResults.length > 0 ? (
                      <div className="space-y-2">
                        {searchResults.map((song) => (
                          <div
                            key={song.id}
                            className={`p-4 rounded-xl transition-all cursor-pointer
                              ${
                                isDark
                                  ? "bg-white/5 hover:bg-white/10 border border-white/5 hover:border-cyan-500/30"
                                  : "bg-gray-50 hover:bg-gray-100 border border-gray-200 hover:border-cyan-400"
                              }`}
                            onClick={() => navigate(`/song/${song.id}`)}
                          >
                            <div className="flex items-start justify-between">
                              <div className="flex-1">
                                <div className="flex items-center gap-2 mb-1">
                                  <h4 className={`font-medium ${textPrimary}`}>
                                    {song.title}
                                  </h4>
                                  {/* Show Key/Chord Badge */}
                                  {song.key_chord && (
                                    <span
                                      className={`px-2 py-0.5 rounded text-xs font-bold
                                      ${
                                        isDark
                                          ? "bg-amber-500/20 text-amber-400"
                                          : "bg-amber-100 text-amber-700"
                                      }`}
                                    >
                                      {song.key_chord}
                                    </span>
                                  )}
                                </div>
                                <p className={`text-sm ${textMuted}`}>
                                  {song.artist ||
                                    song.singer ||
                                    "Unknown artist"}
                                </p>
                                {/* Show chord progression if available */}
                                {song.chords && (
                                  <p
                                    className={`text-xs mt-1 ${isDark ? "text-cyan-400/70" : "text-cyan-600/70"}`}
                                  >
                                    Chords: {song.chords}
                                  </p>
                                )}
                              </div>
                              <Mic2
                                size={14}
                                className="text-cyan-500/50 mt-1"
                              />
                            </div>
                            {song.lyrics && (
                              <p
                                className={`mt-2 text-sm ${textMuted} line-clamp-2`}
                              >
                                {song.lyrics.substring(0, 100)}...
                              </p>
                            )}
                          </div>
                        ))}
                      </div>
                    ) : (
                      searchQuery && (
                        <div className={`text-center py-8 ${textMuted}`}>
                          <Search
                            size={28}
                            className="mx-auto mb-2 opacity-50"
                          />
                          <p className="text-sm">No songs found</p>
                        </div>
                      )
                    )}
                    {!searchQuery && (
                      <div className={`text-center py-8 ${textMuted}`}>
                        <Sparkles
                          size={28}
                          className="mx-auto mb-2 opacity-50"
                        />
                        <p className="text-sm">
                          Start typing to search {stats.songs} songs
                        </p>
                      </div>
                    )}
                    <Link
                      to="/database"
                      className={`block text-center py-3 rounded-xl transition-colors text-sm
                      ${isDark ? "bg-cyan-500/15 hover:bg-cyan-500/25 text-cyan-300" : "bg-cyan-100 hover:bg-cyan-200 text-cyan-700"}`}
                    >
                      Browse Full Database
                    </Link>
                  </div>
                )}
                {activeModal === "upload" && (
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div
                      onClick={() => navigate("/song/new")}
                      className={`p-5 rounded-xl cursor-pointer transition-all group
                        ${
                          isDark
                            ? "bg-gradient-to-br from-emerald-500/10 to-teal-500/10 border border-emerald-500/20 hover:border-emerald-500/40"
                            : "bg-gradient-to-br from-emerald-50 to-teal-50 border border-emerald-200 hover:border-emerald-400"
                        }`}
                    >
                      <div
                        className={`w-12 h-12 rounded-xl ${isDark ? "bg-emerald-500/20" : "bg-emerald-100"} flex items-center justify-center mb-4 group-hover:bg-emerald-500/30 transition-colors`}
                      >
                        <FileText size={24} className="text-emerald-500" />
                      </div>
                      <h4
                        className={`text-base font-semibold ${textPrimary} mb-1`}
                      >
                        Create New
                      </h4>
                      <p className={`text-sm ${textMuted}`}>
                        Start fresh with a blank song
                      </p>
                    </div>
                    <label
                      htmlFor="file-upload"
                      className={`p-5 rounded-xl cursor-pointer transition-all group
                      ${
                        isDark
                          ? "bg-gradient-to-br from-blue-500/10 to-indigo-500/10 border border-blue-500/20 hover:border-blue-500/40"
                          : "bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-200 hover:border-blue-400"
                      }`}
                    >
                      <input
                        id="file-upload"
                        type="file"
                        accept=".pdf,.docx,.txt"
                        onChange={handleFileUpload}
                        className="hidden"
                        disabled={uploading}
                      />
                      <div
                        className={`w-12 h-12 rounded-xl ${isDark ? "bg-blue-500/20" : "bg-blue-100"} flex items-center justify-center mb-4 group-hover:bg-blue-500/30 transition-colors`}
                      >
                        <Upload size={24} className="text-blue-500" />
                      </div>
                      <h4
                        className={`text-base font-semibold ${textPrimary} mb-1`}
                      >
                        Upload File
                      </h4>
                      <p className={`text-sm ${textMuted}`}>
                        {uploading ? "Parsing..." : "PDF, Word, or TXT"}
                      </p>
                    </label>
                  </div>
                )}
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
