import React, { useState, useEffect } from "react";
import MonkeySprite from "../components/MonkeySprite";
import "../App.css";

function Leaderboard() {
  const [submissions, setSubmissions] = useState([]);
  const [message, setMessage] = useState("");

  useEffect(() => {
    loadLeaderboard();
  }, []);

  const loadLeaderboard = async () => {
    try {
      const response = await fetch("/api/leaderboard");
      const data = await response.json();
      setSubmissions(data);
    } catch (error) {
      console.error("Error loading leaderboard:", error);
    }
  };


  const upvote = async (id) => {
    try {
      const response = await fetch("/api/upvote", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id }),
      });

      const data = await response.json();

      if (response.ok) {
        setMessage("✓ Vote recorded!");
        loadLeaderboard();
        setTimeout(() => setMessage(""), 3000);
      } else {
        setMessage("✗ " + (data.error || "Failed to vote"));
      }
    } catch (error) {
      setMessage("✗ Network error");
    }
  };

  const formatDate = (timestamp) => {
    const date = new Date(timestamp * 1000);
    return date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  };

  return (
    <div
      style={{
        padding: "20px",
        paddingTop: "73px",
        maxWidth: "700px",
        margin: "0 auto",
        width: "100%",
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          marginBottom: "20px",
          gap: "16px",
        }}
      >
        <div>
          <h1 style={{ margin: 0 }}>Leaderboard</h1>
          <button
            onClick={loadLeaderboard}
            style={{
              marginTop: "10px",
              padding: "6px 14px",
              fontSize: "14px",
              cursor: "pointer",
              backgroundColor: "transparent",
              color: "#f0f0f0",
              border: "2px solid #555",
              borderRadius: "4px",
              display: "block",
            }}
          >
            Refresh
          </button>
        </div>

        <MonkeySprite animation="idle" />
      </div>

      {message && (
        <div
          style={{
            marginBottom: "20px",
            padding: "10px",
            backgroundColor: "#1a1a1a",
            border: "1px solid #444",
            borderRadius: "4px",
            color: message.startsWith("✓") ? "#ccc" : "#888",
          }}
        >
          {message}
        </div>
      )}

      <div>
        {submissions.length === 0 ? (
          <p style={{ textAlign: "center", padding: "40px", color: "#666" }}>
            No submissions yet. Be the first!
          </p>
        ) : (
          submissions.map((sub, index) => (
            <div
              key={sub.id}
              style={{
                padding: "20px",
                marginBottom: "15px",
                borderRadius: "8px",
                backgroundColor: "#1a1a1a",
                border: `1px solid ${index < 3 ? "#555" : "#333"}`,
                display: "flex",
                alignItems: "center",
                gap: "20px",
              }}
            >
              <div
                style={{
                  fontSize: "24px",
                  minWidth: "40px",
                  color:
                    index === 0
                      ? "#fff"
                      : index === 1
                        ? "#aaa"
                        : index === 2
                          ? "#888"
                          : "#555",
                }}
              >
                #{index + 1}
              </div>

              <div style={{ flex: 1 }}>
                <div
                  style={{
                    fontSize: "18px",
                    marginBottom: "8px",
                    wordBreak: "break-word",
                    color: "#f0f0f0",
                  }}
                >
                  "{sub.phrase}"
                </div>
                <div style={{ fontSize: "12px", color: "#666" }}>
                  {formatDate(sub.created_at)}
                </div>
              </div>

              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  gap: "8px",
                  minWidth: "80px",
                }}
              >
                <button
                  onClick={() => upvote(sub.id)}
                  style={{
                    padding: "8px 16px",
                    fontSize: "16px",
                    cursor: "pointer",
                    backgroundColor: "#f0f0f0",
                    color: "#111",
                    border: "none",
                    borderRadius: "4px",
                  }}
                >
                  +1
                </button>
                <div style={{ fontSize: "18px", color: "#ccc" }}>
                  {sub.votes}
                </div>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

export default Leaderboard;
