"use client";

import { usePoll } from "@/lib/use-poll";
import type { OverviewStats } from "@/lib/types";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { StatusBadge } from "./status-badge";

export function OllamaCard() {
  const { data } = usePoll<OverviewStats>("/api/stats/overview", 60000);
  const gpu = data?.gpu;
  const ollama = data?.ollama;

  return (
    <Card>
      <CardHeader className="pb-2 flex flex-row items-center justify-between">
        <CardTitle className="text-sm font-medium">LLM / GPU</CardTitle>
        {ollama && (
          <StatusBadge
            color={ollama.available ? "green" : "red"}
            label={ollama.available ? "Online" : "Offline"}
          />
        )}
      </CardHeader>
      <CardContent className="space-y-2">
        {!data ? (
          <p className="text-xs text-muted-foreground">Loading...</p>
        ) : gpu?.available ? (
          <>
            {gpu.name && (
              <p className="text-xs text-foreground font-medium">{gpu.name}</p>
            )}
            <div className="grid grid-cols-2 gap-2 text-xs">
              {gpu.vram_used_mb != null && gpu.vram_total_mb != null && (
                <div>
                  <p className="text-muted-foreground">VRAM</p>
                  <p className="text-foreground">
                    {(gpu.vram_used_mb / 1024).toFixed(1)} /{" "}
                    {(gpu.vram_total_mb / 1024).toFixed(1)} GB
                  </p>
                  <div className="mt-1 h-1.5 rounded-full bg-secondary overflow-hidden">
                    <div
                      className="h-full rounded-full bg-primary"
                      style={{
                        width: `${(gpu.vram_used_mb / gpu.vram_total_mb) * 100}%`,
                      }}
                    />
                  </div>
                </div>
              )}
              {gpu.temp_c != null && (
                <div>
                  <p className="text-muted-foreground">Temperature</p>
                  <p className="text-foreground">{gpu.temp_c}&deg;C</p>
                </div>
              )}
              {gpu.power_w != null && (
                <div>
                  <p className="text-muted-foreground">Power</p>
                  <p className="text-foreground">
                    {gpu.power_w}W
                    {gpu.power_limit_w ? ` / ${gpu.power_limit_w}W` : ""}
                  </p>
                </div>
              )}
              {gpu.utilization_pct != null && (
                <div>
                  <p className="text-muted-foreground">Utilization</p>
                  <p className="text-foreground">{gpu.utilization_pct}%</p>
                </div>
              )}
            </div>
          </>
        ) : (
          <p className="text-xs text-muted-foreground">GPU not available</p>
        )}
      </CardContent>
    </Card>
  );
}
