"use client";

import { useEffect, useState, useCallback } from "react";
import Link from "next/link";
import type { Project } from "@/lib/types";
import { LogoutButton } from "./components/LogoutButton";

function StatusBadge({ phase, running, stopping }: { phase: string; running: boolean; stopping?: boolean }) {
  if (running && stopping) {
    return (
      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-warning/15 text-warning">
        <span className="w-1.5 h-1.5 rounded-full bg-warning animate-pulse" />
        Stopping
      </span>
    );
  }
  if (!running && !phase) {
    return (
      <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-surface-overlay text-text-muted">
        <span className="w-1.5 h-1.5 rounded-full bg-text-muted" />
        Stopped
      </span>
    );
  }
  if (!running && phase) {
    const isError = phase.includes("fail") || phase.includes("error") || phase.includes("broken");
    return (
      <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${isError ? "bg-error/15 text-error" : "bg-surface-overlay text-text-muted"}`}>
        <span className={`w-1.5 h-1.5 rounded-full ${isError ? "bg-error" : "bg-text-muted"}`} />
        {phase}
      </span>
    );
  }

  const configs: Record<string, { bg: string; text: string; dot: string; anim?: boolean }> = {
    building: { bg: "bg-accent/15", text: "text-accent-hover", dot: "bg-accent", anim: true },
    pushing: { bg: "bg-info/15", text: "text-info", dot: "bg-info", anim: true },
    idle: { bg: "bg-warning/15", text: "text-warning", dot: "bg-warning" },
    error: { bg: "bg-error/15", text: "text-error", dot: "bg-error" },
    stopped: { bg: "bg-surface-overlay", text: "text-text-muted", dot: "bg-text-muted" },
    "agent-failing": { bg: "bg-error/15", text: "text-error", dot: "bg-error", anim: true },
    "agent-broken": { bg: "bg-error/15", text: "text-error", dot: "bg-error" },
    "push-failed": { bg: "bg-warning/15", text: "text-warning", dot: "bg-warning" },
    "iteration-complete": { bg: "bg-success/15", text: "text-success", dot: "bg-success" },
  };
  const style = configs[phase] || configs.building;
  return (
    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${style.bg} ${style.text}`}>
      <span className={`w-1.5 h-1.5 rounded-full ${style.dot} ${style.anim ? "animate-pulse-dot" : ""}`} />
      {phase || "unknown"}
    </span>
  );
}

