'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { Badge, StatusDot, type StatusTone } from '@/components/ui/Primitives';
import { getPublicItem, type TrackerItem } from '@/lib/tracker-client';

const STATUS_TONE: Record<string, StatusTone> = {
  open: 'info',
  in_progress: 'warning',
  done: 'success',
  closed: 'neutral',
  wont_fix: 'neutral',
};

const STATUS_LABEL: Record<string, string> = {
  open: 'Planned',
  in_progress: 'In progress',
  done: 'Shipped',
  closed: 'Closed',
  wont_fix: "Won't fix",
};

export default function PublicStatusPage() {
  const params = useParams<{ id: string }>();
  const [item, setItem] = useState<TrackerItem | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    async function load() {
      if (!params.id) return;
      setLoading(true);
      setError(null);
      try {
        const result = await getPublicItem(params.id);
        if (!cancelled) setItem(result);
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err.message : 'Unable to load status');
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    void load();
    return () => {
      cancelled = true;
    };
  }, [params.id]);

  return (
    <div className="min-h-screen bg-background">
      <main className="mx-auto max-w-3xl px-4 py-10 sm:px-6">
        <div className="mb-6 flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-foreground">Roadmap status</h1>
            <p className="mt-1 text-sm text-muted-foreground">
              Follow progress from public request to shipped work.
            </p>
          </div>
          <a
            href="/roadmap"
            className="rounded-md px-3 py-2 text-sm text-muted-foreground hover:bg-muted hover:text-foreground"
          >
            Back to roadmap
          </a>
        </div>

        {loading ? (
          <div className="rounded-2xl border border-border bg-card p-6 shadow-sm">
            <div className="h-6 w-2/3 animate-pulse rounded bg-muted" />
            <div className="mt-4 h-24 animate-pulse rounded bg-muted" />
          </div>
        ) : error ? (
          <div className="rounded-2xl border border-destructive/40 bg-destructive/5 p-6">
            <h2 className="font-semibold text-destructive">Submission not found</h2>
            <p className="mt-2 text-sm text-muted-foreground">
              {error}. The request may have been merged, removed, or kept internal.
            </p>
            <a
              href="/roadmap"
              className="mt-4 inline-flex rounded-md border border-border px-3 py-2 text-sm font-medium hover:bg-muted"
            >
              View roadmap
            </a>
          </div>
        ) : item ? (
          <article className="rounded-2xl border border-border bg-card p-6 shadow-sm">
            <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
              <div>
                <h2 className="text-xl font-semibold text-foreground">{item.title}</h2>
                <div className="mt-2 text-sm font-medium text-foreground">Submission status</div>
                <p className="mt-2 text-sm text-muted-foreground">{item.description}</p>
                {item.status === 'open' && (
                  <p className="mt-2 text-sm text-muted-foreground">
                    We received this submission and it is waiting for triage.
                  </p>
                )}
              </div>
              <Badge variant={item.status === 'done' ? 'success' : 'info'}>
                {STATUS_LABEL[item.status] ?? item.status}
              </Badge>
            </div>

            <div className="mt-6 grid gap-3 sm:grid-cols-3">
              <div className="rounded-lg border border-border p-3">
                <div className="text-xs text-muted-foreground">Votes</div>
                <div className="text-2xl font-bold">{item.voteCount} votes</div>
              </div>
              <div className="rounded-lg border border-border p-3">
                <div className="text-xs text-muted-foreground">Priority</div>
                <div className="text-2xl font-bold capitalize">{item.priority}</div>
              </div>
              <div className="rounded-lg border border-border p-3">
                <div className="text-xs text-muted-foreground">Comments</div>
                <div className="text-2xl font-bold">{item.commentCount}</div>
              </div>
            </div>

            <div className="mt-6 space-y-3">
              {['open', 'in_progress', 'done'].map(status => {
                const active = status === item.status;
                return (
                  <div key={status} className="flex items-center gap-3 text-sm">
                    <StatusDot tone={STATUS_TONE[status] ?? 'neutral'} />
                    <span
                      className={active ? 'font-semibold text-foreground' : 'text-muted-foreground'}
                    >
                      {STATUS_LABEL[status]}
                    </span>
                    {active && <span className="text-xs text-muted-foreground">current</span>}
                  </div>
                );
              })}
            </div>
          </article>
        ) : null}
      </main>
    </div>
  );
}
