"use client";

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

type Tab = "initiatives" | "logs" | "screenshots";

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" },
    "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" },
    "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}
    </span>
  );
}

function InitiativesTab({ projectId, activeInitiative }: { projectId: string; activeInitiative: string | null }) {
  const [initiatives, setInitiatives] = useState<Initiative[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<"all" | "executed" | "planned" | "unplanned" | "priority">("all");

  useEffect(() => {
    fetch(`/api/projects/${projectId}/initiatives`)
      .then((r) => r.json())
      .then(setInitiatives)
      .finally(() => setLoading(false));
  }, [projectId]);

  if (loading) return <LoadingSpinner />;

  const filtered = initiatives.filter((i) => {
    if (filter === "executed") return i.executed;
    if (filter === "planned") return i.planned && !i.executed && !i.split;
    if (filter === "unplanned") return !i.planned && !i.executed && !i.split;
    if (filter === "priority") return i.priority > 0 && !i.executed;
    return true;
  });

  return (
    <div className="space-y-4 animate-slide-up">
      <div className="flex items-center gap-2 flex-wrap">
        {(["all", "priority", "executed", "planned", "unplanned"] as const).map((f) => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
              filter === f ? "bg-accent/20 text-accent-hover" : "bg-surface-overlay text-text-muted hover:text-text-secondary hover:bg-surface-hover"
            }`}
          >
            {f === "all" ? `All (${initiatives.length})` :
             f === "priority" ? `⚡ Priority (${initiatives.filter(i => i.priority > 0 && !i.executed).length})` :
             f === "executed" ? `Done (${initiatives.filter(i => i.executed).length})` :
             f === "planned" ? `Planned (${initiatives.filter(i => i.planned && !i.executed && !i.split).length})` :
             `Queue (${initiatives.filter(i => !i.planned && !i.executed && !i.split).length})`}
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="text-center py-12 text-text-muted">No initiatives match this filter</div>
      ) : (
        <div className="space-y-2">
          {filtered.map((init) => (
            <Link key={init.id} href={`/projects/${projectId}/initiatives/${init.id}`} className="block">
              <div className="rounded-lg border border-border-subtle bg-surface-raised p-4 hover:border-accent/30 hover:bg-surface-hover transition-all group">
                <div className="flex items-start gap-3">
                  <div className="mt-0.5">
                    {init.executed ? (
                      <div className="w-5 h-5 rounded-full bg-success/15 flex items-center justify-center">
                        <svg className="w-3 h-3 text-success" fill="none" viewBox="0 0 24 24" strokeWidth={3} stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" /></svg>
                      </div>
                    ) : init.planned ? (
                      <div className="w-5 h-5 rounded-full bg-info/15 flex items-center justify-center"><div className="w-2 h-2 rounded-full bg-info" /></div>
                    ) : init.split ? (
                      <div className="w-5 h-5 rounded-full bg-surface-overlay flex items-center justify-center">
                        <svg className="w-3 h-3 text-text-muted" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z" /></svg>
                      </div>
                    ) : (
                      <div className="w-5 h-5 rounded-full bg-warning/15 flex items-center justify-center"><div className="w-2 h-2 rounded-full bg-warning" /></div>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="text-[11px] font-mono text-text-muted">{init.filename.replace(".md", "")}</span>
                      {init.priority > 0 && (
                        <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
                          init.priority === 1 ? "bg-error/15 text-error" :
                          init.priority === 2 ? "bg-warning/15 text-warning" :
                          init.priority === 3 ? "bg-info/15 text-info" :
                          "bg-surface-overlay text-text-muted"
                        }`}>
                          P{init.priority}
                        </span>
                      )}
                      {init.author && (
                        <span className="text-[10px] text-accent-hover bg-accent/10 px-1.5 py-0.5 rounded">
                          {init.author}
                        </span>
                      )}
                      {(init.id === activeInitiative || init.filename.replace(".md", "") === activeInitiative) && (
                        <span className="text-[10px] font-semibold text-success bg-success/10 px-1.5 py-0.5 rounded">active</span>
                      )}
                      {init.depth > 0 && <span className="text-[10px] text-text-muted bg-surface-overlay px-1.5 py-0.5 rounded">depth {init.depth}</span>}
                      {init.format === "directory" && init.taskCount !== undefined && init.taskCount > 0 && (
                        <span className="text-[10px] text-accent-hover bg-accent/10 px-1.5 py-0.5 rounded">
                          tasks {init.tasksExecuted}/{init.taskCount}
                        </span>
                      )}
                    </div>
                    <h4 className="text-sm font-medium text-text-primary group-hover:text-accent-hover transition-colors mt-0.5">{init.title}</h4>
                    {init.deps.length > 0 && (
                      <div className="flex items-center gap-1 mt-1.5">
                        <span className="text-[10px] text-text-muted">deps:</span>
                        {init.deps.map((d) => <span key={d} className="text-[10px] bg-surface-overlay text-text-muted px-1.5 py-0.5 rounded">{d}</span>)}
                      </div>
                    )}
                  </div>
                  <svg className="w-4 h-4 text-text-muted group-hover:text-accent-hover transition-colors shrink-0 mt-1" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /></svg>
                </div>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}

