"use client";

import { useParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { useApiClient } from "../../../lib/apiClient";
import { components } from "../../../lib/gen";
import { useAudio } from "../../components/AudioContext";
import LyricsPanel from "../../components/LyricsPanel";
import Playbar from "../../components/Playbar";
import SongFeed from "../../components/SongFeed";
import SongCard from "../../SongCard";

interface Song {
  id: string;
  title: string;
  display_name: string;
  handle: string;
  audio_url: string;
  image_url?: string;
  video_cover_url?: string;
  avatar_image_url?: string;
  caption?: string;
  created_at: string;
  upvote_count: number;
  comment_count: number;
  play_count: number;
  display_tags?: string;
  source?: "trending" | "following" | "profile";
  metadata?: {
    duration?: number;
    prompt?: string;
  };
}

// Use the ProfileInfoSchema from gen.ts
type Profile = components["schemas"]["ProfileInfoSchema"];

interface ProfileResponse {
  profile: Profile;
  clips: Song[];
}

export default function ProfilePage() {
  const params = useParams();
  const creatorName = params.creator_name as string;

  const [profileData, setProfileData] = useState<ProfileResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [collapsed, setCollapsed] = useState(false);
  const apiClient = useApiClient();
  const { currentSong, playSong, audioRef } = useAudio();
  const songRefs = useRef<(HTMLDivElement | null)[]>([]);

  // Ensure page starts at top when navigating to profile
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [creatorName]);

  // Collapse header on scroll with debounce
  useEffect(() => {
    let debounceTimeout: NodeJS.Timeout | null = null;
    const handleScroll = () => {
      if (debounceTimeout) clearTimeout(debounceTimeout);
      debounceTimeout = setTimeout(() => {
        setCollapsed(window.scrollY > 60);
      }, 100);
    };
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
      if (debounceTimeout) clearTimeout(debounceTimeout);
    };
  }, []);

  useEffect(() => {
    const loadProfile = async () => {
      try {
        const { data, error: apiError } = await apiClient.GET(
          "/api/profiles/{handle}",
          {
            params: {
              path: { handle: creatorName },
              query: {
                page: 1,
                playlists_sort_by: "upvote_count",
                clips_sort_by: "upvote_count",
              },
            },
          }
        );

        if (apiError) {
          throw new Error(`Failed to fetch profile: ${apiError}`);
        }

        if (!data) {
          throw new Error("No profile data received");
        }

        // Add source field to songs
        const songsWithSource = data.clips.map((song: any) => ({
          ...song,
          source: "profile" as const,
        }));

        setProfileData({
          profile: data,
          clips: songsWithSource,
        });
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load profile");
      } finally {
        setLoading(false);
      }
    };

    if (creatorName) {
      loadProfile();
    }
  }, [creatorName, apiClient]);

  const { profile, clips } = profileData || { profile: null, clips: [] };
  console.log("here", profileData);

  // Play next song and scroll to it
  const playNextSong = () => {
    if (!clips || !currentSong) return;
    const idx = clips.findIndex((s) => s.id === currentSong.id);
    if (idx !== -1 && idx < clips.length - 1) {
      const nextSong = clips[idx + 1];
      playSong(nextSong);
      // Scroll next card into view
      setTimeout(() => {
        songRefs.current[idx + 1]?.scrollIntoView({
          behavior: "smooth",
          block: "center",
        });
      }, 200);
    }
  };

  // Attach onEnded handler
  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    const handleEnded = () => playNextSong();
    audio.addEventListener("ended", handleEnded);
    return () => {
      audio.removeEventListener("ended", handleEnded);
    };
  }, [audioRef, currentSong, clips]);

  return (
    <>
      <div className="min-h-screen bg-gradient-to-b from-background to-background/95">
        {/* Profile Header */}
        {profile && (
          <div
            className={
              "sticky top-16 z-40 bg-background/80 backdrop-blur-md border-b border-black/[.08] dark:border-white/[.145] transition-all duration-300"
            }
          >
            <div
              className={`max-w-2xl pl-8 pr-4 transition-all duration-300 ${
                collapsed ? "py-2" : "py-6"
              }`}
            >
              {collapsed ? (
                <div className="flex items-center gap-3 min-h-[40px]">
                  {profile.avatar_image_url && (
                    <img
                      src={profile.avatar_image_url}
                      alt={profile.display_name || "Profile"}
                      className="w-8 h-8 rounded-full object-cover border border-white/20"
                    />
                  )}
                  <span className="font-semibold text-base text-foreground truncate">
                    {profile.display_name || "Anonymous"}
                  </span>
                  <span className="text-xs text-foreground/60 truncate">
                    @{profile.handle}
                  </span>
                  <span className="text-xs text-foreground/40 ml-2">
                    {profile.num_total_clips.toLocaleString()} songs
                  </span>
                  {profile.is_following && (
                    <span className="text-blue-500 text-xs ml-2">
                      Following
                    </span>
                  )}
                </div>
              ) : (
                <div className="flex items-center gap-5 min-h-[64px]">
                  {profile.avatar_image_url && (
                    <img
                      src={profile.avatar_image_url}
                      alt={profile.display_name || "Profile"}
                      className="w-16 h-16 rounded-full object-cover border border-white/20"
                    />
                  )}
                  <span className="font-semibold text-xl text-foreground truncate">
                    {profile.display_name || "Anonymous"}
                  </span>
                  <span className="text-sm text-foreground/60 truncate">
                    @{profile.handle}
                  </span>
                  <span className="text-sm text-foreground/40 ml-2">
                    {profile.num_total_clips.toLocaleString()} songs
                  </span>
                  {profile.is_following && (
                    <span className="text-blue-500 text-sm ml-2">
                      Following
                    </span>
                  )}
                </div>
              )}
            </div>
          </div>
        )}

        {/* Feed */}
        <div className="max-w-2xl pl-8 pr-4 py-6 pb-32">
          <SongFeed
            songs={clips}
            loading={loading}
            error={error}
            currentSong={currentSong}
            playSong={playSong}
            SongComponent={SongCard}
            emptyMessage={
              profile
                ? "This creator hasn't shared any songs yet."
                : "Profile not found"
            }
          />
        </div>
      </div>

      {/* Floating Lyrics Panel */}
      <LyricsPanel />

      <Playbar />
    </>
  );
}
