"use client";

import { useState } from "react";

export default function StatsDashboard() {
  const [authenticated, setAuthenticated] = useState(false);
  const [password, setPassword] = useState("");
  const [stats, setStats] = useState<{
    views: number;
    projectsViewed: Record<string, number>;
  } | null>(null);
  const [error, setError] = useState("");

  const handleLogin = () => {
    // Simple password check. Replace with secure authentication.
    if (password === "admin123") {
      setAuthenticated(true);
      fetchStats();
    } else {
      setError("Incorrect password.");
    }
  };

  const fetchStats = async () => {
    try {
      const res = await fetch("/api/stats");
      const data = await res.json();
      setStats(data);
    } catch (err) {
      console.error(err);
      setError("Failed to fetch stats.");
    }
  };

  if (!authenticated) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-100 dark:bg-gray-800">
        <div className="p-10 bg-white dark:bg-gray-700 rounded shadow-md">
          <h2 className="text-2xl font-bold mb-4 text-gray-800 dark:text-white">
            Admin Login
          </h2>
          {error && <p className="text-red-500">{error}</p>}
          <input
            type="password"
            placeholder="Enter Password"
            className="w-full p-2 border rounded mb-4 dark:bg-gray-600 dark:border-gray-500 dark:text-white"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          <button
            onClick={handleLogin}
            className="w-full p-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            Login
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="p-10 bg-gray-100 dark:bg-gray-800 min-h-screen">
      <h1 className="text-3xl font-bold text-gray-800 dark:text-white">
        Statistics Dashboard
      </h1>
      {stats ? (
        <div className="mt-6">
          <p className="text-lg text-gray-700 dark:text-gray-300">
            Total Views: {stats.views}
          </p>
          <h2 className="text-2xl font-semibold mt-4 text-gray-800 dark:text-white">
            Project Views:
          </h2>
          <ul className="list-disc pl-5 mt-2 text-gray-700 dark:text-gray-300">
            {Object.entries(stats.projectsViewed).map(([projectId, count]) => (
              <li key={projectId}>
                Project ID {projectId}: {count} view{count !== 1 ? "s" : ""}
              </li>
            ))}
          </ul>
        </div>
      ) : (
        <p className="mt-4 text-gray-700 dark:text-gray-300">
          Loading statistics...
        </p>
      )}
    </div>
  );
}
