"use client";

import { useMemo, useState, useTransition } from "react";
import { ProductVisual } from "@/components/ProductVisual";

function normalizePath(value: string) {
  return value.trim();
}

export function ProductImageField({ initialValue }: { initialValue: string }) {
  const [imagePath, setImagePath] = useState(initialValue);
  const [error, setError] = useState("");
  const [isPending, startTransition] = useTransition();

  const previewProduct = useMemo(() => ({
    imageUrls: imagePath ? JSON.stringify([imagePath]) : "[]",
    images: imagePath ? JSON.stringify([imagePath]) : "[]"
  }), [imagePath]);

  async function onFileChange(event: React.ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file) return;

    setError("");

    startTransition(async () => {
      try {
        const formData = new FormData();
        formData.append("file", file);

        const response = await fetch("/api/admin/uploads/product-image", {
          method: "POST",
          body: formData
        });

        const payload = await response.json().catch(() => null);
        if (!response.ok) {
          setError(payload?.error || "Image upload failed.");
          return;
        }

        setImagePath(payload?.path || "");
      } catch {
        setError("Image upload failed.");
      } finally {
        event.target.value = "";
      }
    });
  }

  return (
    <div className="md:col-span-2">
      <div className="grid gap-4 md:grid-cols-[minmax(0,1fr)_220px]">
        <div className="grid gap-4">
          <label>
            Image URL / Local Path
            <input
              name="image"
              value={imagePath}
              onChange={(event) => setImagePath(normalizePath(event.target.value))}
              placeholder="/uploads/products/example.webp"
            />
          </label>
          <label>
            Upload primary image
            <input
              type="file"
              accept="image/jpeg,image/png,image/webp"
              onChange={onFileChange}
              className="cursor-pointer"
              disabled={isPending}
            />
          </label>
          <p className="text-sm text-[#666]">
            Upload a product photo or paste an image URL/path. Real bullion photos can be uploaded by the client.
          </p>
          <p className="text-xs text-[#666]">
            Local filesystem uploads work for local or traditional hosting. Serverless production hosting may need persistent object storage later.
          </p>
          {isPending ? <p className="text-sm font-bold text-[#7A5310]">Uploading image...</p> : null}
          {error ? <p className="rounded border border-[#B91C1C] bg-red-50 p-3 text-sm font-bold text-[#B91C1C]">{error}</p> : null}
        </div>
        <div className="panel border border-[#E5E1D8] bg-[#F7F5EF] p-3">
          <div className="mb-2 text-xs font-black uppercase tracking-[0.12em] text-[#5f6673]">Preview</div>
          <div className="product-image-shell relative aspect-[4/3] overflow-hidden rounded border border-[#E5E1D8] bg-white">
            <ProductVisual product={previewProduct} className="h-full" compact />
          </div>
        </div>
      </div>
    </div>
  );
}
