"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";

export function LicitationsSyncButton() {
  const [isSyncing, setIsSyncing] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  async function triggerSync() {
    setIsSyncing(true);
    setMessage(null);

    try {
      const response = await fetch("/api/admin/sync", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({}),
      });

      const payload = (await response.json().catch(() => ({}))) as {
        ok?: boolean;
        error?: string;
        payload?: {
          processedMunicipalities?: number;
        };
      };

      if (!response.ok || !payload.ok) {
        setMessage(payload.error ?? "No se pudo ejecutar la sincronizacion.");
        return;
      }

      const processed = payload.payload?.processedMunicipalities ?? 0;
      setMessage(`Sincronizacion completada. Municipios procesados: ${processed}.`);
    } catch {
      setMessage("No se pudo ejecutar la sincronizacion.");
    } finally {
      setIsSyncing(false);
    }
  }

  return (
    <div className="flex flex-col items-end gap-2">
      <Button type="button" onClick={triggerSync} disabled={isSyncing}>
        {isSyncing ? "Sincronizando..." : "Buscar oportunidades"}
      </Button>
      {message ? <p className="text-xs text-[#536583]">{message}</p> : null}
    </div>
  );
}
