'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { TableSkeleton } from '@/components/Skeletons';
import AttachmentPicker, { Attachment } from '@/components/AttachmentPicker';

type Product = {
  id: number; sku: string; name: string; category: string; priceTzs: string;
  stockQty: number; shelfLocation: string | null; lowStockAlert: number; badge: string | null;
};

const emptyForm = {
  sku: '', name: '', category: '', priceTzs: '', stockQty: '0', shelfLocation: '', lowStockAlert: '5', badge: '',
  variants: '', description: '', specs: '',
};

export default function ProductsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [images, setImages] = useState<Attachment[]>([]);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState(emptyForm);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const d = await adminApiFetch('/admin/products', accessToken, appSecretProof);
      setProducts(d.products || []);
    } catch {
      setError('You do not have permission to view this page.');
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof) return;
    setSaving(true);
    try {
      await adminApiFetch('/admin/products', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({
          ...form,
          priceTzs: Number(form.priceTzs),
          stockQty: Number(form.stockQty),
          lowStockAlert: Number(form.lowStockAlert),
          variants: form.variants ? form.variants.split(',').map((v) => v.trim()).filter(Boolean) : undefined,
          images: images.length ? images.map((i) => i.url) : undefined,
        }),
      });
      show('success', `${form.name} added to the catalog.`);
      setForm(emptyForm);
      setImages([]);
      setShowForm(false);
      load();
    } catch {
      show('error', 'Could not save that product — check the SKU is unique.');
    } finally {
      setSaving(false);
    }
  }

  async function remove(id: number, name: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/products/${id}`, accessToken, appSecretProof, { method: 'DELETE' });
      setProducts((p) => p.filter((row) => row.id !== id));
      show('success', `${name} deleted.`);
    } catch {
      show('error', 'Could not delete that product.');
    }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div>
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-xl font-bold">Shop Products &bull; {products.length} &bull; admin.lussavara.co.tz</h1>
        <button onClick={() => setShowForm((s) => !s)} className="bg-brand-red text-white px-4 py-2 rounded-full text-sm transition-transform hover:scale-[1.03] active:scale-[0.98]">
          {showForm ? 'Close' : '+ Add Product'}
        </button>
      </div>

      {showForm && (
        <form onSubmit={submit} className="bg-white border border-brand-border rounded-xl p-4 mb-4 grid grid-cols-2 md:grid-cols-4 gap-3 animate-scaleIn">
          <input required placeholder="SKU (LUS-HYD-BR-001)" value={form.sku} onChange={(e) => setForm({ ...form, sku: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input required placeholder="Name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input required placeholder="Category" value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input required type="number" placeholder="Price TZS" value={form.priceTzs} onChange={(e) => setForm({ ...form, priceTzs: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input type="number" placeholder="Stock" value={form.stockQty} onChange={(e) => setForm({ ...form, stockQty: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input placeholder="Shelf (A1)" value={form.shelfLocation} onChange={(e) => setForm({ ...form, shelfLocation: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input type="number" placeholder="Low stock alert" value={form.lowStockAlert} onChange={(e) => setForm({ ...form, lowStockAlert: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input placeholder="Badge (UL Listed, Best Seller…)" value={form.badge} onChange={(e) => setForm({ ...form, badge: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input placeholder="Variants (1.5&quot;, 2&quot;, 2.5&quot; — comma separated)" value={form.variants} onChange={(e) => setForm({ ...form, variants: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs col-span-2" />
          <textarea placeholder="Description" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs col-span-2 md:col-span-4" rows={2} />
          <textarea placeholder="Specs (NFPA / BS references)" value={form.specs} onChange={(e) => setForm({ ...form, specs: e.target.value })} className="border border-brand-border rounded-lg px-2 py-1.5 text-xs col-span-2 md:col-span-4" rows={2} />
          <div className="col-span-2 md:col-span-4">
            <AttachmentPicker attachments={images} onChange={setImages} />
          </div>
          <button disabled={saving} className="col-span-2 md:col-span-4 bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60">{saving ? 'Saving…' : 'Save Product'}</button>
        </form>
      )}

      {loading ? <TableSkeleton rows={6} cols={6} /> : (
        <div className="bg-white rounded-xl border border-brand-border overflow-hidden">
          <table className="w-full text-xs">
            <thead className="bg-brand-bg"><tr>
              <th className="p-3 text-left">SKU &bull; Name</th>
              <th className="p-3 text-left">Category</th>
              <th className="p-3 text-left">Price TZS</th>
              <th className="p-3 text-left">Stock</th>
              <th className="p-3 text-left">Badge</th>
              <th className="p-3 text-left">Actions</th>
            </tr></thead>
            <tbody>
              {products.map((p) => (
                <tr key={p.id} className={`border-t border-brand-border transition-colors ${p.stockQty <= p.lowStockAlert ? 'bg-red-50 hover:bg-red-100' : 'hover:bg-brand-bg'}`}>
                  <td className="p-3"><p className="font-mono text-[10px]">{p.sku}</p><p className="font-semibold">{p.name}</p></td>
                  <td className="p-3">{p.category}</td>
                  <td className="p-3 font-semibold">TZS {Number(p.priceTzs).toLocaleString()}</td>
                  <td className="p-3">{p.stockQty} &bull; {p.shelfLocation || '—'}</td>
                  <td className="p-3">{p.badge && <span className="bg-brand-red/10 text-brand-red px-2 py-0.5 rounded-full text-[10px]">{p.badge}</span>}</td>
                  <td className="p-3"><button onClick={() => remove(p.id, p.name)} className="text-brand-red transition-colors hover:text-red-800">Delete</button></td>
                </tr>
              ))}
              {products.length === 0 && <tr><td colSpan={6} className="p-6 text-center text-gray-400">No products yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
