"use client";

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

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

export default function TaskPage({
  params,
}: {
  params: Promise<{ id: string; initId: string; taskFilename: string }>;
}) {
  const { id, initId, taskFilename } = use(params);
  const decoded = decodeURIComponent(taskFilename);
  const [data, setData] = useState<{
    content: string;
    createdAt: string;
    modifiedAt: string;
  } | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch(`/api/projects/${id}/initiative/${initId}/tasks/${encodeURIComponent(decoded)}`)
      .then((r) => {
        if (!r.ok) throw new Error("Not found");
        return r.json();
      })
      .then(setData)
      .catch(() => setError("Could not load task"))
      .finally(() => setLoading(false));
  }, [id, initId, decoded]);

  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 || !data) {
    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">
            <Link
              href={`/projects/${id}/initiatives/${initId}`}
              className="text-sm text-text-muted hover:text-accent-hover"
            >
              ← Back to initiative
            </Link>
          </div>
        </header>
        <main className="max-w-5xl mx-auto px-6 py-12 text-center text-error">{error}</main>
      </div>
    );
  }

  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">
          <Link
            href={`/projects/${id}/initiatives/${initId}`}
            className="inline-flex items-center gap-2 text-sm text-text-muted hover:text-accent-hover mb-3"
          >
            <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>
            Back to initiative
          </Link>
          <div className="text-xs font-mono text-text-muted mb-1">{decoded}</div>
          <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-text-muted">
            <span>
              <span className="text-text-muted/80">Created:</span> {formatWhen(data.createdAt)}
            </span>
            <span>
              <span className="text-text-muted/80">Modified:</span> {formatWhen(data.modifiedAt)}
            </span>
          </div>
        </div>
      </header>

      <main className="max-w-5xl mx-auto px-6 py-6">
        <div className="rounded-xl border border-border bg-surface-raised overflow-hidden">
          <div className="px-5 py-3 border-b border-border-subtle">
            <h2 className="text-sm font-semibold text-text-secondary">Markdown</h2>
          </div>
          <div className="p-5">
            <pre className="whitespace-pre-wrap text-sm text-text-secondary leading-relaxed font-mono overflow-x-auto">
              {data.content || "(empty)"}
            </pre>
          </div>
        </div>
      </main>
    </div>
  );
}
