"use client";

import { useState, useTransition } from "react";
import { RefreshCw, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Container } from "@/components/container";
import { useLanguage } from "@/lib/i18n/context";
import { recalculateAllScoresAction } from "@/actions/admin-import-actions";

export function AdminScoringContent({ modelVersion }: { modelVersion: string }) {
  const { t, locale } = useLanguage();
  const s = t.admin.scoring;
  const [isPending, startTransition] = useTransition();
  const [lastResult, setLastResult] = useState<string | null>(null);

  function handleRecalculate() {
    startTransition(async () => {
      const result = await recalculateAllScoresAction(locale);
      if (result.success) {
        setLastResult(s.recalculateSuccess.replace("{count}", String(result.succeededCount)));
        toast.success(s.recalculateSuccess.replace("{count}", String(result.succeededCount)));
        if (result.failedCount > 0) {
          toast.error(s.recalculateFailure.replace("{count}", String(result.failedCount)));
        }
      } else {
        toast.error(result.error);
      }
    });
  }

  return (
    <div className="admin-page py-8">
      <Container className="flex flex-col gap-6">
        <h1 className="admin-page-intro text-lg font-semibold text-foreground">{s.title}</h1>
        <Card className="admin-surface">
          <CardHeader>
            <CardTitle>{s.modelVersion}</CardTitle>
            <CardDescription>{modelVersion}</CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col gap-3">
            <Button onClick={handleRecalculate} disabled={isPending} className="w-fit">
              {isPending ? <Loader2 className="size-4 animate-spin" /> : <RefreshCw className="size-4" />}
              {isPending ? s.recalculating : s.recalculateAll}
            </Button>
            {lastResult && <p className="text-sm text-muted-foreground">{lastResult}</p>}
          </CardContent>
        </Card>
      </Container>
    </div>
  );
}