function LogsTab({ projectId }: { projectId: string }) {
  const [content, setContent] = useState("");
  const [totalLines, setTotalLines] = useState(0);
  const [search, setSearch] = useState("");
  const [autoScroll, setAutoScroll] = useState(true);
  const [lineCount, setLineCount] = useState(500);
  const logRef = useRef<HTMLPreElement>(null);

  const fetchLogs = useCallback(async () => {
    const params = new URLSearchParams({ lines: lineCount.toString() });
    if (search) params.set("search", search);
    const res = await fetch(`/api/projects/${projectId}/logs?${params}`);
    const data = await res.json();
    setContent(data.content);
    setTotalLines(data.totalLines);
  }, [projectId, search, lineCount]);

  useEffect(() => { fetchLogs(); const i = setInterval(fetchLogs, 5_000); return () => clearInterval(i); }, [fetchLogs]);
  useEffect(() => { if (autoScroll && logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; }, [content, autoScroll]);

  function highlightLine(line: string): string {
    if (/\bERROR\b|\bCRASH\b|\bFAILED\b|\bfailed\b/i.test(line)) return "log-error";
    if (/\bWARN\b|\bwarning\b/i.test(line)) return "log-warning";
    if (/\bsucceeded\b|\bsuccess\b|\bcomplete\b/i.test(line)) return "log-success";
    if (/^[═╔╚║#+]/.test(line.replace(/^\[.*?\]\s*/, ""))) return "log-header";
    if (/^\[.*?\]/.test(line)) return "log-info";
    return "";
  }

  return (
    <div className="space-y-3 animate-slide-up">
      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative flex-1 min-w-[200px]">
          <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" /></svg>
          <input type="text" value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search logs..." className="w-full pl-9 pr-3 py-2 bg-surface-overlay border border-border-subtle rounded-lg text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:border-accent/50 focus:ring-1 focus:ring-accent/20" />
        </div>
        <select value={lineCount} onChange={(e) => setLineCount(Number(e.target.value))} className="bg-surface-overlay border border-border-subtle rounded-lg px-3 py-2 text-sm text-text-secondary focus:outline-none focus:border-accent/50">
          <option value={200}>200 lines</option>
          <option value={500}>500 lines</option>
          <option value={1000}>1000 lines</option>
          <option value={5000}>5000 lines</option>
        </select>
        <button onClick={() => setAutoScroll(!autoScroll)} className={`px-3 py-2 rounded-lg text-xs font-medium transition-colors ${autoScroll ? "bg-accent/20 text-accent-hover" : "bg-surface-overlay text-text-muted"}`}>
          Auto-scroll {autoScroll ? "ON" : "OFF"}
        </button>
        <span className="text-xs text-text-muted">{totalLines.toLocaleString()} total lines</span>
      </div>
      <pre ref={logRef} className="log-viewer rounded-lg border border-border-subtle bg-surface-raised p-4 overflow-auto max-h-[70vh] whitespace-pre-wrap break-all">
        {content ? content.split("\n").map((line, i) => <div key={i} className={highlightLine(line)}>{line}</div>) : <span className="text-text-muted">No log content</span>}
      </pre>
    </div>
  );
}

function ScreenshotsTab({ projectId }: { projectId: string }) {
  const [screenshots, setScreenshots] = useState<Screenshot[]>([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<Screenshot | null>(null);

  useEffect(() => { fetch(`/api/projects/${projectId}/screenshots`).then((r) => r.json()).then(setScreenshots).finally(() => setLoading(false)); }, [projectId]);

  if (loading) return <LoadingSpinner />;
  if (screenshots.length === 0) {
    return (
      <div className="text-center py-16 animate-slide-up">
        <svg className="w-12 h-12 mx-auto text-text-muted mb-3" fill="none" viewBox="0 0 24 24" strokeWidth={1} stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909M3.75 21h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v13.5A1.5 1.5 0 003.75 21z" /></svg>
        <p className="text-text-muted">No dogfood screenshots found</p>
      </div>
    );
  }

  return (
    <div className="animate-slide-up">
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
        {screenshots.map((ss) => (
          <button key={ss.path} onClick={() => setSelected(ss)} className="group rounded-lg border border-border-subtle bg-surface-raised overflow-hidden hover:border-accent/30 transition-all text-left">
            <div className="aspect-video bg-surface-overlay relative overflow-hidden">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={`/api/screenshots${ss.path}`} alt={ss.filename} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" loading="lazy" />
            </div>
            <div className="p-2">
              <p className="text-xs text-text-secondary truncate">{ss.filename}</p>
              <p className="text-[10px] text-text-muted">{new Date(ss.modified).toLocaleString()} &middot; {(ss.size / 1024).toFixed(0)}KB</p>
            </div>
          </button>
        ))}
      </div>
      {selected && (
        <div className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-8" onClick={() => setSelected(null)}>
          <div className="relative max-w-5xl w-full" onClick={(e) => e.stopPropagation()}>
            <button onClick={() => setSelected(null)} className="absolute -top-10 right-0 text-text-muted hover:text-text-primary">
              <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>
            </button>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={`/api/screenshots${selected.path}`} alt={selected.filename} className="w-full h-auto max-h-[85vh] object-contain rounded-lg" />
            <p className="text-center text-sm text-text-secondary mt-3">{selected.filename}</p>
          </div>
        </div>
      )}
    </div>
  );
}

function LoadingSpinner() {
  return <div className="flex items-center justify-center py-16"><div className="w-5 h-5 border-2 border-accent border-t-transparent rounded-full animate-spin" /></div>;
}

export default function ProjectPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const [project, setProject] = useState<Project | null>(null);
  const [tab, setTab] = useState<Tab>("initiatives");
  const [loading, setLoading] = useState(true);

  const fetchProject = useCallback(async () => {
    try {
      const res = await fetch("/api/projects");
      const projects: Project[] = await res.json();
      setProject(projects.find((p) => p.id === id) || null);
    } finally {
      setLoading(false);
    }
  }, [id]);

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

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

  const status = project?.status;
  const proc = project?.process;

  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">
          <div className="flex items-center gap-3 mb-3">
            <Link href="/" className="p-1.5 rounded-lg text-text-muted hover:text-text-primary hover:bg-surface-hover transition-colors">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" /></svg>
            </Link>
            <div className="flex-1 min-w-0">
              <h1 className="text-lg font-bold tracking-tight truncate">{id}</h1>
              {project?.scopeSnippet && <p className="text-xs text-text-muted truncate">{project.scopeSnippet}</p>}
            </div>
            <div className="flex items-center gap-2">
              {status && <StatusBadge phase={status.phase} running={proc?.running || false} stopping={proc?.stopping} />}
              <LogoutButton />
            </div>
          </div>

          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4 text-xs text-text-muted">
              {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?.uptime && <span>Uptime: {proc.uptime}</span>}
              {status?.iteration ? <span>Iter #{status.iteration}</span> : null}
              {status?.updated && <span>{status.updated}</span>}
              {project?.gitBranch && <span className="font-mono">{project.gitBranch}</span>}
            </div>
            <div className="flex items-center gap-2">
              {!proc?.running && (
                <button onClick={() => handleAction("start")} className="px-3 py-1.5 rounded-lg text-xs font-medium bg-success/10 text-success hover:bg-success/20 transition-colors">Start</button>
              )}
              {proc?.running && proc?.stopping && (
                <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium bg-warning/15 text-warning">
                  <span className="w-1.5 h-1.5 rounded-full bg-warning animate-pulse" />
                  Stopping after current iteration...
                </span>
              )}
              {proc?.running && !proc?.stopping && (
                <button onClick={() => handleAction("stop")} className="px-3 py-1.5 rounded-lg text-xs font-medium bg-warning/10 text-warning hover:bg-warning/20 transition-colors">Stop Gracefully</button>
              )}
              {proc?.running && (
                <button onClick={() => handleAction("kill")} className="px-3 py-1.5 rounded-lg text-xs font-medium bg-error/10 text-error hover:bg-error/20 transition-colors">Kill Process</button>
              )}
            </div>
          </div>
        </div>

        <div className="max-w-7xl mx-auto px-6 flex gap-1">
          {(["initiatives", "logs", "screenshots"] as Tab[]).map((t) => (
            <button key={t} onClick={() => setTab(t)} className={`px-4 py-2.5 text-sm font-medium transition-colors relative ${tab === t ? "text-accent-hover" : "text-text-muted hover:text-text-secondary"}`}>
              {t.charAt(0).toUpperCase() + t.slice(1)}
              {tab === t && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-accent rounded-full" />}
            </button>
          ))}
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-6 py-6">
        {loading ? <LoadingSpinner /> : (
          <>
            {tab === "initiatives" && <InitiativesTab projectId={id} activeInitiative={project?.activeInitiative ?? null} />}
            {tab === "logs" && <LogsTab projectId={id} />}
            {tab === "screenshots" && <ScreenshotsTab projectId={id} />}
          </>
        )}
      </main>
    </div>
  );
}
