"use client";

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

function formatTaskTime(iso: string): string {
  try {
    return new Date(iso).toLocaleString(undefined, {
      dateStyle: "medium",
      timeStyle: "short",
    });
  } catch {
    return iso;
  }
}

function TaskList({ projectId, initId }: { projectId: string; initId: string }) {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);

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

  if (loading) {
    return (
      <div className="flex items-center justify-center py-8">
        <div className="w-4 h-4 border-2 border-accent border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  if (tasks.length === 0) return null;

  const executed = tasks.filter((t) => t.executed).length;
  const pct = Math.round((executed / tasks.length) * 100);
  const taskHref = (filename: string) =>
    `/projects/${projectId}/initiatives/${encodeURIComponent(initId)}/tasks/${encodeURIComponent(filename)}`;

  return (
    <div className="rounded-xl border border-border bg-surface-raised overflow-hidden">
      <div className="px-5 py-3 border-b border-border-subtle flex items-center justify-between">
        <h3 className="text-sm font-semibold text-text-secondary">
          Tasks ({executed}/{tasks.length})
        </h3>
        <div className="flex items-center gap-2">
          <div className="w-24 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"
              style={{ width: `${pct}%` }}
            />
          </div>
          <span className="text-xs text-text-muted">{pct}%</span>
        </div>
      </div>
      <div className="grid grid-cols-[auto_1fr_auto] gap-2 px-5 py-2 border-b border-border-subtle/80 text-[10px] text-text-muted uppercase tracking-wider">
        <span className="w-4" aria-hidden />
        <span>Task</span>
        <span className="text-right pr-0 min-w-[9rem]">Created</span>
      </div>
      <div className="divide-y divide-border-subtle max-h-[600px] overflow-auto">
        {tasks.map((task) => (
          <Link
            key={task.id}
            href={taskHref(task.filename)}
            className="grid grid-cols-[auto_1fr_auto] gap-2 px-5 py-3 items-center hover:bg-surface-hover/50 transition-colors group"
          >
            {task.executed ? (
              <div className="w-4 h-4 rounded-full bg-success/15 flex items-center justify-center shrink-0">
                <svg className="w-2.5 h-2.5 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>
            ) : task.planned ? (
              <div className="w-4 h-4 rounded-full bg-info/15 flex items-center justify-center shrink-0">
                <div className="w-1.5 h-1.5 rounded-full bg-info" />
              </div>
            ) : (
              <div className="w-4 h-4 rounded-full bg-surface-overlay flex items-center justify-center shrink-0">
                <div className="w-1.5 h-1.5 rounded-full bg-text-muted" />
              </div>
            )}
            <div className="min-w-0">
              <span className="text-xs font-mono text-text-muted mr-2">{task.filename.replace(".md", "")}</span>
              <span className="text-sm text-text-primary group-hover:text-accent-hover transition-colors">
                {task.title}
              </span>
            </div>
            <time
              dateTime={task.createdAt}
              className="text-xs text-text-muted tabular-nums text-right shrink-0 min-w-[9rem]"
              title={`Modified ${formatTaskTime(task.modifiedAt)}`}
            >
              {formatTaskTime(task.createdAt)}
            </time>
          </Link>
        ))}
      </div>
    </div>
  );
}

export default function InitiativePage({
  params,
}: {
  params: Promise<{ id: string; initId: string }>;
}) {
  const { id, initId } = use(params);
  const [initiative, setInitiative] = useState<Initiative | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch(`/api/projects/${id}/initiative/${initId}`)
      .then((r) => {
        if (!r.ok) throw new Error("Not found");
        return r.json();
      })
      .then(setInitiative)
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, [id, initId]);

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

  if (error || !initiative) {
    return (
      <div className="min-h-screen">
        <header className="border-b border-border bg-surface/80 backdrop-blur-xl">
          <div className="max-w-5xl mx-auto px-6 py-4 flex items-center gap-3">
            <Link href={`/projects/${id}`} 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>
            <h1 className="text-lg font-bold">Initiative not found</h1>
          </div>
        </header>
        <main className="max-w-5xl mx-auto px-6 py-12 text-center">
          <p className="text-error">{error || "Initiative not found"}</p>
        </main>
      </div>
    );
  }

  const bodyContent = initiative.content
    .replace(/^---[\s\S]*?---\s*/, "")
    .trim();

  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-5xl mx-auto px-6 py-4">
          <div className="flex items-center gap-3 mb-2">
            <Link
              href={`/projects/${id}`}
              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>
            <span className="text-xs text-text-muted font-mono">{initiative.filename}</span>
            {initiative.format === "directory" && (
              <span className="text-[10px] bg-accent/10 text-accent-hover px-1.5 py-0.5 rounded">
                directory
              </span>
            )}
          </div>
          <div className="flex items-center justify-between">
            <h1 className="text-xl font-bold tracking-tight">{initiative.title}</h1>
            <LogoutButton />
          </div>
        </div>
      </header>

      <main className="max-w-5xl mx-auto px-6 py-6 space-y-6">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          <MetaCard
            label="Status"
            value={
              initiative.iterationStatus ||
              (initiative.executed
                ? "Executed"
                : initiative.planned
                ? "Planned"
                : initiative.split
                ? "Split"
                : "Unplanned")
            }
            color={
              initiative.executed
                ? "text-success"
                : initiative.planned
                ? "text-info"
                : initiative.split
                ? "text-text-muted"
                : "text-warning"
            }
          />
          {initiative.format === "directory" && initiative.taskCount !== undefined ? (
            <MetaCard
              label="Tasks"
              value={`${initiative.tasksExecuted || 0}/${initiative.taskCount}`}
              color="text-accent-hover"
            />
          ) : (
            <MetaCard label="Depth" value={String(initiative.depth)} color="text-text-secondary" />
          )}
          <MetaCard label="Parent" value={initiative.parent || "none"} color="text-text-secondary" />
          {initiative.format === "directory" && initiative.screenshotCount ? (
            <MetaCard
              label="Screenshots"
              value={String(initiative.screenshotCount)}
              color="text-warning"
            />
          ) : (
            <MetaCard
              label="Dependencies"
              value={initiative.deps.length > 0 ? initiative.deps.join(", ") : "none"}
              color="text-text-secondary"
            />
          )}
        </div>

        {initiative.progressSnippet && (
          <div className="rounded-xl border border-border bg-surface-raised overflow-hidden">
            <div className="px-5 py-3 border-b border-border-subtle">
              <h3 className="text-sm font-semibold text-text-secondary">Progress</h3>
            </div>
            <pre className="p-5 text-sm text-text-secondary whitespace-pre-wrap font-sans leading-relaxed">
              {initiative.progressSnippet}
            </pre>
          </div>
        )}

        {initiative.format === "directory" && (
          <TaskList projectId={id} initId={initId} />
        )}

        <div className="rounded-xl border border-border bg-surface-raised overflow-hidden">
          <div className="px-5 py-3 border-b border-border-subtle">
            <h3 className="text-sm font-semibold text-text-secondary">
              {initiative.format === "directory" ? "Specification" : "Content"}
            </h3>
          </div>
          <div className="p-5">
            <pre className="whitespace-pre-wrap text-sm text-text-secondary leading-relaxed font-sans">
              {bodyContent || "No content beyond frontmatter"}
            </pre>
          </div>
        </div>
      </main>
    </div>
  );
}

function MetaCard({
  label,
  value,
  color,
}: {
  label: string;
  value: string;
  color: string;
}) {
  return (
    <div className="rounded-lg border border-border-subtle bg-surface-raised p-3">
      <div className="text-[10px] text-text-muted uppercase tracking-wider mb-1">{label}</div>
      <div className={`text-sm font-medium truncate ${color}`}>{value}</div>
    </div>
  );
}
