'use client'

import { useEffect, useState, useCallback } from 'react'
import { useParams } from 'next/navigation'

type MenuItem = {
  id: number
  name: string
  description: string
  price: number
  available: boolean
  isBar: boolean
  imageUrl: string | null
}
type Category = { id: number; name: string; items: MenuItem[] }
type CartLine = { item: MenuItem; quantity: number; notes: string }

export default function TablePage() {
  const params = useParams()
  const tableNumber = params.id as string

  const [categories, setCategories] = useState<Category[]>([])
  const [activeCategory, setActiveCategory] = useState<number | null>(null)
  const [cart, setCart] = useState<CartLine[]>([])
  const [view, setView] = useState<'menu' | 'cart' | 'checkout' | 'paying' | 'success'>('menu')
  const [name, setName] = useState('')
  const [contact, setContact] = useState('')
  const [tipPct, setTipPct] = useState(0)
  const [cardNumber, setCardNumber] = useState('4242 4242 4242 4242')
  const [cardExp, setCardExp] = useState('12/28')
  const [cardCvc, setCardCvc] = useState('123')
  const [orderId, setOrderId] = useState<number | null>(null)
  const [orderStatus, setOrderStatus] = useState('new')
  const [error, setError] = useState('')

  useEffect(() => {
    fetch('/api/menu')
      .then((r) => r.json())
      .then((data: Category[]) => {
        setCategories(data)
        if (data.length) setActiveCategory(data[0].id)
      })
  }, [])

  useEffect(() => {
    if (!orderId || view !== 'success') return
    const interval = setInterval(() => {
      fetch(`/api/orders/${orderId}`)
        .then((r) => r.json())
        .then((o) => setOrderStatus(o.status))
    }, 3000)
    return () => clearInterval(interval)
  }, [orderId, view])

  const addToCart = useCallback((item: MenuItem) => {
    setCart((prev) => {
      const existing = prev.find((l) => l.item.id === item.id)
      if (existing) {
        return prev.map((l) => (l.item.id === item.id ? { ...l, quantity: l.quantity + 1 } : l))
      }
      return [...prev, { item, quantity: 1, notes: '' }]
    })
  }, [])

  const removeFromCart = (itemId: number) => {
    setCart((prev) =>
      prev
        .map((l) => (l.item.id === itemId ? { ...l, quantity: l.quantity - 1 } : l))
        .filter((l) => l.quantity > 0)
    )
  }

  const subtotal = cart.reduce((s, l) => s + l.item.price * l.quantity, 0)
  const tip = +(subtotal * (tipPct / 100)).toFixed(2)
  const total = +(subtotal + tip).toFixed(2)
  const cartCount = cart.reduce((s, l) => s + l.quantity, 0)

  const placeOrder = async () => {
    setError('')
    setView('paying')
    try {
      const tableRes = await fetch('/api/tables').then((r) => r.json())
      const table = tableRes.find((t: { number: number }) => t.number === parseInt(tableNumber))
      if (!table) throw new Error('Table not found')

      const payRes = await fetch('/api/payment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ amount: total, cardNumber }),
      })
      const payData = await payRes.json()
      if (!payData.success) throw new Error(payData.error || 'Payment failed')

      const isEmail = contact.includes('@')
      const orderRes = await fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          tableId: table.id,
          customerName: name || 'Guest',
          email: isEmail ? contact : undefined,
          phone: !isEmail ? contact : undefined,
          tip,
          items: cart.map((l) => ({
            menuItemId: l.item.id,
            quantity: l.quantity,
            notes: l.notes,
            price: l.item.price,
            name: l.item.name,
          })),
        }),
      })
      const order = await orderRes.json()
      await fetch(`/api/orders/${order.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ paymentStatus: 'paid' }),
      })

      setOrderId(order.id)
      setOrderStatus('new')
      setView('success')
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Something went wrong')
      setView('checkout')
    }
  }

  const statusLabel: Record<string, string> = {
    new: 'Order Received',
    preparing: 'Being Made',
    ready: 'Ready!',
    completed: 'Delivered — Enjoy!',
  }

  return (
    <div className="min-h-screen bg-black text-white pb-24">
      <header className="sticky top-0 z-20 bg-black/95 backdrop-blur border-b border-zinc-800 px-4 py-3 flex items-center justify-between">
        <div>
          <div className="flex items-center gap-2">
            <span className="font-bold text-lg tracking-wide">MOON TAVERN</span>
          </div>
          <p className="text-xs text-zinc-500">Table {tableNumber}</p>
        </div>
        {view === 'menu' && cartCount > 0 && (
          <button
            onClick={() => setView('cart')}
            className="relative bg-white text-black font-semibold px-4 py-2 rounded-full text-sm"
          >
            View Cart
            <span className="absolute -top-2 -right-2 bg-black border border-white text-white text-xs rounded-full w-6 h-6 flex items-center justify-center">
              {cartCount}
            </span>
          </button>
        )}
      </header>

      {view === 'menu' && (
        <>
          <nav className="flex gap-2 overflow-x-auto px-4 py-3 border-b border-zinc-900 sticky top-[64px] bg-black z-10">
            {categories.map((c) => (
              <button
                key={c.id}
                onClick={() => setActiveCategory(c.id)}
                className={`whitespace-nowrap px-4 py-2 rounded-full text-sm font-medium transition ${
                  activeCategory === c.id
                    ? 'bg-white text-black'
                    : 'bg-zinc-900 text-zinc-300 border border-zinc-700'
                }`}
              >
                {c.name}
              </button>
            ))}
          </nav>

          <main className="px-4 py-4 space-y-3">
            {categories
              .filter((c) => c.id === activeCategory)
              .map((c) => (
                <div key={c.id} className="space-y-3">
                  {c.items.map((item) => (
                    <div
                      key={item.id}
                      className={`bg-zinc-900 border border-zinc-700 rounded-xl p-4 flex justify-between items-start gap-3 ${
                        !item.available ? 'opacity-40' : ''
                      }`}
                    >
                      {item.imageUrl && (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img src={item.imageUrl} alt={item.name} className="w-20 h-20 object-cover rounded-lg border border-zinc-700 shrink-0" />
                      )}
                      <div className="flex-1">
                        <h3 className="font-semibold text-white">{item.name}</h3>
                        <p className="text-sm text-zinc-400 mt-0.5">{item.description}</p>
                        <p className="text-white font-bold mt-2">${item.price.toFixed(2)}</p>
                      </div>
                      <button
                        disabled={!item.available}
                        onClick={() => addToCart(item)}
                        className="bg-white hover:bg-zinc-200 disabled:bg-zinc-800 disabled:text-zinc-500 text-black text-sm font-semibold px-4 py-2 rounded-lg shrink-0"
                      >
                        {item.available ? 'Add' : 'Sold Out'}
                      </button>
                    </div>
                  ))}
                </div>
              ))}
          </main>

          {cartCount > 0 && (
            <button
              onClick={() => setView('cart')}
              className="fixed bottom-0 left-0 right-0 bg-white text-black font-bold py-4 flex items-center justify-center gap-2 shadow-lg"
            >
              View Cart ({cartCount}) — ${subtotal.toFixed(2)}
            </button>
          )}
        </>
      )}

      {view === 'cart' && (
        <main className="px-4 py-4">
          <button onClick={() => setView('menu')} className="text-zinc-400 text-sm mb-4">
            ← Back to Menu
          </button>
          <h2 className="text-xl font-bold mb-4">Your Order</h2>
          <div className="space-y-3">
            {cart.map((line) => (
              <div key={line.item.id} className="bg-zinc-900 border border-zinc-700 rounded-xl p-3 flex justify-between items-center">
                <div>
                  <p className="font-medium">{line.item.name}</p>
                  <p className="text-sm text-zinc-400">${line.item.price.toFixed(2)} each</p>
                </div>
                <div className="flex items-center gap-3">
                  <button onClick={() => removeFromCart(line.item.id)} className="w-8 h-8 bg-zinc-800 border border-zinc-600 rounded-full">−</button>
                  <span className="w-6 text-center">{line.quantity}</span>
                  <button onClick={() => addToCart(line.item)} className="w-8 h-8 bg-zinc-800 border border-zinc-600 rounded-full">+</button>
                </div>
              </div>
            ))}
          </div>

          {cart.length === 0 && <p className="text-zinc-500 text-center mt-12">Your cart is empty.</p>}

          {cart.length > 0 && (
            <>
              <div className="mt-6 border-t border-zinc-800 pt-4 space-y-1 text-sm">
                <div className="flex justify-between"><span className="text-zinc-400">Subtotal</span><span>${subtotal.toFixed(2)}</span></div>
              </div>
              <button
                onClick={() => setView('checkout')}
                className="w-full mt-6 bg-white text-black font-bold py-3 rounded-xl"
              >
                Checkout — ${subtotal.toFixed(2)}
              </button>
            </>
          )}
        </main>
      )}

      {view === 'checkout' && (
        <main className="px-4 py-4 max-w-md mx-auto">
          <button onClick={() => setView('cart')} className="text-zinc-400 text-sm mb-4">
            ← Back to Cart
          </button>
          <h2 className="text-xl font-bold mb-4">Checkout</h2>

          {error && <div className="bg-zinc-900 border border-white text-white text-sm rounded-lg p-3 mb-4">{error}</div>}

          <div className="space-y-3">
            <input
              className="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-4 py-3 text-sm"
              placeholder="Your name"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
            <input
              className="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-4 py-3 text-sm"
              placeholder="Email or phone (for receipt)"
              value={contact}
              onChange={(e) => setContact(e.target.value)}
            />

            <div>
              <p className="text-sm text-zinc-400 mb-2">Add a tip (optional)</p>
              <div className="flex gap-2">
                {[0, 15, 18, 20, 25].map((pct) => (
                  <button
                    key={pct}
                    onClick={() => setTipPct(pct)}
                    className={`flex-1 py-2 rounded-lg text-sm font-medium ${
                      tipPct === pct ? 'bg-white text-black' : 'bg-zinc-900 border border-zinc-700 text-zinc-300'
                    }`}
                  >
                    {pct === 0 ? 'No Tip' : `${pct}%`}
                  </button>
                ))}
              </div>
            </div>

            <div className="border-t border-zinc-800 pt-3 mt-3">
              <p className="text-sm text-zinc-400 mb-2">Payment — Authorize.Net (demo)</p>
              <input
                className="w-full bg-zinc-900 border border-zinc-700 rounded-lg px-4 py-3 text-sm mb-2"
                placeholder="Card number"
                value={cardNumber}
                onChange={(e) => setCardNumber(e.target.value)}
              />
              <div className="flex gap-2">
                <input
                  className="flex-1 bg-zinc-900 border border-zinc-700 rounded-lg px-4 py-3 text-sm"
                  placeholder="MM/YY"
                  value={cardExp}
                  onChange={(e) => setCardExp(e.target.value)}
                />
                <input
                  className="flex-1 bg-zinc-900 border border-zinc-700 rounded-lg px-4 py-3 text-sm"
                  placeholder="CVC"
                  value={cardCvc}
                  onChange={(e) => setCardCvc(e.target.value)}
                />
              </div>
              <p className="text-xs text-zinc-500 mt-2">Demo mode — no real charge will be made.</p>
            </div>

            <div className="border-t border-zinc-800 pt-3 space-y-1 text-sm">
              <div className="flex justify-between"><span className="text-zinc-400">Subtotal</span><span>${subtotal.toFixed(2)}</span></div>
              <div className="flex justify-between"><span className="text-zinc-400">Tip {tipPct > 0 ? `(${tipPct}%)` : ''}</span><span>${tip.toFixed(2)}</span></div>
              <div className="flex justify-between font-bold text-base pt-1"><span>Total</span><span>${total.toFixed(2)}</span></div>
            </div>

            <button
              onClick={placeOrder}
              disabled={!name || !contact}
              className="w-full bg-white disabled:bg-zinc-800 disabled:text-zinc-500 text-black font-bold py-3 rounded-xl mt-2"
            >
              Pay & Place Order — ${total.toFixed(2)}
            </button>
          </div>
        </main>
      )}

      {view === 'paying' && (
        <main className="flex flex-col items-center justify-center h-[80vh] gap-4">
          <div className="w-12 h-12 border-4 border-white border-t-transparent rounded-full animate-spin" />
          <p className="text-zinc-300">Processing payment…</p>
        </main>
      )}

      {view === 'success' && (
        <main className="flex flex-col items-center justify-center h-[80vh] gap-4 px-6 text-center">
          <h2 className="text-2xl font-bold">Order Placed!</h2>
          <p className="text-zinc-400">Table {tableNumber} · Order #{orderId}</p>
          <div className="bg-zinc-900 border border-zinc-700 rounded-xl px-6 py-4 mt-2 w-full max-w-xs">
            <p className="text-sm text-zinc-400">Status</p>
            <p className="text-xl font-bold text-white">{statusLabel[orderStatus] || orderStatus}</p>
          </div>
          <p className="text-xs text-zinc-500 mt-4">Receipt sent to {contact}</p>
          <button
            onClick={() => {
              setCart([])
              setView('menu')
            }}
            className="mt-6 text-zinc-300 text-sm underline"
          >
            ← Order More
          </button>
        </main>
      )}
    </div>
  )
}
