"use client";

import { useState, useEffect, useCallback } from "react";
import { Card } from "@/components/ui/card";
import { DataTable, type Column } from "@/components/ui/data-table";
import { StatCard } from "@/components/ui/stat-card";
import { DollarSign, ListOrdered } from "lucide-react";

interface UsageEvent {
  id: string;
  request_id: string;
  device_id: string | null;
  model: string;
  prompt_tokens: number;
  completion_tokens: number;
  total_tokens: number;
  price_cents: number | null;
  created_at: string;
}

interface UsageResponse {
  totalSpendCents: number;
  events: UsageEvent[];
}

function formatCents(cents: number): string {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(cents / 100);
}

export default function MarketplacePage() {
  const [data, setData] = useState<UsageResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const fetchUsage = useCallback(async () => {
    try {
      setError("");
      const res = await fetch("/api/dashboard/marketplace/usage?limit=50");
      if (!res.ok) {
        if (res.status === 401) {
          setError("Please sign in to view marketplace usage.");
          return;
        }
        setError("Failed to load marketplace usage.");
        return;
      }
      const json: UsageResponse = await res.json();
      setData(json);
    } catch {
      setError("Failed to load marketplace usage.");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchUsage();
  }, [fetchUsage]);

  const columns: Column<UsageEvent>[] = [
    {
      key: "created_at",
      header: "Time",
      render: (row) =>
        new Date(row.created_at).toLocaleString(undefined, {
          dateStyle: "short",
          timeStyle: "short",
        }),
    },
    {
      key: "request_id",
      header: "Request ID",
      render: (row) => (
        <span className="font-mono text-xs text-gray-400 truncate max-w-[140px] block">
          {row.request_id}
        </span>
      ),
    },
    {
      key: "model",
      header: "Model",
      render: (row) => (
        <span className="font-medium text-gray-100">{row.model}</span>
      ),
    },
    {
      key: "device_id",
      header: "Node",
      render: (row) => (
        <span className="text-gray-400">
          {row.device_id ?? "—"}
        </span>
      ),
    },
    {
      key: "total_tokens",
      header: "Tokens",
      render: (row) => (
        <span className="text-gray-300">
          {row.total_tokens.toLocaleString()}
        </span>
      ),
    },
    {
      key: "price_cents",
      header: "Cost",
      render: (row) => (
        <span className="font-medium text-gray-100">
          {row.price_cents != null
            ? formatCents(row.price_cents)
            : "—"}
        </span>
      ),
    },
  ];

  if (loading) {
    return (
      <div className="space-y-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-100">
            Marketplace usage
          </h1>
          <p className="mt-1 text-sm text-gray-400">
            Spend and recent requests from marketplace nodes
          </p>
        </div>
        <div className="flex items-center justify-center py-12 text-gray-500">
          Loading…
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-100">
            Marketplace usage
          </h1>
          <p className="mt-1 text-sm text-gray-400">
            Spend and recent requests from marketplace nodes
          </p>
        </div>
        <Card className="p-6 text-center text-gray-400">
          {error}
        </Card>
      </div>
    );
  }

  const totalSpendCents = data?.totalSpendCents ?? 0;
  const events = data?.events ?? [];

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold text-gray-100">
          Marketplace usage
        </h1>
        <p className="mt-1 text-sm text-gray-400">
          Spend and recent requests from marketplace nodes (Phase 5 buyer
          dashboard). Usage is recorded when requests are routed to remote
          devices.
        </p>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <StatCard
          title="Total spend"
          value={formatCents(totalSpendCents)}
          icon={<DollarSign size={20} />}
        />
        <StatCard
          title="Recent requests"
          value={String(events.length)}
          icon={<ListOrdered size={20} />}
        />
      </div>

      <Card className="overflow-hidden">
        <div className="border-b border-gray-800 px-4 py-3">
          <h2 className="text-lg font-semibold text-gray-100">
            Recent requests
          </h2>
          <p className="text-sm text-gray-400">
            Request ID, model, node (device_id), tokens, and cost per request
          </p>
        </div>
        <DataTable<UsageEvent>
          columns={columns}
          data={events}
          keyExtractor={(row) => row.id}
          emptyMessage="No marketplace usage yet. Usage appears here when requests are routed to remote nodes and your API key is linked (proxyKeyId)."
        />
      </Card>
    </div>
  );
}
