'use client';

import { useEffect, useMemo, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch, adminApiOpenPdf } from '@/lib/api';
import { useToast } from '@/lib/toast';
import { TableSkeleton } from '@/components/Skeletons';
import { Search, Plus, Minus, Trash2 } from 'lucide-react';

type Product = { id: number; sku: string; name: string; category: string; priceTzs: string; stockQty: number; vatEnabled: boolean };
type CartLine = { productId: number; sku: string; name: string; priceTzs: number; stockQty: number; qty: number };
type SaleRow = {
  id: number; saleNo: string; totalTzs: string; paymentMethod: string; createdAt: string;
  cashier: { name: string } | null; itemsJson: { name: string; qty: number }[];
};

const PAYMENT_METHODS = ['CASH', 'MPESA', 'TIGO_PESA', 'BANK', 'CARD'];

export default function PosPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [products, setProducts] = useState<Product[]>([]);
  const [search, setSearch] = useState('');
  const [cart, setCart] = useState<CartLine[]>([]);
  const [paymentMethod, setPaymentMethod] = useState('CASH');
  const [customerName, setCustomerName] = useState('');
  const [customerPhone, setCustomerPhone] = useState('');
  const [loading, setLoading] = useState(true);
  const [checking, setChecking] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [sales, setSales] = useState<SaleRow[]>([]);
  const [totalToday, setTotalToday] = useState(0);
  const [topProducts, setTopProducts] = useState<{ sku: string; name: string; qty: number; revenueTzs: number }[]>([]);

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const [p, s] = await Promise.all([
        adminApiFetch('/admin/pos/products', accessToken, appSecretProof),
        adminApiFetch('/admin/pos/sales', accessToken, appSecretProof),
      ]);
      setProducts(p.products || []);
      setSales(s.sales || []);
      setTotalToday(s.totalToday || 0);
      setTopProducts(s.topProducts || []);
    } catch {
      setError('You do not have permission to use the till.');
    } finally {
      setLoading(false);
    }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return products;
    return products.filter((p) => p.name.toLowerCase().includes(q) || p.sku.toLowerCase().includes(q));
  }, [products, search]);

  function addToCart(p: Product) {
    setCart((c) => {
      const existing = c.find((l) => l.productId === p.id);
      if (existing) {
        if (existing.qty >= p.stockQty) { show('error', `Only ${p.stockQty} of ${p.name} in stock.`); return c; }
        return c.map((l) => l.productId === p.id ? { ...l, qty: l.qty + 1 } : l);
      }
      return [...c, { productId: p.id, sku: p.sku, name: p.name, priceTzs: Number(p.priceTzs), stockQty: p.stockQty, qty: 1 }];
    });
  }

  function changeQty(productId: number, delta: number) {
    setCart((c) => c
      .map((l) => l.productId === productId ? { ...l, qty: Math.min(l.stockQty, Math.max(1, l.qty + delta)) } : l));
  }

  function removeLine(productId: number) {
    setCart((c) => c.filter((l) => l.productId !== productId));
  }

  const cartTotal = cart.reduce((s, l) => s + l.priceTzs * l.qty, 0);

  async function checkout() {
    if (!accessToken || !appSecretProof || cart.length === 0) return;
    setChecking(true);
    try {
      const d = await adminApiFetch('/admin/pos/sales', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({
          items: cart.map((l) => ({ productId: l.productId, qty: l.qty })),
          paymentMethod,
          customerName: customerName || undefined,
          customerPhone: customerPhone || undefined,
        }),
      });
      show('success', `Sale ${d.sale.saleNo} complete — TZS ${Number(d.sale.totalTzs).toLocaleString()}.`);
      setCart([]);
      setCustomerName('');
      setCustomerPhone('');
      load();
      try { await adminApiOpenPdf(`/admin/pos/sales/${d.sale.id}/receipt.pdf`, accessToken, appSecretProof); } catch { /* receipt is a bonus, don't block on it */ }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : '';
      show('error', message === 'INSUFFICIENT_STOCK' ? 'Not enough stock for one of these items — refresh and try again.' : 'Could not complete the sale.');
    } finally {
      setChecking(false);
    }
  }

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

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
      {/* Product picker */}
      <div className="lg:col-span-2 space-y-4">
        <div>
          <h1 className="text-xl font-bold mb-1">POS &bull; Shop Till</h1>
          <p className="text-xs text-gray-500">Walk-in counter sales — deducts stock and posts to Cashbook automatically, no website checkout involved.</p>
        </div>

        <div className="relative">
          <Search className="absolute left-3 top-2.5 text-gray-400" size={16} />
          <input
            value={search} onChange={(e) => setSearch(e.target.value)}
            placeholder="Search product name or SKU…"
            className="pl-9 pr-4 py-2 w-full bg-white border border-brand-border rounded-full text-sm transition-colors focus:outline-none focus:border-brand-red"
          />
        </div>

        {loading ? <TableSkeleton rows={6} cols={3} /> : (
          <div className="grid grid-cols-2 md:grid-cols-3 gap-2 max-h-[420px] overflow-y-auto pr-1">
            {filtered.map((p) => (
              <button
                key={p.id} onClick={() => addToCart(p)}
                className="text-left bg-white border border-brand-border rounded-xl p-3 transition-all hover:shadow-md hover:-translate-y-0.5 hover:border-brand-red"
              >
                <p className="text-xs font-semibold truncate">{p.name}</p>
                <p className="text-[10px] text-gray-400">{p.sku}</p>
                <p className="text-sm font-bold mt-1">TZS {Number(p.priceTzs).toLocaleString()}</p>
                <p className="text-[10px] text-gray-400">{p.stockQty} in stock</p>
              </button>
            ))}
            {filtered.length === 0 && <p className="text-xs text-gray-400 col-span-3 py-6 text-center">No matching products.</p>}
          </div>
        )}

        <div className="bg-white border border-brand-border rounded-xl p-4">
          <div className="flex justify-between items-center mb-2">
            <p className="text-sm font-semibold">Sold Today</p>
            <p className="text-sm font-bold">TZS {totalToday.toLocaleString()}</p>
          </div>
          {topProducts.length > 0 && (
            <div className="flex flex-wrap gap-1 mb-3">
              {topProducts.slice(0, 6).map((t) => (
                <span key={t.sku} className="text-[10px] bg-brand-bg border border-brand-border rounded-full px-2 py-0.5">{t.name} &times;{t.qty}</span>
              ))}
            </div>
          )}
          <div className="max-h-[160px] overflow-y-auto space-y-1">
            {sales.map((s) => (
              <div key={s.id} className="flex justify-between text-xs border-t border-brand-border pt-1.5 first:border-t-0 first:pt-0 animate-fadeInUp">
                <span className="text-gray-500">{new Date(s.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} &bull; {s.cashier?.name || '—'} &bull; {s.itemsJson.map((i) => `${i.name} x${i.qty}`).join(', ')}</span>
                <span className="font-semibold">TZS {Number(s.totalTzs).toLocaleString()}</span>
              </div>
            ))}
            {sales.length === 0 && <p className="text-xs text-gray-400">No sales rung up yet today.</p>}
          </div>
        </div>
      </div>

      {/* Cart / checkout */}
      <div className="bg-white border border-brand-border rounded-xl p-4 h-fit sticky top-4">
        <p className="text-sm font-bold mb-3">Current Sale</p>
        <div className="space-y-2 max-h-[300px] overflow-y-auto mb-3">
          {cart.map((l) => (
            <div key={l.productId} className="flex items-center justify-between text-xs animate-fadeInUp">
              <div className="flex-1 min-w-0">
                <p className="truncate font-medium">{l.name}</p>
                <p className="text-gray-400">TZS {l.priceTzs.toLocaleString()} each</p>
              </div>
              <div className="flex items-center gap-1">
                <button onClick={() => changeQty(l.productId, -1)} className="p-1 border border-brand-border rounded transition-colors hover:bg-brand-bg"><Minus size={10} /></button>
                <span className="w-5 text-center">{l.qty}</span>
                <button onClick={() => changeQty(l.productId, 1)} className="p-1 border border-brand-border rounded transition-colors hover:bg-brand-bg"><Plus size={10} /></button>
                <button onClick={() => removeLine(l.productId)} className="p-1 text-brand-red transition-colors hover:text-red-800"><Trash2 size={12} /></button>
              </div>
            </div>
          ))}
          {cart.length === 0 && <p className="text-xs text-gray-400 py-4 text-center">Tap a product to add it.</p>}
        </div>

        <div className="border-t border-brand-border pt-3 space-y-2">
          <div className="flex justify-between text-sm font-bold"><span>Total</span><span>TZS {cartTotal.toLocaleString()}</span></div>

          <select value={paymentMethod} onChange={(e) => setPaymentMethod(e.target.value)} className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs">
            {PAYMENT_METHODS.map((m) => <option key={m} value={m}>{m.replace('_', ' ')}</option>)}
          </select>
          <input placeholder="Customer name (optional)" value={customerName} onChange={(e) => setCustomerName(e.target.value)}
            className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />
          <input placeholder="Customer phone (optional)" value={customerPhone} onChange={(e) => setCustomerPhone(e.target.value)}
            className="w-full border border-brand-border rounded-lg px-2 py-1.5 text-xs" />

          <button
            onClick={checkout} disabled={cart.length === 0 || checking}
            className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-40 transition-transform hover:scale-[1.02] active:scale-[0.98]"
          >
            {checking ? 'Completing…' : 'Complete Sale'}
          </button>
        </div>
      </div>
    </div>
  );
}
