import { useRef } from "react";
import { useParams } from "react-router-dom";
import { useProjectStats } from "../hooks/useProjects";
import { useExternalChangeSound } from "../hooks/useExternalChangeSound";
import StatusBadge from "./StatusBadge";

export default function Dashboard() {
  const { id } = useParams<{ id: string }>();
  const { data: stats } = useProjectStats(id);
  const mutationGuard = useRef(false);

  useExternalChangeSound(stats, "zug-zug", mutationGuard);

  if (!stats) {
    return <p className="text-[#8a8672]">Loading...</p>;
  }

  const totalFeatures = Object.values(stats.feature_counts).reduce(
    (a, b) => a + b,
    0
  );
  const totalTasks = Object.values(stats.task_counts).reduce(
    (a, b) => a + b,
    0
  );
  const testTotal = Object.values(stats.test_counts).reduce(
    (a, b) => a + b,
    0
  );
  const passRate =
    testTotal > 0
      ? Math.round(((stats.test_counts["pass"] || 0) / testTotal) * 100)
      : 0;

  const statCards = [
    {
      label: "Features",
      value: totalFeatures,
      sub: `${stats.feature_counts["done"] || 0} done`,
    },
    {
      label: "Tasks",
      value: totalTasks,
      sub: `${stats.task_counts["done"] || 0} done`,
    },
    { label: "Work Logs", value: stats.total_logs, sub: "total entries" },
    {
      label: "Test Pass Rate",
      value: `${passRate}%`,
      sub: `${testTotal} results`,
    },
  ];

  return (
    <div>
      <h1 className="mb-6 text-2xl font-bold">{id}</h1>

      <div className="mb-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {statCards.map((card) => (
          <div
            key={card.label}
            className="rounded-lg border border-[#2e3625] bg-[#1a1f14] p-5"
          >
            <p className="text-sm text-[#8a8672]">{card.label}</p>
            <p className="mt-1 text-2xl font-bold">{card.value}</p>
            <p className="mt-1 text-xs text-[#5c5a4a]">{card.sub}</p>
          </div>
        ))}
      </div>

      <h2 className="mb-4 text-lg font-semibold">Recent Activity</h2>
      {stats.recent_logs.length === 0 ? (
        <p className="text-[#8a8672]">No work logs yet.</p>
      ) : (
        <div className="space-y-3">
          {stats.recent_logs.map((log) => (
            <div
              key={log.id}
              className="rounded-lg border border-[#2e3625] bg-[#1a1f14] p-4"
            >
              <div className="flex items-start justify-between">
                <p className="text-sm">{log.summary}</p>
                {log.test_result && (
                  <span
                    className={`ml-2 inline-block rounded-full px-2 py-0.5 text-xs font-medium ${
                      log.test_result === "pass"
                        ? "bg-emerald-900 text-emerald-300"
                        : log.test_result === "fail"
                          ? "bg-red-900 text-red-300"
                          : "bg-gray-800 text-gray-400"
                    }`}
                  >
                    {log.test_result}
                  </span>
                )}
              </div>
              <div className="mt-2 flex items-center gap-3 text-xs text-[#5c5a4a]">
                <StatusBadge status={`task #${log.task_id}`} />
                <span>
                  {new Date(log.created_at).toLocaleString()}
                </span>
                {log.files_changed && (
                  <span className="truncate">{log.files_changed}</span>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
