'use client';

import { useEffect, useState } from 'react';
import { Eye, EyeOff, Save } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { useLiveRefresh } from '@/lib/realtime';
import { TableSkeleton } from '@/components/Skeletons';

type Product = { id: number; sku: string; name: string; category: string; priceTzs: number; showPrice: boolean; isPublished: boolean; stockQty: number };
type Global = { showPrices: boolean; hiddenLabel: string };

export default function PricesPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [products, setProducts] = useState<Product[]>([]);
  const [global, setGlobal] = useState<Global>({ showPrices: true, hiddenLabel: 'Request a quote' });
  const [loading, setLoading] = useState(true);
  const [q, setQ] = useState('');
  const [edited, setEdited] = useState<Record<number, string>>({});
  const [selected, setSelected] = useState<Set<number>>(new Set());

  async function load() {
    if (!accessToken || !appSecretProof) return;
    try {
      const d = await adminApiFetch('/admin/prices', accessToken, appSecretProof);
      setProducts(d.products); setGlobal(d.global);
    } finally { setLoading(false); }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps
  useLiveRefresh(['prices', 'products'], load);

  async function saveGlobal(next: Global) {
    if (!accessToken || !appSecretProof) return;
    setGlobal(next);
    try { await adminApiFetch('/admin/prices/global', accessToken, appSecretProof, { method: 'PUT', body: JSON.stringify(next) }); show('success', 'Website price visibility updated.'); }
    catch { show('error', 'Could not save that setting.'); }
  }

  async function toggle(p: Product, field: 'showPrice' | 'isPublished') {
    if (!accessToken || !appSecretProof) return;
    const next = { [field]: !p[field] };
    setProducts((list) => list.map((x) => (x.id === p.id ? { ...x, ...next } : x)));
    try { await adminApiFetch(`/admin/prices/${p.id}`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify(next) }); }
    catch { show('error', 'Could not save that change.'); load(); }
  }

  async function savePrice(p: Product) {
    const raw = edited[p.id]; if (raw === undefined || !accessToken || !appSecretProof) return;
    const priceTzs = Number(raw.replace(/,/g, ''));
    if (!priceTzs || priceTzs <= 0) return show('error', 'Enter a valid price.');
    try {
      await adminApiFetch(`/admin/prices/${p.id}`, accessToken, appSecretProof, { method: 'PATCH', body: JSON.stringify({ priceTzs }) });
      setProducts((list) => list.map((x) => (x.id === p.id ? { ...x, priceTzs } : x)));
      setEdited((e) => { const n = { ...e }; delete n[p.id]; return n; });
      show('success', `${p.name} price updated.`);
    } catch { show('error', 'Could not save that price.'); }
  }

  async function bulk(action: 'SHOW' | 'HIDE' | 'PUBLISH' | 'UNPUBLISH') {
    if (!accessToken || !appSecretProof || selected.size === 0) return;
    try { await adminApiFetch('/admin/prices/bulk', accessToken, appSecretProof, { method: 'POST', body: JSON.stringify({ ids: [...selected], action }) }); show('success', `Updated ${selected.size} product(s).`); setSelected(new Set()); load(); }
    catch { show('error', 'Bulk update failed.'); }
  }

  const filtered = products.filter((p) => !q.trim() || p.name.toLowerCase().includes(q.toLowerCase()) || p.sku.toLowerCase().includes(q.toLowerCase()));

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-bold">Price Manager &bull; controls what the website shows</h1>

      <div className="bg-white border border-brand-border rounded-xl p-4 flex flex-wrap items-center gap-4">
        <label className="flex items-center gap-2 text-sm font-semibold">
          <input type="checkbox" checked={global.showPrices} onChange={(e) => saveGlobal({ ...global, showPrices: e.target.checked })} className="w-4 h-4 accent-brand-red" />
          Show prices on the website
        </label>
        {!global.showPrices && <input value={global.hiddenLabel} onChange={(e) => setGlobal({ ...global, hiddenLabel: e.target.value })} onBlur={() => saveGlobal(global)} placeholder="Text shown instead of price" className="border border-brand-border rounded-lg px-2 py-1 text-xs" />}
        <p className="text-[11px] text-gray-400">{global.showPrices ? 'Individual products can still be hidden below.' : 'No prices show anywhere on the site while this is off, regardless of per-product settings.'}</p>
      </div>

      <div className="flex items-center gap-2">
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search product or SKU…" className="border border-brand-border rounded-lg px-3 py-1.5 text-sm w-64" />
        {selected.size > 0 && (
          <div className="flex gap-1.5 text-xs">
            <button onClick={() => bulk('SHOW')} className="border border-brand-border rounded-full px-2 py-1 hover:bg-brand-bg">Show prices</button>
            <button onClick={() => bulk('HIDE')} className="border border-brand-border rounded-full px-2 py-1 hover:bg-brand-bg">Hide prices</button>
            <button onClick={() => bulk('PUBLISH')} className="border border-brand-border rounded-full px-2 py-1 hover:bg-brand-bg">Publish</button>
            <button onClick={() => bulk('UNPUBLISH')} className="border border-brand-border rounded-full px-2 py-1 hover:bg-brand-bg">Unpublish</button>
            <span className="text-gray-400 self-center">{selected.size} selected</span>
          </div>
        )}
      </div>

      {loading ? <TableSkeleton rows={8} cols={6} /> : (
        <div className="bg-white border border-brand-border rounded-xl overflow-hidden">
          <table className="w-full text-xs">
            <thead className="bg-brand-bg text-gray-500"><tr>
              <th className="p-2 w-8"><input type="checkbox" onChange={(e) => setSelected(e.target.checked ? new Set(filtered.map((p) => p.id)) : new Set())} /></th>
              <th className="text-left p-2">Product</th><th className="text-left p-2">Category</th><th className="text-right p-2">Price (TZS)</th>
              <th className="text-center p-2">On website</th><th className="text-center p-2">Show price</th><th className="text-right p-2">Stock</th>
            </tr></thead>
            <tbody>
              {filtered.map((p) => (
                <tr key={p.id} className="border-t border-brand-border">
                  <td className="p-2"><input type="checkbox" checked={selected.has(p.id)} onChange={(e) => setSelected((s) => { const n = new Set(s); e.target.checked ? n.add(p.id) : n.delete(p.id); return n; })} /></td>
                  <td className="p-2"><p className="font-medium">{p.name}</p><p className="text-gray-400">{p.sku}</p></td>
                  <td className="p-2">{p.category}</td>
                  <td className="p-2 text-right">
                    <div className="flex items-center justify-end gap-1">
                      <input value={edited[p.id] ?? p.priceTzs.toLocaleString()} onChange={(e) => setEdited((ed) => ({ ...ed, [p.id]: e.target.value }))}
                        onKeyDown={(e) => e.key === 'Enter' && savePrice(p)} className="w-28 border border-brand-border rounded px-1.5 py-1 text-right" />
                      {edited[p.id] !== undefined && <button onClick={() => savePrice(p)} title="Save"><Save size={13} className="text-brand-red" /></button>}
                    </div>
                  </td>
                  <td className="p-2 text-center"><button onClick={() => toggle(p, 'isPublished')} className={p.isPublished ? 'text-green-600' : 'text-gray-300'}>{p.isPublished ? <Eye size={15} /> : <EyeOff size={15} />}</button></td>
                  <td className="p-2 text-center"><button onClick={() => toggle(p, 'showPrice')} className={p.showPrice ? 'text-green-600' : 'text-gray-300'} disabled={!p.isPublished}>{p.showPrice ? <Eye size={15} /> : <EyeOff size={15} />}</button></td>
                  <td className="p-2 text-right">{p.stockQty}</td>
                </tr>
              ))}
            </tbody>
          </table>
          {filtered.length === 0 && <p className="text-xs text-gray-400 p-4">No products match.</p>}
        </div>
      )}
    </div>
  );
}
