"use client";

import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { categories } from "@/lib/categories";

type ImportResult = {
  added: number;
  errorCount: number;
  errors: { row: number; reason: string }[];
};

export function CsvImportForm() {
  const [file, setFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);
  const [result, setResult] = useState<ImportResult | null>(null);
  const [error, setError] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);
  const router = useRouter();

  async function handleUpload() {
    if (!file) return;
    setUploading(true);
    setError("");
    setResult(null);

    try {
      const formData = new FormData();
      formData.append("file", file);
      const res = await fetch("/api/admin/products/import", {
        method: "POST",
        body: formData,
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.message || "Couldn't import that file.");
        return;
      }
      setResult(data);
      setFile(null);
      if (inputRef.current) inputRef.current.value = "";
      router.refresh();
    } catch {
      setError("Something went wrong uploading that file.");
    } finally {
      setUploading(false);
    }
  }

  return (
    <div className="flex max-w-2xl flex-col gap-6">
      <div className="rounded-xl border border-black/[0.06] bg-black/[0.015] p-5">
        <p className="text-sm font-semibold text-brand-ink">1. Get the template</p>
        <p className="mt-1.5 text-sm text-black/55">
          Download the CSV template, fill in a row per product, and keep the
          column headers exactly as they are.
        </p>
        <a
          href="/templates/product-import-template.csv"
          download
          className="mt-3 inline-block rounded-lg border border-black/10 px-4 py-2 text-sm font-semibold text-brand-ink hover:bg-black/5"
        >
          Download CSV template
        </a>
        <p className="mt-3 text-xs text-black/45">
          <strong>category</strong> must be one of:{" "}
          {categories.map((c) => c.slug).join(", ")}. Leave{" "}
          <strong>compareAtPrice</strong>, <strong>sku</strong>,{" "}
          <strong>image</strong>, <strong>variant</strong> blank if you don&apos;t
          have them, they&apos;re optional.
        </p>
      </div>

      <div className="rounded-xl border border-black/[0.06] bg-black/[0.015] p-5">
        <p className="text-sm font-semibold text-brand-ink">2. Upload your filled-in CSV</p>
        <input
          ref={inputRef}
          type="file"
          accept=".csv,text/csv"
          onChange={(e) => setFile(e.target.files?.[0] ?? null)}
          className="mt-3 block w-full text-sm text-brand-ink file:mr-3 file:rounded-lg file:border-0 file:bg-brand-ink file:px-4 file:py-2 file:text-sm file:font-semibold file:text-white hover:file:bg-black"
        />
        <button
          type="button"
          onClick={handleUpload}
          disabled={!file || uploading}
          className="mt-4 rounded-lg bg-brand-orange px-5 py-2.5 text-sm font-semibold text-white hover:bg-brand-orange-dark disabled:cursor-not-allowed disabled:bg-black/15 disabled:text-black/40"
        >
          {uploading ? "Importing..." : "Import products"}
        </button>
      </div>

      {error && <p className="text-sm text-danger">{error}</p>}

      {result && (
        <div className="rounded-xl border border-black/[0.06] p-5">
          <p className="text-sm font-semibold text-success">
            {result.added} product{result.added === 1 ? "" : "s"} added.
          </p>
          {result.errorCount > 0 && (
            <>
              <p className="mt-3 text-sm font-semibold text-brand-ink">
                {result.errorCount} row{result.errorCount === 1 ? "" : "s"} skipped:
              </p>
              <ul className="mt-2 flex flex-col gap-1 text-sm text-black/60">
                {result.errors.map((e, i) => (
                  <li key={i}>
                    Row {e.row}: {e.reason}
                  </li>
                ))}
              </ul>
            </>
          )}
        </div>
      )}
    </div>
  );
}
