"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { ArrowLeft, Save } from "lucide-react";
import toast from "react-hot-toast";

const petTypes = ["dog", "cat", "bird", "fish", "small", "reptile", "all"];
const categories = ["Food & Nutrition", "Toys & Enrichment", "Health & Wellness", "Grooming", "Beds & Furniture", "Travel & Accessories", "Technology", "Clothing & Accessories"];

export default function NewProductPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({
    name: "", description: "", price: "", salePrice: "",
    category: categories[0], petType: "dog",
    images: "", stock: "100",
    featured: false, active: true,
    cjProductId: "", cjVariantId: "",
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    const res = await fetch("/api/admin/products", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ...form,
        price: parseFloat(form.price),
        salePrice: form.salePrice ? parseFloat(form.salePrice) : null,
        stock: parseInt(form.stock),
        images: form.images ? JSON.stringify(form.images.split("\n").filter(Boolean)) : "[]",
      }),
    });
    if (res.ok) {
      toast.success("Product created!");
      router.push("/admin/products");
    } else {
      const data = await res.json().catch(() => null);
      toast.error(data?.error ?? "Failed to create product.");
    }
    setLoading(false);
  };

  return (
    <div className="p-8 max-w-3xl">
      <div className="flex items-center gap-4 mb-8">
        <Link href="/admin/products" className="p-2 hover:bg-gray-200 rounded-xl transition-colors">
          <ArrowLeft className="h-5 w-5 text-gray-600" />
        </Link>
        <h1 className="text-2xl font-bold text-gray-900">Add New Product</h1>
      </div>

      <form onSubmit={handleSubmit} className="bg-white rounded-2xl shadow-sm p-8 space-y-6">
        <div>
          <label className="label">Product Name *</label>
          <input required value={form.name} onChange={e => setForm({...form, name: e.target.value})} className="input-field" placeholder="e.g. Premium Dog Kibble" />
        </div>
        <div>
          <label className="label">Description *</label>
          <textarea required rows={4} value={form.description} onChange={e => setForm({...form, description: e.target.value})} className="input-field resize-none" />
        </div>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="label">Price ($) *</label>
            <input type="number" step="0.01" required value={form.price} onChange={e => setForm({...form, price: e.target.value})} className="input-field" placeholder="29.99" />
          </div>
          <div>
            <label className="label">Sale Price ($)</label>
            <input type="number" step="0.01" value={form.salePrice} onChange={e => setForm({...form, salePrice: e.target.value})} className="input-field" placeholder="Optional" />
          </div>
        </div>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="label">Category *</label>
            <select value={form.category} onChange={e => setForm({...form, category: e.target.value})} className="input-field">
              {categories.map(c => <option key={c}>{c}</option>)}
            </select>
          </div>
          <div>
            <label className="label">Pet Type *</label>
            <select value={form.petType} onChange={e => setForm({...form, petType: e.target.value})} className="input-field">
              {petTypes.map(p => <option key={p} value={p} className="capitalize">{p}</option>)}
            </select>
          </div>
        </div>
        <div>
          <label className="label">Stock Quantity *</label>
          <input type="number" required value={form.stock} onChange={e => setForm({...form, stock: e.target.value})} className="input-field" />
        </div>
        <div>
          <label className="label">Image URLs (one per line)</label>
          <textarea rows={3} value={form.images} onChange={e => setForm({...form, images: e.target.value})} className="input-field resize-none" placeholder="https://example.com/image.jpg" />
        </div>
        <div className="flex gap-6">
          <label className="flex items-center gap-2 cursor-pointer">
            <input type="checkbox" checked={form.featured} onChange={e => setForm({...form, featured: e.target.checked})} className="w-4 h-4 rounded accent-primary-500" />
            <span className="text-sm font-medium text-gray-700">Featured Product</span>
          </label>
          <label className="flex items-center gap-2 cursor-pointer">
            <input type="checkbox" checked={form.active} onChange={e => setForm({...form, active: e.target.checked})} className="w-4 h-4 rounded accent-primary-500" />
            <span className="text-sm font-medium text-gray-700">Active</span>
          </label>
        </div>
        {/* CJ Dropshipping */}
        <div className="border-t border-gray-100 pt-5 mt-5">
          <h3 className="text-sm font-bold text-gray-900 uppercase tracking-wide mb-3">CJ Dropshipping</h3>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="label">CJ Product ID</label>
              <input type="text" value={form.cjProductId} onChange={e => setForm({...form, cjProductId: e.target.value})} className="input-field font-mono text-xs" placeholder="e.g. 1OE14F00021A73" />
            </div>
            <div>
              <label className="label">CJ Variant ID</label>
              <input type="text" value={form.cjVariantId} onChange={e => setForm({...form, cjVariantId: e.target.value})} className="input-field font-mono text-xs" placeholder="e.g. 92511400-C758-4474-..." />
            </div>
          </div>
          <p className="text-xs text-gray-400 mt-2">
            The <strong>Variant ID</strong> is what actually gets ordered — a product without one is never forwarded to CJ.
            Find both in CJ under the product&apos;s variant list. Leave blank for manually fulfilled products.
          </p>
        </div>
        <div className="flex gap-3 pt-2">
          <Link href="/admin/products" className="btn-outline">Cancel</Link>
          <button type="submit" disabled={loading} className="btn-primary disabled:opacity-70">
            <Save className="h-4 w-4" />
            {loading ? "Saving..." : "Save Product"}
          </button>
        </div>
      </form>
    </div>
  );
}
