"use client";

import { useState } from "react";

export default function PrintfulAdminPage() {
  const [name, setName] = useState("");
  const [externalId, setExternalId] = useState("");
  const [thumbnail, setThumbnail] = useState("");
  const [variantId, setVariantId] = useState("");
  const [retailPrice, setRetailPrice] = useState("");
  const [fileUrl, setFileUrl] = useState("");
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setMessage("");
    try {
      const payload = {
        sync_product: {
          name,
          external_id: externalId || undefined,
          thumbnail: thumbnail || undefined,
        },
        sync_variants: [
          {
            variant_id: Number(variantId),
            retail_price: retailPrice,
            files: fileUrl ? [{ type: "default", url: fileUrl }] : [],
          },
        ],
      };

      const res = await fetch("/api/printful/sync-products", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to create product.");
      setMessage(`Created sync product: ${data.result?.id || "ok"}`);
    } catch (err: any) {
      setMessage(err.message || "Failed to create product.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="auth-page">
      <section className="section">
        <div className="container auth-page__inner">
          <h1 className="page-title">Printful Admin</h1>
          <form className="auth-card" onSubmit={handleCreate}>
            <input
              type="text"
              placeholder="Product name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              required
            />
            <input
              type="text"
              placeholder="External ID (optional)"
              value={externalId}
              onChange={(e) => setExternalId(e.target.value)}
            />
            <input
              type="text"
              placeholder="Thumbnail URL (optional)"
              value={thumbnail}
              onChange={(e) => setThumbnail(e.target.value)}
            />
            <input
              type="number"
              placeholder="Printful variant ID"
              value={variantId}
              onChange={(e) => setVariantId(e.target.value)}
              required
            />
            <input
              type="text"
              placeholder="Retail price (e.g. 29.99)"
              value={retailPrice}
              onChange={(e) => setRetailPrice(e.target.value)}
              required
            />
            <input
              type="text"
              placeholder="Print file URL (optional)"
              value={fileUrl}
              onChange={(e) => setFileUrl(e.target.value)}
            />
            <button className="btn" type="submit" disabled={loading}>
              {loading ? "Creating..." : "Create Sync Product"}
            </button>
            {message ? <div className="connect-message">{message}</div> : null}
          </form>
        </div>
      </section>
    </main>
  );
}
