"use client";

import { useState } from "react";

import { useToast } from "@/components/admin/common/ToastProvider";

export function GscImportForm() {
  const toast = useToast();
  const [kind, setKind] = useState<"queries" | "pages">("queries");
  const [start, setStart] = useState("");
  const [end, setEnd] = useState("");
  const [file, setFile] = useState<File | null>(null);
  const [busy, setBusy] = useState(false);
  const [syncBusy, setSyncBusy] = useState(false);

  async function syncDirectly() {
    setSyncBusy(true);
    try {
      const res = await fetch("/api/admin/seo/gsc-sync", { method: "POST" });
      const data = (await res.json()) as {
        ok?: boolean;
        queries?: number;
        pages?: number;
        error?: string;
      };
      if (res.ok && data.ok) {
        toast.success(
          `Search Console sinhronizovan: ${data.queries ?? 0} upita i ${data.pages ?? 0} stranica.`,
        );
      } else {
        toast.error(data.error ?? "Search Console sync nije uspeo.");
      }
    } catch {
      toast.error("Search Console sync nije uspeo.");
    } finally {
      setSyncBusy(false);
    }
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!file) {
      toast.error("Odaberi CSV fajl.");
      return;
    }
    if (!start || !end) {
      toast.error("Postavi period (od / do).");
      return;
    }
    setBusy(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      fd.append("kind", kind);
      fd.append("start", start);
      fd.append("end", end);
      const res = await fetch("/api/admin/seo/gsc-import", {
        method: "POST",
        body: fd,
      });
      const data = (await res.json()) as { ok?: boolean; count?: number; error?: string };
      if (res.ok && data.ok) {
        toast.success(`Uvezeno ${data.count ?? 0} redova.`);
      } else {
        toast.error(data.error ?? "Greška pri uvozu.");
      }
    } catch {
      toast.error("Greška pri uvozu.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <form onSubmit={onSubmit} className="surface space-y-4 rounded-2xl p-6">
      <div className="flex flex-wrap items-center justify-between gap-4 rounded-xl border border-primary/20 bg-primary/5 p-4">
        <div>
          <p className="font-semibold text-foreground">Direktna Search Console sinhronizacija</p>
          <p className="mt-1 text-xs text-muted-foreground">
            Preuzima poslednjih 28 završenih dana za upite i stranice, bez ručnog CSV-a.
          </p>
        </div>
        <button
          type="button"
          disabled={syncBusy}
          onClick={syncDirectly}
          className="primary-button inline-flex"
        >
          {syncBusy ? "Sinhronizujem…" : "Sinhronizuj GSC"}
        </button>
      </div>
      <div className="flex items-center gap-3 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
        <span className="h-px flex-1 bg-border" />
        Rezervni CSV uvoz
        <span className="h-px flex-1 bg-border" />
      </div>
      <div className="grid gap-4 sm:grid-cols-2">
        <label className="block">
          <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
            Tip izveštaja
          </span>
          <select
            value={kind}
            onChange={(e) => setKind(e.target.value as "queries" | "pages")}
            className="mt-1 w-full rounded-xl border border-border bg-white px-3 py-2 text-sm"
          >
            <option value="queries">Queries (upiti)</option>
            <option value="pages">Pages (stranice)</option>
          </select>
        </label>
        <label className="block">
          <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
            CSV fajl
          </span>
          <input
            type="file"
            accept=".csv,.tsv,text/csv"
            onChange={(e) => setFile(e.target.files?.[0] ?? null)}
            className="mt-1 block w-full text-sm"
          />
        </label>
        <label className="block">
          <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
            Period — od
          </span>
          <input
            type="date"
            value={start}
            onChange={(e) => setStart(e.target.value)}
            className="mt-1 w-full rounded-xl border border-border bg-white px-3 py-2 text-sm"
          />
        </label>
        <label className="block">
          <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
            Period — do
          </span>
          <input
            type="date"
            value={end}
            onChange={(e) => setEnd(e.target.value)}
            className="mt-1 w-full rounded-xl border border-border bg-white px-3 py-2 text-sm"
          />
        </label>
      </div>
      <button
        type="submit"
        disabled={busy}
        className="primary-button inline-flex"
      >
        {busy ? "Uvozim…" : "Uvezi CSV"}
      </button>
      <p className="text-xs text-muted-foreground">
        Export iz Google Search Console → Performance → Export → CSV. Preuzmi „Queries“ ili
        „Pages“ list, a zatim ga ovde otpremi.
      </p>
    </form>
  );
}
