'use client'

import { useEffect, useState } from 'react'
import { Plus, Trash2, QrCode, Download, Loader2, Key, Printer, X, Copy, Check, List, Map, ExternalLink, RefreshCw } from 'lucide-react'
import toast from 'react-hot-toast'
import { printAccessCode, ThermalPrintOptions } from '@/lib/print-receipt'
import { useThermalPrinter } from '@/hooks/useThermalPrinter'
import Pagination, { PaginationData } from '@/components/Pagination'
import FloorPlanEditor from '@/components/floor-plan/FloorPlanEditor'

export default function TablesPage() {
  const [activeTab, setActiveTab] = useState<'list' | 'floorplan'>('list')
  const [stores, setStores] = useState<any[]>([])
  const [tables, setTables] = useState<any[]>([])
  const [selectedStore, setSelectedStore] = useState('')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [newTable, setNewTable] = useState({ number: '', name: '', capacity: '4' })
  const [regeneratingQR, setRegeneratingQR] = useState(false)
  const [orderProtectionEnabled, setOrderProtectionEnabled] = useState(false)

  // Access code state
  const [accessCodes, setAccessCodes] = useState<any[]>([])
  const [generatingCode, setGeneratingCode] = useState(false)
  const [copiedCode, setCopiedCode] = useState('')
  const [restaurantName, setRestaurantName] = useState('')
  const [storeName, setStoreName] = useState('')
  const [tablePagination, setTablePagination] = useState<PaginationData>({ page: 1, limit: 50, total: 0, totalPages: 0 })
  const printer = useThermalPrinter()
  const [printerSettings, setPrinterSettings] = useState({
    thermal_printer_enabled: 'false',
    thermal_paper_width: '80mm',
    thermal_auto_print_receipt: 'false',
    thermal_auto_print_kitchen: 'false',
  })

  useEffect(() => {
    fetch('/api/settings/printer')
      .then(r => r.json())
      .then(d => { if (d.settings) setPrinterSettings(d.settings) })
      .catch(() => {})
  }, [])

  const thermalOpts: ThermalPrintOptions | undefined =
    printer.isConnected && printerSettings.thermal_printer_enabled === 'true'
      ? { print: printer.print, paper: printerSettings.thermal_paper_width as '58mm' | '80mm' }
      : undefined

  const fetchStores = async () => {
    const res = await fetch('/api/stores')
    const data = await res.json()
    setStores(data.stores || [])
    if (data.stores?.length > 0 && !selectedStore) {
      setSelectedStore(data.stores[0].id)
      setStoreName(data.stores[0].name || '')
    }
    setLoading(false)
  }

  const fetchTables = async (storeId: string, page = 1) => {
    if (!storeId) return
    const res = await fetch(`/api/tables?storeId=${storeId}&page=${page}`)
    const data = await res.json()
    setTables(data.tables || [])
    if (data.pagination) setTablePagination(data.pagination)
  }

  const fetchSettings = async () => {
    try {
      const res = await fetch('/api/settings')
      const data = await res.json()
      if (data.settings?.order_protection_enabled === 'true') {
        setOrderProtectionEnabled(true)
      }
      if (data.tenantName) setRestaurantName(data.tenantName)
    } catch {}
  }

  const fetchAccessCodes = async (storeId: string) => {
    if (!storeId) return
    try {
      const res = await fetch(`/api/access-codes?storeId=${storeId}`)
      const data = await res.json()
      setAccessCodes(data.accessCodes || [])
    } catch {}
  }

  useEffect(() => {
    fetchStores()
    fetchSettings()
  }, [])

  useEffect(() => {
    if (selectedStore) {
      fetchTables(selectedStore)
      if (orderProtectionEnabled) fetchAccessCodes(selectedStore)
      const store = stores.find(s => s.id === selectedStore)
      if (store) setStoreName(store.name || '')
    }
  }, [selectedStore, orderProtectionEnabled])

  const handleAddTable = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedStore) return
    setSaving(true)
    try {
      const res = await fetch('/api/tables', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          storeId: selectedStore,
          number: parseInt(newTable.number),
          name: newTable.name || `Meja ${newTable.number}`,
          capacity: parseInt(newTable.capacity),
        }),
      })
      if (!res.ok) throw new Error((await res.json()).error)
      toast.success('Meja ditambahkan')
      setNewTable({ number: '', name: '', capacity: '4' })
      fetchTables(selectedStore)
    } catch (err: any) { toast.error(err.message) }
    finally { setSaving(false) }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Hapus meja ini?')) return
    await fetch(`/api/tables/${id}`, { method: 'DELETE' })
    toast.success('Meja dihapus')
    fetchTables(selectedStore)
  }

  const handleRegenerateQR = async () => {
    if (!selectedStore) return
    setRegeneratingQR(true)
    try {
      const res = await fetch('/api/tables', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ storeId: selectedStore }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      toast.success(data.message || 'QR code berhasil di-regenerate')
      fetchTables(selectedStore)
    } catch (err: any) { toast.error(err.message) }
    finally { setRegeneratingQR(false) }
  }

  const downloadQR = (table: any) => {
    if (!table.qrCode) return
    const link = document.createElement('a')
    link.download = `QR-Meja-${table.number}.png`
    link.href = table.qrCode
    link.click()
  }

  // Access code handlers
  const handleGenerateCode = async () => {
    setGeneratingCode(true)
    try {
      const res = await fetch('/api/access-codes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ storeId: selectedStore }),
      })
      if (!res.ok) throw new Error((await res.json()).error)
      const data = await res.json()
      toast.success(`Kode ${data.accessCode.code} berhasil dibuat`)
      printAccessCode(data.accessCode.code, restaurantName, storeName, thermalOpts)
      fetchAccessCodes(selectedStore)
    } catch (err: any) { toast.error(err.message) }
    finally { setGeneratingCode(false) }
  }

  const handleDeactivateCode = async (codeId: string) => {
    try {
      const res = await fetch(`/api/access-codes/${codeId}`, { method: 'DELETE' })
      if (!res.ok) throw new Error((await res.json()).error)
      toast.success('Kode dinonaktifkan')
      fetchAccessCodes(selectedStore)
    } catch (err: any) { toast.error(err.message) }
  }

  const handlePrintCode = (code: string) => {
    printAccessCode(code, restaurantName, storeName, thermalOpts)
  }

  const handleCopyCode = (code: string) => {
    navigator.clipboard.writeText(code)
    setCopiedCode(code)
    toast.success('Kode disalin')
    setTimeout(() => setCopiedCode(''), 2000)
  }

  const formatTimeAgo = (dateStr: string) => {
    const diff = Math.floor((Date.now() - new Date(dateStr).getTime()) / 60000)
    if (diff < 1) return 'Baru saja'
    if (diff < 60) return `${diff} mnt lalu`
    const hours = Math.floor(diff / 60)
    if (hours < 24) return `${hours} jam lalu`
    return `${Math.floor(hours / 24)} hari lalu`
  }

  if (loading) return <div className="flex items-center justify-center h-64"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div></div>

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">QR Code & Manajemen Meja</h1>
        <p className="text-gray-600 dark:text-gray-300 mt-1">Buat meja dan generate QR code untuk menu digital.</p>
      </div>

      {/* Store selector */}
      <div className="card mb-6">
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">Pilih Cabang</label>
        <select className="input-field max-w-xs dark:bg-gray-800 dark:border-gray-600 dark:text-white" value={selectedStore} onChange={(e) => setSelectedStore(e.target.value)}>
          {stores.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
        </select>
      </div>

      {/* Tab switcher */}
      <div className="flex gap-1 mb-6 bg-gray-100 dark:bg-gray-800 rounded-lg p-1 w-fit">
        <button
          onClick={() => setActiveTab('list')}
          className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-md transition-colors ${
            activeTab === 'list'
              ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
              : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
          }`}
        >
          <List className="w-4 h-4" /> Daftar Meja
        </button>
        <button
          onClick={() => setActiveTab('floorplan')}
          className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-md transition-colors ${
            activeTab === 'floorplan'
              ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
              : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
          }`}
        >
          <Map className="w-4 h-4" /> Floor Plan
        </button>
      </div>

      {activeTab === 'list' ? (
        <>
          {/* Add table form */}
          <div className="card mb-6">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-3">Tambah Meja Baru</h2>
            <form onSubmit={handleAddTable} className="flex flex-wrap gap-3 items-end">
              <div>
                <label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">No. Meja</label>
                <input type="number" className="input-field w-24" value={newTable.number} onChange={(e) => setNewTable({ ...newTable, number: e.target.value })} required min="1" />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">Nama (opsional)</label>
                <input type="text" className="input-field w-40" placeholder="Meja VIP" value={newTable.name} onChange={(e) => setNewTable({ ...newTable, name: e.target.value })} />
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">Kapasitas</label>
                <input type="number" className="input-field w-20" value={newTable.capacity} onChange={(e) => setNewTable({ ...newTable, capacity: e.target.value })} min="1" />
              </div>
              <button type="submit" disabled={saving} className="btn-primary text-sm">
                {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <><Plus className="w-4 h-4 inline mr-1" /> Tambah</>}
              </button>
              {tables.length > 0 && (
                <button type="button" onClick={handleRegenerateQR} disabled={regeneratingQR} className="btn-secondary text-sm flex items-center gap-1.5">
                  {regeneratingQR ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
                  {regeneratingQR ? 'Regenerating...' : 'Regenerate QR'}
                </button>
              )}
            </form>
          </div>

          {/* Access Code Section */}
          {orderProtectionEnabled && selectedStore && (
            <div className="card mb-6">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-primary-100 dark:bg-primary-900/30 rounded-lg flex items-center justify-center">
                    <Key className="w-5 h-5 text-primary-600" />
                  </div>
                  <div>
                    <h2 className="text-lg font-semibold text-gray-900 dark:text-white">Kode Akses Customer</h2>
                    <p className="text-sm text-gray-500 dark:text-gray-400">Generate kode unik untuk customer yang datang.</p>
                  </div>
                </div>
                <button
                  onClick={handleGenerateCode}
                  disabled={generatingCode}
                  className="btn-primary text-sm flex items-center gap-2"
                >
                  {generatingCode ? <Loader2 className="w-4 h-4 animate-spin" /> : <><Key className="w-4 h-4" /> Generate &amp; Print Kode</>}
                </button>
              </div>

              {accessCodes.length > 0 && (
                <div>
                  <p className="text-sm font-medium text-gray-700 dark:text-gray-200 mb-2">Kode Aktif ({accessCodes.length}):</p>
                  <div className="space-y-2">
                    {accessCodes.map((ac: any) => (
                      <div key={ac.id} className="flex items-center justify-between bg-gray-50 dark:bg-gray-700/50 rounded-lg px-4 py-2.5">
                        <div className="flex items-center gap-4">
                          <span className="font-mono font-bold text-lg text-gray-900 dark:text-white tracking-widest">{ac.code}</span>
                          <span className="text-xs text-gray-500 dark:text-gray-400">{formatTimeAgo(ac.createdAt)}</span>
                          <span className="text-xs text-gray-500 dark:text-gray-400">{ac._count?.orders || 0} order</span>
                        </div>
                        <div className="flex items-center gap-1.5">
                          <button onClick={() => handleCopyCode(ac.code)} className="p-1.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-500 dark:text-gray-400" title="Salin kode">
                            {copiedCode === ac.code ? <Check className="w-4 h-4 text-green-600" /> : <Copy className="w-4 h-4" />}
                          </button>
                          <button onClick={() => handlePrintCode(ac.code)} className="p-1.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-500 dark:text-gray-400" title="Print ulang">
                            <Printer className="w-4 h-4" />
                          </button>
                          <button onClick={() => handleDeactivateCode(ac.id)} className="p-1.5 rounded hover:bg-red-100 dark:hover:bg-red-900/30 text-red-500" title="Nonaktifkan">
                            <X className="w-4 h-4" />
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {accessCodes.length === 0 && (
                <p className="text-sm text-gray-500 dark:text-gray-400 text-center py-4">Belum ada kode aktif. Klik &quot;Generate &amp; Print Kode&quot; saat customer datang.</p>
              )}
            </div>
          )}

          {/* Tables grid */}
          <div className="grid sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            {tables.map(table => {
              const store = stores.find(s => s.id === selectedStore)
              const menuCode = store?.menuCode
              const appUrl = typeof window !== 'undefined' ? window.location.origin : ''
              const menuUrl = menuCode ? `${appUrl}/menu/${menuCode}/${table.number}` : ''

              return (
                <div key={table.id} className="card text-center">
                  <div className="mb-3">
                    {table.qrCode ? (
                      <img src={table.qrCode} alt={`QR Meja ${table.number}`} className="w-40 h-40 mx-auto" />
                    ) : (
                      <div className="w-40 h-40 mx-auto bg-gray-100 dark:bg-gray-700/50 rounded-lg flex items-center justify-center">
                        <QrCode className="w-12 h-12 text-gray-400 dark:text-gray-500" />
                      </div>
                    )}
                  </div>
                  <h3 className="font-semibold text-gray-900 dark:text-white">{table.name || `Meja ${table.number}`}</h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400">No. {table.number} &bull; {table.capacity} orang</p>

                  {/* Menu URL */}
                  {menuUrl && (
                    <div className="mt-2 flex items-center justify-center gap-1.5">
                      <p className="text-xs text-gray-400 dark:text-gray-500 font-mono truncate max-w-[180px]" title={menuUrl}>
                        /menu/{menuCode}/{table.number}
                      </p>
                      <a
                        href={menuUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-primary-600 dark:text-gray-500 dark:hover:text-primary-400 transition-colors"
                        title="Buka di tab baru"
                      >
                        <ExternalLink className="w-3.5 h-3.5" />
                      </a>
                    </div>
                  )}

                  <div className="flex gap-2 mt-3 justify-center">
                    <button onClick={() => downloadQR(table)} className="btn-secondary text-xs">
                      <Download className="w-3.5 h-3.5 inline mr-1" /> Download
                    </button>
                    <button onClick={() => handleDelete(table.id)} className="btn-ghost text-xs text-red-500 hover:bg-red-50 dark:hover:bg-red-900/30">
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>
              )
            })}
          </div>
          {tables.length === 0 && <p className="text-center text-gray-500 dark:text-gray-400 py-12">Belum ada meja di cabang ini.</p>}
          <Pagination pagination={tablePagination} onPageChange={(page) => fetchTables(selectedStore, page)} itemLabel="meja" />
        </>
      ) : (
        <FloorPlanEditor
          tables={tables}
          storeId={selectedStore}
          onRefresh={() => fetchTables(selectedStore)}
        />
      )}
    </div>
  )
}