function ProjectCard({ project, onAction }: { project: Project; onAction: (id: string, action: string) => void }) {
  const { initiativeCounts: counts } = project;
  const progressPct =
    counts.tasksTotal > 0 ? Math.round((counts.tasksExecuted / counts.tasksTotal) * 100) : 0;
  const proc = project.process;

  return (
    <Link href={`/projects/${project.id}`} className="block group">
      <div className="rounded-xl border border-border bg-surface-raised p-5 transition-all duration-200 hover:border-accent/40 hover:bg-surface-hover hover:shadow-lg hover:shadow-accent/5">
        <div className="flex items-start justify-between mb-3">
          <div className="min-w-0 flex-1">
            <h3 className="text-base font-semibold text-text-primary truncate group-hover:text-accent-hover transition-colors">
              {project.name}
            </h3>
            <p className="text-xs text-text-muted mt-0.5 truncate font-mono">{project.projectDir}</p>
          </div>
          <StatusBadge phase={project.status?.phase || ""} running={proc.running} stopping={proc.stopping} />
        </div>

        {project.scopeSnippet && (
          <p className="text-sm text-text-secondary mb-4 line-clamp-2">{project.scopeSnippet}</p>
        )}

        <div className="space-y-3">
          {counts.tasksTotal > 0 && (
            <div>
              <div className="flex items-center justify-between mb-1.5">
                <span className="text-xs text-text-muted">Tasks</span>
                <span className="text-xs font-medium text-text-secondary">
                  {counts.tasksExecuted}/{counts.tasksTotal}
                </span>
              </div>
              <div className="h-1.5 bg-surface-overlay rounded-full overflow-hidden">
                <div
                  className="h-full bg-gradient-to-r from-accent to-accent-hover rounded-full transition-all duration-500"
                  style={{ width: `${progressPct}%` }}
                />
              </div>
            </div>
          )}

          <div className="grid grid-cols-4 gap-2">
            <StatBox value={counts.tasksExecuted} label="Done" color="text-success" />
            <StatBox value={counts.tasksTotal} label="Tasks" color="text-info" />
            <StatBox value={counts.initiativeCount} label="Initiatives" color="text-warning" />
            <StatBox value={project.screenshotCount} label="Shots" color="text-text-secondary" />
          </div>
        </div>

        <div className="flex items-center justify-between mt-4 pt-3 border-t border-border-subtle">
          <div className="flex items-center gap-3 text-xs text-text-muted flex-wrap">
            {proc.running && proc.pid && (
              <span className="text-success font-medium">PID {proc.pid}</span>
            )}
            {!proc.running && proc.pid && (
              <span className="text-error font-medium">PID {proc.pid} (dead)</span>
            )}
            {proc.running && proc.uptime && (
              <span title="Daemon process uptime">Up {proc.uptime}</span>
            )}
            {project.status?.iteration ? <span>Iter #{project.status.iteration}</span> : null}
            {project.gitBranch && <span className="font-mono">{project.gitBranch}</span>}
          </div>
          <div className="flex items-center gap-1.5" onClick={(e) => { e.preventDefault(); e.stopPropagation(); }}>
            {!proc.running && (
              <button onClick={() => onAction(project.id, "start")} className="px-2.5 py-1 rounded-md text-[11px] font-medium bg-success/10 text-success hover:bg-success/20 transition-colors">Start</button>
            )}
            {proc.running && !proc.stopping && (
              <button onClick={() => onAction(project.id, "stop")} className="px-2.5 py-1 rounded-md text-[11px] font-medium bg-warning/10 text-warning hover:bg-warning/20 transition-colors">Stop</button>
            )}
            {proc.running && (
              <button onClick={() => onAction(project.id, "kill")} className="px-2.5 py-1 rounded-md text-[11px] font-medium bg-error/10 text-error hover:bg-error/20 transition-colors">Kill</button>
            )}
          </div>
        </div>
      </div>
    </Link>
  );
}

function StatBox({ value, label, color }: { value: number; label: string; color: string }) {
  return (
    <div className="text-center p-2 rounded-lg bg-surface-overlay/50">
      <div className={`text-lg font-semibold ${color}`}>{value}</div>
      <div className="text-[10px] text-text-muted uppercase tracking-wider">{label}</div>
    </div>
  );
}

function AggregateStats({ projects }: { projects: Project[] }) {
  const running = projects.filter((p) => p.process.running).length;
  const stopped = projects.length - running;
  const totalInitiatives = projects.reduce((s, p) => s + p.initiativeCounts.initiativeCount, 0);
  const totalTasks = projects.reduce((s, p) => s + p.initiativeCounts.tasksTotal, 0);
  const tasksDone = projects.reduce((s, p) => s + p.initiativeCounts.tasksExecuted, 0);

  return (
    <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
      <div className="rounded-lg border border-border-subtle bg-surface-raised p-4">
        <div className="text-2xl font-bold text-success">{running}<span className="text-sm font-normal text-text-muted">/{projects.length}</span></div>
        <div className="text-xs text-text-muted mt-1">Running</div>
      </div>
      <div className="rounded-lg border border-border-subtle bg-surface-raised p-4">
        <div className={`text-2xl font-bold ${stopped > 0 ? "text-error" : "text-text-muted"}`}>{stopped}</div>
        <div className="text-xs text-text-muted mt-1">Stopped / Dead</div>
      </div>
      <div className="rounded-lg border border-border-subtle bg-surface-raised p-4">
        <div className="text-2xl font-bold text-accent-hover">{totalInitiatives}</div>
        <div className="text-xs text-text-muted mt-1">Initiatives</div>
      </div>
      <div className="rounded-lg border border-border-subtle bg-surface-raised p-4">
        <div className="text-2xl font-bold text-info">{tasksDone}<span className="text-sm font-normal text-text-muted">/{totalTasks}</span></div>
        <div className="text-xs text-text-muted mt-1">Tasks done</div>
      </div>
    </div>
  );
}

export default function Dashboard() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchProjects = useCallback(async () => {
    try {
      const res = await fetch("/api/projects");
      if (!res.ok) throw new Error("Failed to fetch");
      setProjects(await res.json());
      setError(null);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Unknown error");
    } finally {
      setLoading(false);
    }
  }, []);

  async function handleAction(projectId: string, action: string) {
    if (action !== "start" && !confirm(`Are you sure you want to ${action} ${projectId}?`)) return;
    const res = await fetch(`/api/projects/${projectId}/process`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action }) });
    const data = await res.json();
    if (!res.ok) alert(`Error: ${data.error}`);
    fetchProjects();
  }

  useEffect(() => {
    fetchProjects();
    const interval = setInterval(fetchProjects, 8_000);
    return () => clearInterval(interval);
  }, [fetchProjects]);

  return (
    <div className="min-h-screen">
      <header className="sticky top-0 z-40 border-b border-border bg-surface/80 backdrop-blur-xl">
        <div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-accent to-purple-500 flex items-center justify-center">
              <svg className="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z" />
              </svg>
            </div>
            <div>
              <h1 className="text-lg font-bold tracking-tight">Autobuilder Dashboard</h1>
              <p className="text-[11px] text-text-muted -mt-0.5">Process Monitor</p>
            </div>
          </div>
          <div className="flex items-center gap-4">
            <button onClick={fetchProjects} className="p-2 rounded-lg text-text-muted hover:text-text-primary hover:bg-surface-hover transition-colors" title="Refresh">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182" />
              </svg>
            </button>
            <span className="text-xs text-text-muted">{projects.length} projects</span>
            <LogoutButton />
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-6 py-6 space-y-6">
        {loading ? (
          <div className="flex items-center justify-center py-32">
            <div className="w-6 h-6 border-2 border-accent border-t-transparent rounded-full animate-spin" />
          </div>
        ) : error ? (
          <div className="rounded-xl border border-error/30 bg-error/5 p-6 text-center">
            <p className="text-error font-medium">Failed to load projects</p>
            <p className="text-sm text-text-muted mt-1">{error}</p>
          </div>
        ) : (
          <>
            <AggregateStats projects={projects} />
            <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4">
              {projects.map((p) => <ProjectCard key={p.id} project={p} onAction={handleAction} />)}
            </div>
          </>
        )}
      </main>
    </div>
  );
}
