"use client";

import { useCallback, useEffect, useState } from "react";
import { useApiClient } from "../../lib/apiClient";
import { useAudio } from "../components/AudioContext";
import LyricsPanel from "../components/LyricsPanel";
import Playbar from "../components/Playbar";
import SongFeed from "../components/SongFeed";
import SongCard from "../SongCard";

export default function MyLibrary() {
  const [songs, setSongs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [likedOnly, setLikedOnly] = useState(false);
  const [createLoading, setCreateLoading] = useState(false);
  const apiClient = useApiClient();

  // Fetch songs function
  const fetchSongs = useCallback(
    async (isInitialLoad = true) => {
      try {
        if (isInitialLoad) {
          setLoading(true);
          setError(null);
        }
        const response = await apiClient.GET("/api/project/{project_id}", {
          params: {
            path: { project_id: "default" },
            query: {
              is_liked: likedOnly ? true : undefined,
              hide_disliked: true,
              hide_gen_stems: true,
              hide_studio_clips: true,
              page: 1,
            },
          },
        });
        const projectClips = response.data?.project_clips || [];
        const clips = projectClips.map((pc: any) => pc.clip).filter(Boolean);
        setSongs(clips.reverse());
        if (clips.length === 0 && isInitialLoad) {
          setError("No songs found in your library.");
        }

        // Check if any songs are still loading
        const hasLoadingSongs = clips.some(
          (clip: any) =>
            clip.status &&
            clip.status !== "complete" &&
            clip.status !== "streaming"
        );

        return hasLoadingSongs;
      } catch (err) {
        if (isInitialLoad) {
          setError("Failed to load your library.");
        }
        return false;
      } finally {
        if (isInitialLoad) {
          setLoading(false);
        }
      }
    },
    [apiClient, likedOnly]
  );

  const handleCreate = async () => {
    setCreateLoading(true);
    try {
      const response = await apiClient.POST("/api/generate/v2-web/", {
        body: {
          gpt_description_prompt:
            "song about love on a sunny day (use abstract metaphors)",
          prompt: "",
          generation_type: "TEXT",
          tags: "neo-soul, post-industrial",
          negative_tags: "",
          mv: "chirp-auk",
          title: "sunny day",
          continue_clip_id: null,
          continue_at: 0,
          continued_aligned_prompt: null,
          infill_start_s: null,
          infill_end_s: null,
          task: null,
          override_fields: ["tags"],
          persona_id: null,
          artist_clip_id: null,
          artist_start_s: null,
          artist_end_s: null,
          cover_clip_id: null,
          metadata: {
            create_mode: "custom",
            user_tier: "e1235dd7-9f4d-4738-aeb2-1470466cba27",
            lyrics_model: "remi-v1",
            control_sliders: {
              style_weight: 0.65,
              weirdness_constraint: 0.81,
            },
            can_control_sliders: ["weirdness_constraint", "style_weight"],
          },
        },
      });
      console.log("Create response:", response);

      // Refetch songs after creation
      await fetchSongs(true);
    } catch (err) {
      console.error("Failed to create song:", err);
    } finally {
      setCreateLoading(false);
    }
  };

  // Initial fetch and polling effect
  useEffect(() => {
    let intervalId: NodeJS.Timeout | null = null;

    const startFetching = async () => {
      // Initial fetch
      const hasLoadingSongs = await fetchSongs(true);

      // If there are loading songs, start polling
      if (hasLoadingSongs) {
        intervalId = setInterval(async () => {
          const stillLoading = await fetchSongs(false);
          if (!stillLoading && intervalId) {
            clearInterval(intervalId);
            intervalId = null;
          }
        }, 4000);
      }
    };

    startFetching();

    // Cleanup
    return () => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    };
  }, [fetchSongs]);

  // Scroll to bottom when songs load or filter changes
  useEffect(() => {
    if (!loading && songs.length > 0) {
      // Small delay to ensure DOM is fully rendered
      setTimeout(() => {
        window.scrollTo({
          top: document.body.scrollHeight,
          behavior: "instant",
        });
      }, 100);
    }
  }, [loading, songs, likedOnly]);

  const { currentSong, playSong } = useAudio();

  return (
    <>
      {/* Fixed Header */}
      <div className="sticky top-16 z-40 bg-background/80 backdrop-blur-md border-b border-black/[.08] dark:border-white/[.145]">
        <div className="max-w-2xl pl-8 pr-4 py-4 flex items-center justify-between gap-4">
          <h1 className="text-2xl font-bold text-foreground">My Library</h1>
          <div className="flex items-center gap-3">
            <label className="flex items-center gap-2 cursor-pointer select-none">
              <span className="text-sm text-foreground/70">Liked Only</span>
              <input
                type="checkbox"
                checked={likedOnly}
                onChange={() => setLikedOnly((v) => !v)}
                className="accent-blue-500 w-5 h-5"
                aria-label="Toggle liked only"
              />
            </label>
            <button
              onClick={handleCreate}
              disabled={createLoading}
              className={`ml-4 px-4 py-2 rounded-lg font-semibold text-white bg-blue-600 hover:bg-blue-700 transition-colors ${
                createLoading ? "opacity-60 cursor-not-allowed" : ""
              }`}
            >
              {createLoading ? "Creating..." : "Create"}
            </button>
          </div>
        </div>
      </div>

      {/* Scrollable Content */}
      <div className="min-h-screen bg-gradient-to-b from-background to-background/95">
        {/* Feed */}
        <div className="max-w-2xl pl-8 pr-4 py-6 pb-32">
          <SongFeed
            songs={songs}
            loading={loading}
            error={error}
            currentSong={currentSong}
            playSong={playSong}
            SongComponent={SongCard}
          />
        </div>
      </div>

      <LyricsPanel />
      <Playbar />
    </>
  );
}
