"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { collection, addDoc, serverTimestamp } from "firebase/firestore";
import { db } from "@/lib/firebase";

export default function NewProductPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [form, setForm] = useState({
    barcode: "",
    brandName: "",
    companyName: "",
    productName: "",
    manufacturedIn: "",
    description: "",
    certificateBodies: "",
    certificateExpiry: "",
    ingredients: "",
    nutrition: "",
    kcalPerUnit: "",
    last4Digits: "",
  });
  const [imageFile, setImageFile] = useState<File | null>(null);

  function update(f: keyof typeof form, v: string) {
    setForm((p) => {
      const next = { ...p, [f]: v };
      if (f === "barcode" && v.length >= 4 && !p.last4Digits) {
        next.last4Digits = v.slice(-4);
      }
      return next;
    });
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setLoading(true);

    try {
      const barcode = form.barcode.trim();
      const productName = form.productName.trim();
      if (!barcode || !productName) {
        throw new Error("barcode and productName required");
      }

      let productImageAsset = "";
      if (imageFile && imageFile.size > 0) {
        const formData = new FormData();
        formData.append("image", imageFile);
        const res = await fetch("/api/upload-product-image", {
          method: "POST",
          body: formData,
        });
        if (!res.ok) {
          const data = await res.json().catch(() => ({}));
          throw new Error((data?.error as string) ?? "Image upload failed");
        }
        const { url } = await res.json();
        const base =
          process.env.NEXT_PUBLIC_APP_URL ||
          (typeof window !== "undefined" ? window.location.origin : "");
        productImageAsset = url.startsWith("/") && base ? `${base}${url}` : url;
      }

      const last4 = form.last4Digits.trim() || barcode.slice(-4);

      await addDoc(collection(db, "products"), {
        barcode,
        brandName: form.brandName.trim() || "",
        companyName: form.companyName.trim() || "",
        productName,
        manufacturedIn: form.manufacturedIn.trim() || "",
        description: form.description.trim() || "",
        certificateBodies: form.certificateBodies.trim() || "",
        certificateExpiry: form.certificateExpiry.trim() || "",
        ingredients: form.ingredients.trim() || "",
        nutrition: form.nutrition.trim() || "",
        kcalPerUnit: form.kcalPerUnit ? parseFloat(form.kcalPerUnit) : 0,
        productImageAsset,
        last4Digits: last4,
        name: productName,
        imageUrl: productImageAsset,
        createdAt: serverTimestamp(),
      });

      router.push("/dashboard/products");
    } catch (err) {
      console.error(err);
      setError(err instanceof Error ? err.message : "Failed to add product.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      <div className="flex items-center gap-4 mb-6">
        <Link
          href="/dashboard/products"
          className="text-gray-500 hover:text-gray-700"
        >
          ← Back
        </Link>
      </div>

      <h1 className="text-2xl font-bold text-gray-900">Add Product</h1>
      <p className="mt-1 text-gray-500">
        Add product with barcode for scan lookup in Halalens Main.
      </p>

      <form onSubmit={handleSubmit} className="mt-8 max-w-xl space-y-6">
        {error && (
          <div className="p-4 rounded-lg bg-red-50 border border-red-200">
            <p className="text-red-600 text-sm">{error}</p>
          </div>
        )}

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Product Image (productImageAsset)
          </label>
          <input
            type="file"
            accept="image/*"
            onChange={(e) => setImageFile(e.target.files?.[0] ?? null)}
            className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:bg-gray-100 file:text-gray-700"
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label htmlFor="barcode" className="block text-sm font-medium text-gray-700 mb-2">
              Barcode *
            </label>
            <input
              id="barcode"
              type="text"
              value={form.barcode}
              onChange={(e) => update("barcode", e.target.value)}
              required
              className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="e.g. 8901234567890"
            />
            <p className="mt-1 text-xs text-gray-500">
              Used when user scans in Halalens Main.
            </p>
          </div>
          <div>
            <label htmlFor="last4Digits" className="block text-sm font-medium text-gray-700 mb-2">
              Last 4 Digits
            </label>
            <input
              id="last4Digits"
              type="text"
              maxLength={4}
              value={form.last4Digits}
              onChange={(e) => update("last4Digits", e.target.value.replace(/\D/g, ""))}
              className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="Auto from barcode"
            />
          </div>
        </div>

        <div>
          <label htmlFor="productName" className="block text-sm font-medium text-gray-700 mb-2">
            Product Name *
          </label>
          <input
            id="productName"
            type="text"
            value={form.productName}
            onChange={(e) => update("productName", e.target.value)}
            required
            className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            placeholder="e.g. Maggi Pes Sambal Tumis"
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label htmlFor="brandName" className="block text-sm font-medium text-gray-700 mb-2">
              Brand Name
            </label>
            <input
              id="brandName"
              type="text"
              value={form.brandName}
              onChange={(e) => update("brandName", e.target.value)}
              className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="e.g. Maggi"
            />
          </div>
          <div>
            <label htmlFor="companyName" className="block text-sm font-medium text-gray-700 mb-2">
              Company Name
            </label>
            <input
              id="companyName"
              type="text"
              value={form.companyName}
              onChange={(e) => update("companyName", e.target.value)}
              className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="e.g. Nestlé (Malaysia) Berhad"
            />
          </div>
        </div>

        <div>
          <label htmlFor="manufacturedIn" className="block text-sm font-medium text-gray-700 mb-2">
            Manufactured In
          </label>
          <input
            id="manufacturedIn"
            type="text"
            value={form.manufacturedIn}
            onChange={(e) => update("manufacturedIn", e.target.value)}
            className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            placeholder="e.g. Malaysia"
          />
        </div>

        <div>
          <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-2">
            Description
          </label>
          <textarea
            id="description"
            value={form.description}
            onChange={(e) => update("description", e.target.value)}
            rows={2}
            className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            placeholder="Product description"
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label htmlFor="certificateBodies" className="block text-sm font-medium text-gray-700 mb-2">
              Certificate Bodies
            </label>
            <input
              id="certificateBodies"
              type="text"
              value={form.certificateBodies}
              onChange={(e) => update("certificateBodies", e.target.value)}
              className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="e.g. JAKIM"
            />
          </div>
          <div>
            <label htmlFor="certificateExpiry" className="block text-sm font-medium text-gray-700 mb-2">
              Certificate Expiry
            </label>
            <input
              id="certificateExpiry"
              type="text"
              value={form.certificateExpiry}
              onChange={(e) => update("certificateExpiry", e.target.value)}
              className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              placeholder="e.g. 2025-12-31"
            />
          </div>
        </div>

        <div>
          <label htmlFor="ingredients" className="block text-sm font-medium text-gray-700 mb-2">
            Ingredients
          </label>
          <textarea
            id="ingredients"
            value={form.ingredients}
            onChange={(e) => update("ingredients", e.target.value)}
            rows={2}
            className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            placeholder="e.g. Cili, bawang, minyak, rempah ratus..."
          />
        </div>

        <div>
          <label htmlFor="nutrition" className="block text-sm font-medium text-gray-700 mb-2">
            Nutrition
          </label>
          <textarea
            id="nutrition"
            value={form.nutrition}
            onChange={(e) => update("nutrition", e.target.value)}
            rows={2}
            className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            placeholder="e.g. Energy 50 kcal/250ml"
          />
        </div>

        <div>
          <label htmlFor="kcalPerUnit" className="block text-sm font-medium text-gray-700 mb-2">
            kcal/unit
          </label>
          <input
            id="kcalPerUnit"
            type="number"
            step="1"
            min="0"
            value={form.kcalPerUnit}
            onChange={(e) => update("kcalPerUnit", e.target.value)}
            className="w-full max-w-[160px] px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            placeholder="0"
          />
          <p className="mt-1 text-xs text-gray-500">For calorie tracking in Halalens Main</p>
        </div>

        <div className="flex gap-3">
          <button
            type="submit"
            disabled={loading}
            className="px-6 py-3 rounded-lg bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white font-medium"
          >
            {loading ? "Adding..." : "Add Product"}
          </button>
          <Link
            href="/dashboard/products"
            className="px-6 py-3 rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-50 font-medium"
          >
            Cancel
          </Link>
        </div>
      </form>
    </div>
  );
}
