"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { useApiClient } from "../../lib/apiClient";
import { components } from "../../lib/gen";
import { useAudio } from "./AudioContext";

type Comment = components["schemas"]["CommentSchema"];

function CommentSkeleton() {
  return (
    <div className="space-y-2">
      <div className="flex items-start gap-3">
        <div className="w-8 h-8 rounded-full bg-foreground/10 animate-pulse" />
        <div className="flex-1 min-w-0 space-y-2">
          <div className="flex items-center gap-2">
            <div className="h-4 w-24 bg-foreground/10 rounded animate-pulse" />
            <div className="h-3 w-16 bg-foreground/10 rounded animate-pulse" />
          </div>
          <div className="space-y-1">
            <div className="h-4 w-full bg-foreground/10 rounded animate-pulse" />
            <div className="h-4 w-3/4 bg-foreground/10 rounded animate-pulse" />
          </div>
          <div className="flex items-center gap-4">
            <div className="h-3 w-12 bg-foreground/10 rounded animate-pulse" />
            <div className="h-3 w-16 bg-foreground/10 rounded animate-pulse" />
          </div>
        </div>
      </div>
    </div>
  );
}

export default function LyricsPanel() {
  const { currentSong } = useAudio();
  const [isExpanded, setIsExpanded] = useState(true);
  const [comments, setComments] = useState<Comment[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const apiClient = useApiClient();
  const fetchTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    const fetchComments = async () => {
      if (!currentSong?.id) return;

      setIsLoading(true);
      try {
        const { data } = await apiClient.GET("/api/gen/{clip_id}/comments", {
          params: {
            path: { clip_id: currentSong.id },
          },
        });
        // Sort comments by number of likes in descending order
        const sortedComments = (data?.results || []).sort(
          (a, b) => b.num_likes - a.num_likes
        );
        setComments(sortedComments);
      } catch (error) {
        console.error("Failed to fetch comments:", error);
      } finally {
        setIsLoading(false);
      }
    };

    // Clear any existing timeout
    if (fetchTimeoutRef.current) {
      clearTimeout(fetchTimeoutRef.current);
    }

    // Set a new timeout to fetch comments
    fetchTimeoutRef.current = setTimeout(fetchComments, 300);

    // Cleanup timeout on unmount or when currentSong changes
    return () => {
      if (fetchTimeoutRef.current) {
        clearTimeout(fetchTimeoutRef.current);
      }
    };
  }, [currentSong?.id, apiClient]);

  // Don't show panel if no song is playing
  if (!currentSong) {
    return null;
  }

  return (
    <div className="fixed right-4 top-20 bottom-32 w-80 z-50">
      <div className="h-full bg-white/90 dark:bg-black/90 backdrop-blur-md border border-black/[.08] dark:border-white/[.145] rounded-2xl shadow-lg overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-black/[.08] dark:border-white/[.145]">
          <div className="flex-1 min-w-0">
            <h3 className="font-semibold text-sm truncate">Comments</h3>
            <p className="text-xs text-foreground/60 truncate">
              {currentSong.title}
            </p>
          </div>
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="ml-2 p-1 rounded-lg hover:bg-black/[.05] dark:hover:bg-white/[.05] transition-colors"
          >
            <svg
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="currentColor"
              className={`transition-transform duration-200 ${
                isExpanded ? "rotate-180" : ""
              }`}
            >
              <path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z" />
            </svg>
          </button>
        </div>

        {/* Comments Content */}
        {isExpanded && (
          <div className="flex-1 overflow-y-auto">
            <div className="p-4">
              {isLoading ? (
                <div className="space-y-6">
                  <CommentSkeleton />
                  <CommentSkeleton />
                  <CommentSkeleton />
                </div>
              ) : comments.length === 0 ? (
                <div className="text-sm text-foreground/60 text-center py-4">
                  No comments yet
                </div>
              ) : (
                <div className="space-y-4">
                  {comments.map((comment) => (
                    <div key={comment.id} className="space-y-2">
                      <div className="flex items-start gap-3">
                        <Link
                          href={`/@${comment.user_handle}`}
                          className="w-8 h-8 rounded-full overflow-hidden hover:opacity-80 transition-opacity"
                        >
                          <img
                            src={comment.user_avatar_url}
                            alt={comment.user_display_name}
                            className="w-full h-full object-cover"
                          />
                        </Link>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <Link
                              href={`/@${comment.user_handle}`}
                              className="font-medium text-sm hover:text-foreground/80 transition-colors"
                            >
                              {comment.user_display_name}
                            </Link>
                            <span className="text-xs text-foreground/60">
                              {new Date(
                                comment.created_at
                              ).toLocaleDateString()}
                            </span>
                          </div>
                          <p className="text-sm text-foreground/80 mt-1">
                            {comment.content}
                          </p>
                          <div className="flex items-center gap-4 mt-2">
                            <button className="text-xs text-foreground/60 hover:text-foreground/80 flex items-center gap-1">
                              <svg
                                width="14"
                                height="14"
                                viewBox="0 0 24 24"
                                fill="currentColor"
                              >
                                <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
                              </svg>
                              {comment.num_likes}
                            </button>
                            {comment.num_replies ? (
                              <button className="text-xs text-foreground/60 hover:text-foreground/80">
                                {comment.num_replies} replies
                              </button>
                            ) : null}
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        )}

        {/* Collapsed State */}
        {!isExpanded && (
          <div className="p-4 text-center">
            <div className="text-xs text-foreground/50">
              Click to view comments
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
