"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";

interface ActivityItem {
  id: string;
  projectId: string;
  projectName: string;
  action: string;
  type: "atlas" | "build" | "deploy" | "user";
  createdAt: string;
}

function timeAgo(dateStr: string): string {
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return "—";
  const diff = (Date.now() - date.getTime()) / 1000;
  if (diff < 60) return "just now";
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  const days = Math.floor(diff / 86400);
  if (days === 1) return "Yesterday";
  if (days < 7) return `${days}d ago`;
  return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

function typeColor(t: string) {
  return t === "atlas" ? "#1a1a1a" : t === "build" ? "#3d5afe" : t === "deploy" ? "#2e7d32" : "#8a8478";
}

const FILTERS = [
  { id: "all",    label: "All" },
  { id: "atlas",  label: "Vibn" },
  { id: "build",  label: "Builds" },
  { id: "deploy", label: "Deploys" },
  { id: "user",   label: "You" },
];

export default function ActivityPage() {
  const params = useParams();
  const workspace = params.workspace as string;
  const [filter, setFilter] = useState("all");
  const [items, setItems] = useState<ActivityItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/activity")
      .then((r) => r.json())
      .then((d) => setItems(d.items ?? []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const filtered = filter === "all" ? items : items.filter((a) => a.type === filter);

  return (
    <div
      className="vibn-enter"
      style={{ padding: "44px 52px", maxWidth: 720, fontFamily: "var(--font-inter), ui-sans-serif, sans-serif" }}
    >
      <h1 style={{
        fontFamily: "var(--font-lora), ui-serif, serif", fontSize: "1.9rem",
        fontWeight: 400, color: "#1a1a1a", letterSpacing: "-0.03em", marginBottom: 4,
      }}>
        Activity
      </h1>
      <p style={{ fontSize: "0.82rem", color: "#a09a90", marginBottom: 28 }}>
        Everything happening across your projects
      </p>

      {/* Filter pills */}
      <div style={{ display: "flex", gap: 4, marginBottom: 24 }}>
        {FILTERS.map((f) => (
          <button
            key={f.id}
            onClick={() => setFilter(f.id)}
            style={{
              padding: "6px 14px", borderRadius: 6, border: "none",
              background: filter === f.id ? "#1a1a1a" : "#fff",
              color: filter === f.id ? "#fff" : "#6b6560",
              fontSize: "0.75rem", fontWeight: 600, transition: "all 0.12s",
              cursor: "pointer", fontFamily: "var(--font-inter), ui-sans-serif, sans-serif",
            }}
          >
            {f.label}
          </button>
        ))}
      </div>

      {loading && (
        <p style={{ fontSize: "0.82rem", color: "#b5b0a6" }}>Loading…</p>
      )}

      {/* Timeline */}
      {!loading && filtered.length === 0 && (
        <p style={{ fontSize: "0.82rem", color: "#b5b0a6" }}>No activity yet.</p>
      )}

      {!loading && filtered.length > 0 && (
        <div style={{ position: "relative", paddingLeft: 24 }}>
          {/* Vertical line */}
          <div style={{
            position: "absolute", left: 8, top: 8, bottom: 8,
            width: 1, background: "#e8e4dc",
          }} />

          {filtered.map((item, i) => (
            <div
              key={item.id}
              className="vibn-enter"
              style={{
                display: "flex", gap: 14, marginBottom: 4,
                padding: "12px 16px", borderRadius: 8,
                transition: "background 0.12s", position: "relative",
                animationDelay: `${i * 0.03}s`,
              }}
              onMouseEnter={(e) => (e.currentTarget.style.background = "#fff")}
              onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
            >
              {/* Timeline dot */}
              <div style={{
                position: "absolute", left: -20, top: 18,
                width: 9, height: 9, borderRadius: "50%",
                background: typeColor(item.type),
                border: "2px solid #f6f4f0",
              }} />

              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
                  <Link
                    href={`/${workspace}/project/${item.projectId}/overview`}
                    style={{
                      fontSize: "0.82rem", fontWeight: 600, color: "#1a1a1a",
                      textDecoration: "none",
                    }}
                    onMouseEnter={(e) => (e.currentTarget.style.textDecoration = "underline")}
                    onMouseLeave={(e) => (e.currentTarget.style.textDecoration = "none")}
                  >
                    {item.projectName}
                  </Link>
                  <span style={{ fontSize: "0.68rem", color: "#b5b0a6" }}>·</span>
                  <span style={{ fontSize: "0.72rem", color: "#b5b0a6" }}>{timeAgo(item.createdAt)}</span>
                </div>
                <div style={{ fontSize: "0.82rem", color: "#6b6560", lineHeight: 1.5 }}>
                  {item.action}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
