"use client";
import { useRef, useState } from "react";
import { useRouter } from "next/navigation";

export default function ProductForm({ initial, productId }: { initial?: any; productId?: string }) {
  const router = useRouter();
  const imageInputRef = useRef<HTMLInputElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [uploadingFile, setUploadingFile] = useState(false);
  const [form, setForm] = useState({
    title: initial?.title || "",
    description: initial?.description || "",
    imageUrl: initial?.imageUrl || "",
    type: initial?.type || "digital",
    price: initial?.price?.toString() || "0",
    compareAtPrice: initial?.compareAtPrice?.toString() || "",
    fileUrl: initial?.fileUrl || "",
    affiliateUrl: initial?.affiliateUrl || "",
    featured: initial?.featured || false,
    status: initial?.status || "published",
  });
  const [saving, setSaving] = useState(false);

  function update(key: string, value: any) {
    setForm((f) => ({ ...f, [key]: value }));
  }

  async function uploadFileTo(file: File): Promise<string | null> {
    const formData = new FormData();
    formData.append("file", file);
    const res = await fetch("/api/upload", { method: "POST", body: formData });
    const data = await res.json();
    return res.ok ? data.url : null;
  }

  async function handleImageUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploadingImage(true);
    const url = await uploadFileTo(file);
    setUploadingImage(false);
    if (url) update("imageUrl", url);
    e.target.value = "";
  }

  async function handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploadingFile(true);
    const url = await uploadFileTo(file);
    setUploadingFile(false);
    if (url) update("fileUrl", url);
    e.target.value = "";
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    const url = productId ? `/api/admin/products/${productId}` : "/api/admin/products";
    await fetch(url, {
      method: productId ? "PATCH" : "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    });
    router.push("/admin/products");
    router.refresh();
  }

  const cls = "w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600";

  return (
    <form onSubmit={handleSubmit} className="space-y-4 max-w-xl">
      <div>
        <label className="block text-sm mb-1 text-neutral-400">Title</label>
        <input required value={form.title} onChange={(e) => update("title", e.target.value)} className={cls} />
      </div>
      <div>
        <label className="block text-sm mb-1 text-neutral-400">Description</label>
        <textarea value={form.description} onChange={(e) => update("description", e.target.value)} rows={3} className={cls} />
      </div>
      <div>
        <label className="block text-sm mb-1 text-neutral-400">Product Image</label>
        <div className="flex items-start gap-3">
          <div className="w-24 h-24 rounded-lg bg-neutral-900 border border-neutral-800 flex items-center justify-center overflow-hidden shrink-0">
            {form.imageUrl ? (
              <img src={form.imageUrl} className="w-full h-full object-cover" />
            ) : (
              <span className="text-2xl opacity-30">📦</span>
            )}
          </div>
          <div className="flex-1 space-y-2">
            <input ref={imageInputRef} type="file" accept="image/*" className="hidden" onChange={handleImageUpload} />
            <button type="button" onClick={() => imageInputRef.current?.click()} disabled={uploadingImage} className="btn-secondary px-4 py-2 text-sm">
              {uploadingImage ? "Uploading..." : "Upload Image"}
            </button>
            <p className="text-xs text-neutral-600">Or paste a URL:</p>
            <input value={form.imageUrl} onChange={(e) => update("imageUrl", e.target.value)} placeholder="https://..." className={cls} />
          </div>
        </div>
      </div>
      <div>
        <label className="block text-sm mb-1 text-neutral-400">Type</label>
        <select value={form.type} onChange={(e) => update("type", e.target.value)} className={cls}>
          <option value="digital">Digital download (sold via Stripe)</option>
          <option value="physical">Physical / ships to buyer (sold via Stripe)</option>
          <option value="affiliate">Affiliate / external link</option>
        </select>
      </div>

      {form.type === "physical" && (
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm mb-1 text-neutral-400">Price ($)</label>
            <input type="number" step="0.01" value={form.price} onChange={(e) => update("price", e.target.value)} className={cls} />
          </div>
          <div>
            <label className="block text-sm mb-1 text-neutral-400">Compare-at price (optional)</label>
            <input type="number" step="0.01" value={form.compareAtPrice} onChange={(e) => update("compareAtPrice", e.target.value)} className={cls} />
          </div>
          <p className="col-span-2 text-xs text-neutral-500">
            Shipping address is collected from the buyer at checkout automatically — orders show up in{" "}
            <a href="/admin/orders" className="text-red-500 underline">Admin → Orders</a> for you to fulfill.
          </p>
        </div>
      )}

      {form.type === "digital" && (
        <>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm mb-1 text-neutral-400">Price ($)</label>
              <input type="number" step="0.01" value={form.price} onChange={(e) => update("price", e.target.value)} className={cls} />
            </div>
            <div>
              <label className="block text-sm mb-1 text-neutral-400">Compare-at price (optional)</label>
              <input type="number" step="0.01" value={form.compareAtPrice} onChange={(e) => update("compareAtPrice", e.target.value)} className={cls} />
            </div>
          </div>
          <div>
            <label className="block text-sm mb-2 text-neutral-400">Digital File (PDF / eBook / Download)</label>
            <div className="space-y-2">
              {form.fileUrl && (
                <div className="flex items-center gap-2 bg-neutral-900 border border-green-800 rounded-md px-3 py-2">
                  <span className="text-green-500">✓</span>
                  <span className="flex-1 truncate text-xs text-neutral-300">{decodeURIComponent(form.fileUrl.split("/").pop() || form.fileUrl)}</span>
                  <a href={form.fileUrl} target="_blank" className="text-blue-500 hover:text-blue-400 text-xs shrink-0">Preview</a>
                  <button type="button" onClick={() => update("fileUrl", "")} className="text-red-500 hover:text-red-400 text-xs shrink-0 ml-1">Remove</button>
                </div>
              )}
              <input ref={fileInputRef} type="file" accept=".pdf,.epub,.docx,.zip,.mp3,.mp4,.txt" className="hidden" onChange={handleFileUpload} />
              <button type="button" onClick={() => fileInputRef.current?.click()} disabled={uploadingFile} className="btn-secondary px-4 py-2 text-sm w-full">
                {uploadingFile ? "Uploading..." : form.fileUrl ? "📤 Replace File" : "📤 Upload File (PDF, eBook, etc.)"}
              </button>
              <p className="text-xs text-neutral-600">Or paste a direct download URL:</p>
              <input value={form.fileUrl} onChange={(e) => update("fileUrl", e.target.value)} placeholder="https://..." className={cls} />
            </div>
          </div>
        </>
      )}

      {form.type === "affiliate" && (
        <div>
          <label className="block text-sm mb-1 text-neutral-400">Affiliate URL</label>
          <input value={form.affiliateUrl} onChange={(e) => update("affiliateUrl", e.target.value)} className={cls} />
        </div>
      )}

      <div className="flex items-center gap-6">
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={form.featured} onChange={(e) => update("featured", e.target.checked)} />
          Featured
        </label>
        <label className="flex items-center gap-2 text-sm">
          Status:
          <select value={form.status} onChange={(e) => update("status", e.target.value)}
            className="bg-neutral-900 border border-neutral-800 rounded-md px-2 py-1 text-sm outline-none focus:border-red-600">
            <option value="draft">Draft</option>
            <option value="published">Published</option>
          </select>
        </label>
      </div>
      <button type="submit" disabled={saving} className="btn-primary px-6 py-2.5">
        {saving ? "Saving..." : productId ? "Save Changes" : "Create Product"}
      </button>
    </form>
  );
}
