"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({
          includePnt: true,
          includeLicitaya: true,
          force: true,
        }),
      });

      const payload = (await response.json().catch(() => ({}))) as {
        ok?: boolean;
        error?: string;
        payload?: {
          processedMunicipalities?: number;
          processedScopes?: number;
          processedLicitayaBuckets?: number;
          results?: Array<{
            sourceResults?: Array<{
              status?: string;
              warnings?: string[];
              stats?: {
                totalFetched?: number;
                inserted?: number;
                updated?: number;
              };
            }>;
          }>;
        };
      };

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

      const processedMunicipalities = payload.payload?.processedMunicipalities ?? 0;
      const processedScopes = payload.payload?.processedScopes ?? processedMunicipalities;
      const licitayaBuckets = payload.payload?.processedLicitayaBuckets ?? 0;
      const sourceResults = payload.payload?.results?.flatMap((result) => result.sourceResults ?? []) ?? [];

      const totals = sourceResults.reduce(
        (acc, sourceResult) => {
          acc.fetched += sourceResult.stats?.totalFetched ?? 0;
          acc.inserted += sourceResult.stats?.inserted ?? 0;
          acc.updated += sourceResult.stats?.updated ?? 0;
          acc.warnings += sourceResult.warnings?.length ?? 0;

          if (sourceResult.status === "FAILED") {
            acc.failed += 1;
          } else if (sourceResult.status === "PARTIAL") {
            acc.partial += 1;
          }

          return acc;
        },
        {
          fetched: 0,
          inserted: 0,
          updated: 0,
          warnings: 0,
          failed: 0,
          partial: 0,
        },
      );

      setMessage(
        `Sync listo. Municipios: ${processedMunicipalities}. Alcances: ${processedScopes}. LicitaYa: ${licitayaBuckets}. ` +
          `Detectados: ${totals.fetched}. Nuevos: ${totals.inserted}. Actualizados: ${totals.updated}. ` +
          `Parciales: ${totals.partial}. Fallidos: ${totals.failed}. Advertencias: ${totals.warnings}.`,
      );
    } 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>
  );
}
