"use client";

import { useAuthActions } from "@convex-dev/auth/react";
import { useQuery } from "convex/react";
import { api } from "@/convex/_generated/api";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { useState, useEffect, Suspense } from "react";
import { SongAtomRow } from "@/components/SongAtomRow";
import { ImageAtomCard } from "@/components/ImageAtomCard";
import { PlaybackProvider } from "@/contexts/PlaybackContext";
import { PlayBar } from "@/components/PlayBar";

type AtomType = "song" | "video" | "image" | "lyrics" | "webview" | "all";

const ATOM_TYPES: { value: AtomType; label: string }[] = [
  { value: "all", label: "All" },
  { value: "song", label: "Songs" },
  { value: "video", label: "Videos" },
  { value: "image", label: "Images" },
  { value: "lyrics", label: "Lyrics" },
  { value: "webview", label: "Webviews" },
];

function LibraryContent() {
  const { signOut } = useAuthActions();
  const router = useRouter();
  const searchParams = useSearchParams();
  const user = useQuery(api.users.current);

  // Get type and filters from URL
  const typeFromUrl = (searchParams.get("type") as AtomType) || "all";
  const onlyLikedFromUrl = searchParams.get("liked") === "true";

  const [selectedType, setSelectedType] = useState<AtomType>(typeFromUrl);
  const [onlyLiked, setOnlyLiked] = useState(onlyLikedFromUrl);

  // Update URL when filters change
  useEffect(() => {
    const params = new URLSearchParams();
    if (selectedType !== "all") {
      params.set("type", selectedType);
    }
    if (onlyLiked) {
      params.set("liked", "true");
    }
    const newUrl = params.toString() ? `/library?${params.toString()}` : "/library";
    router.replace(newUrl);
  }, [selectedType, onlyLiked, router]);

  // Sync state with URL on initial load
  useEffect(() => {
    setSelectedType(typeFromUrl);
    setOnlyLiked(onlyLikedFromUrl);
  }, [typeFromUrl, onlyLikedFromUrl]);

  // Query atoms with filters
  const atoms = useQuery(
    api.atoms.getMyAtoms,
    user
      ? {
          type: selectedType === "all" ? undefined : selectedType,
          onlyLiked: onlyLiked || undefined,
        }
      : "skip"
  );

  if (!user) {
    return (
      <main className="flex min-h-screen items-center justify-center">
        <div className="text-center">
          <p>Loading...</p>
        </div>
      </main>
    );
  }

  const songAtoms = atoms?.filter((atom) => atom.type === "song") || [];
  const imageAtoms = atoms?.filter((atom) => atom.type === "image") || [];
  const videoAtoms = atoms?.filter((atom) => atom.type === "video") || [];
  const lyricsAtoms = atoms?.filter((atom) => atom.type === "lyrics") || [];
  const webviewAtoms = atoms?.filter((atom) => atom.type === "webview") || [];

  return (
    <PlaybackProvider roomId={null}>
      <main className="min-h-screen bg-gray-50 dark:bg-gray-900">
        <nav className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex justify-between items-center h-16">
              <div className="flex items-center gap-6">
                <h1 className="text-xl font-bold">Suno Spaces</h1>
                <Link
                  href="/dashboard"
                  className="text-sm text-gray-600 dark:text-gray-400 hover:underline"
                >
                  Dashboard
                </Link>
                <Link
                  href="/library"
                  className="text-sm text-blue-600 dark:text-blue-400 font-semibold"
                >
                  Library
                </Link>
              </div>
              <div className="flex items-center gap-4">
                <Link
                  href="/settings"
                  className="text-sm text-blue-600 hover:underline"
                >
                  Settings
                </Link>
                <span className="text-sm text-gray-600 dark:text-gray-400">
                  {user.profile?.displayName || user.user?.name || user.user?.email}
                </span>
                <button
                  onClick={() => signOut()}
                  className="text-sm text-red-600 hover:text-red-700"
                >
                  Sign Out
                </button>
              </div>
            </div>
          </div>
        </nav>

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="mb-6">
            <h2 className="text-3xl font-bold mb-2">My Library</h2>
            <p className="text-gray-600 dark:text-gray-400">
              All atoms you&apos;ve created
            </p>
          </div>

          {/* Filters */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4 mb-6">
            <div className="flex items-center gap-4">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={onlyLiked}
                  onChange={(e) => setOnlyLiked(e.target.checked)}
                  className="w-4 h-4 rounded border-gray-300 dark:border-gray-600"
                />
                <span className="text-sm font-medium">Show only liked</span>
              </label>
            </div>
          </div>

          {/* Type tabs */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow mb-6">
            <div className="flex border-b border-gray-200 dark:border-gray-700 overflow-x-auto">
              {ATOM_TYPES.map((type) => (
                <button
                  key={type.value}
                  onClick={() => setSelectedType(type.value)}
                  className={`px-6 py-3 font-medium text-sm whitespace-nowrap transition-colors ${
                    selectedType === type.value
                      ? "border-b-2 border-blue-600 text-blue-600 dark:text-blue-400"
                      : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
                  }`}
                >
                  {type.label}
                </button>
              ))}
            </div>

            {/* Content */}
            <div className="p-6">
              {!atoms ? (
                <div className="text-center py-12 text-gray-500">
                  <p>Loading...</p>
                </div>
              ) : atoms.length === 0 ? (
                <div className="text-center py-12 text-gray-500">
                  <p>No atoms found with the current filters.</p>
                </div>
              ) : (
                <div className="space-y-6">
                  {/* Songs */}
                  {(selectedType === "all" || selectedType === "song") &&
                    songAtoms.length > 0 && (
                      <div>
                        {selectedType === "all" && (
                          <h3 className="text-lg font-semibold mb-3">
                            Songs ({songAtoms.length})
                          </h3>
                        )}
                        <div className="space-y-2">
                          {songAtoms.map((atom) => (
                            <SongAtomRow
                              key={atom._id}
                              atom={atom}
                              currentUserId={user.user?._id}
                            />
                          ))}
                        </div>
                      </div>
                    )}

                  {/* Images */}
                  {(selectedType === "all" || selectedType === "image") &&
                    imageAtoms.length > 0 && (
                      <div>
                        {selectedType === "all" && (
                          <h3 className="text-lg font-semibold mb-3">
                            Images ({imageAtoms.length})
                          </h3>
                        )}
                        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                          {imageAtoms.map((atom) => (
                            <ImageAtomCard
                              key={atom._id}
                              atom={atom}
                              currentUserId={user.user?._id}
                            />
                          ))}
                        </div>
                      </div>
                    )}

                  {/* Videos */}
                  {(selectedType === "all" || selectedType === "video") &&
                    videoAtoms.length > 0 && (
                      <div>
                        {selectedType === "all" && (
                          <h3 className="text-lg font-semibold mb-3">
                            Videos ({videoAtoms.length})
                          </h3>
                        )}
                        <div className="space-y-2">
                          {videoAtoms.map((atom) => (
                            <div
                              key={atom._id}
                              className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg"
                            >
                              <p className="text-sm">Video: {atom._id}</p>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                  {/* Lyrics */}
                  {(selectedType === "all" || selectedType === "lyrics") &&
                    lyricsAtoms.length > 0 && (
                      <div>
                        {selectedType === "all" && (
                          <h3 className="text-lg font-semibold mb-3">
                            Lyrics ({lyricsAtoms.length})
                          </h3>
                        )}
                        <div className="space-y-2">
                          {lyricsAtoms.map((atom) => (
                            <div
                              key={atom._id}
                              className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg"
                            >
                              <p className="text-sm">Lyrics: {atom._id}</p>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                  {/* Webviews */}
                  {(selectedType === "all" || selectedType === "webview") &&
                    webviewAtoms.length > 0 && (
                      <div>
                        {selectedType === "all" && (
                          <h3 className="text-lg font-semibold mb-3">
                            Webviews ({webviewAtoms.length})
                          </h3>
                        )}
                        <div className="space-y-2">
                          {webviewAtoms.map((atom) => (
                            <div
                              key={atom._id}
                              className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg"
                            >
                              <p className="text-sm">Webview: {atom._id}</p>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                </div>
              )}
            </div>
          </div>
        </div>

        <PlayBar roomId={null} />
      </main>
    </PlaybackProvider>
  );
}

export default function LibraryPage() {
  return (
    <Suspense fallback={
      <main className="flex min-h-screen items-center justify-center">
        <div className="text-center">
          <p>Loading...</p>
        </div>
      </main>
    }>
      <LibraryContent />
    </Suspense>
  );
}
