import { useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'
import StatusBadge from '../components/StatusBadge'
import ConfirmModal from '../components/ConfirmModal'

function PrintOrderModal({ onClose, onPrint, printers }) {
  const [printerId, setPrinterId] = useState(printers[0]?.id ?? '')
  function submit() {
    if (!printerId) { toast.error('Επιλέξτε εκτυπωτή'); return }
    onPrint(Number(printerId))
    onClose()
  }
  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 space-y-5">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-bold text-gray-800">Εκτύπωση παραγγελίας</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl leading-none">✕</button>
        </div>
        <div>
          <label className="label">Εκτυπωτής</label>
          <select className="input w-full" value={printerId} onChange={e => setPrinterId(e.target.value)}>
            <option value="">— Επιλέξτε —</option>
            {printers.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
        </div>
        <div className="flex gap-3">
          <button onClick={onClose} className="btn btn-secondary flex-1">Ακύρωση</button>
          <button onClick={submit} className="btn btn-primary flex-1">Εκτύπωση</button>
        </div>
      </div>
    </div>
  )
}

function itemTotal(item) {
  return (item.unit_price * item.quantity).toFixed(2)
}

function formatDate(dt) {
  if (!dt) return '—'
  return new Date(dt).toLocaleString('el-GR', { dateStyle: 'short', timeStyle: 'short' })
}

const EVENT_LABELS = {
  ORDER_OPENED: 'Άνοιγμα',
  ITEMS_ADDED: 'Προσθήκη',
  PAYMENT: 'Πληρωμή',
  PAYMENT_OFFLINE: 'Πληρωμή (Offline)',
  ORDER_CLOSED: 'Κλείσιμο',
  ORDER_CANCELLED: 'Ακύρωση',
  ITEM_CANCELLED: 'Ακύρωση αντ.',
}

function AuditTab({ order, waiterMap }) {
  if (!order.audit_logs || order.audit_logs.length === 0) {
    return <p className="py-8 text-center text-gray-400 text-sm">Δεν υπάρχουν εγγραφές.</p>
  }
  return (
    <div className="divide-y divide-gray-100">
      {order.audit_logs.map(log => {
        const isDuplicate = log.is_duplicate === 1 || log.is_duplicate === true
        const isPayment = log.event_type === 'PAYMENT' || log.event_type === 'PAYMENT_OFFLINE'
        const badgeClass = isDuplicate
          ? 'bg-red-100 text-red-700'
          : isPayment ? 'bg-green-100 text-green-700'
          : log.event_type.includes('CANCEL') ? 'bg-red-100 text-red-600'
          : log.event_type === 'ORDER_CLOSED' ? 'bg-gray-100 text-gray-600'
          : 'bg-blue-100 text-blue-700'
        // Show offline_at (real payment time) when available, else server created_at
        const displayTime = log.offline_at ? formatDate(log.offline_at) : formatDate(log.created_at)
        return (
          <div key={log.id} className={`flex items-start gap-3 px-4 py-3 ${isDuplicate ? 'bg-red-50' : ''}`}>
            <div className="shrink-0 mt-0.5">
              <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${badgeClass}`}>
                {EVENT_LABELS[log.event_type] ?? log.event_type}
              </span>
              {isDuplicate && (
                <span className="block text-xs text-red-500 font-semibold mt-0.5">ΔΙΠΛΗ</span>
              )}
            </div>
            <div className="flex-1 min-w-0 text-sm text-gray-700">
              <span>{log.waiter_name ?? waiterMap[log.waiter_id] ?? `#${log.waiter_id}`}</span>
              {log.amount != null && (
                <span className={`ml-2 font-semibold ${isDuplicate ? 'text-red-600' : 'text-green-700'}`}>
                  €{log.amount.toFixed(2)}
                </span>
              )}
              {log.payment_method && (
                <span className="ml-1 text-gray-400 text-xs">({log.payment_method})</span>
              )}
            </div>
            <div className="text-right shrink-0">
              <span className="text-xs text-gray-400">{displayTime}</span>
              {log.offline_at && (
                <span className="block text-xs text-orange-400">offline</span>
              )}
            </div>
          </div>
        )
      })}
    </div>
  )
}

export default function OrderDetailPage({ orderId: propOrderId, readOnly = false }) {
  const { orderId: paramOrderId } = useParams()
  const orderId = propOrderId ?? paramOrderId
  const navigate = useNavigate()
  const qc = useQueryClient()

  const [tab, setTab] = useState('overview')
  const [confirmAction, setConfirmAction] = useState(null) // { type, payload }
  const [showPrintModal, setShowPrintModal] = useState(false)

  const { data: order, isLoading } = useQuery({
    queryKey: ['order', orderId],
    queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data),
    enabled: !!orderId,
  })

  const { data: waiters = [] } = useQuery({
    queryKey: ['waiters'],
    queryFn: () => client.get('/api/waiters/').then(r => r.data),
    staleTime: 60_000,
  })

  const { data: printers = [] } = useQuery({
    queryKey: ['printers'],
    queryFn: () => client.get('/api/system/printers').then(r => r.data),
    staleTime: 60_000,
  })

  const printOrder = useMutation({
    mutationFn: (printerId) => client.post(`/api/orders/${orderId}/print`, { printer_id: printerId }),
    onSuccess: () => toast.success('Αποστολή στον εκτυπωτή…'),
    onError: () => toast.error('Σφάλμα εκτύπωσης'),
  })

  const waiterMap = Object.fromEntries(waiters.map(w => [w.id, w.nickname || w.full_name || w.username]))
  const assignedIds = new Set((order?.waiters ?? []).map(w => w.waiter_id))

  const invalidate = () => {
    qc.invalidateQueries({ queryKey: ['order', orderId] })
    qc.invalidateQueries({ queryKey: ['orders-active'] })
  }

  const cancelItem = useMutation({
    mutationFn: (itemId) => client.delete(`/api/orders/${orderId}/items/${itemId}`),
    onSuccess: () => { toast.success('Αντικείμενο ακυρώθηκε'); invalidate() },
    onError: () => toast.error('Σφάλμα ακύρωσης αντικειμένου'),
  })

  const cancelOrder = useMutation({
    mutationFn: () => client.delete(`/api/orders/${orderId}`),
    onSuccess: () => { toast.success('Παραγγελία ακυρώθηκε'); navigate('/tables') },
    onError: () => toast.error('Σφάλμα ακύρωσης παραγγελίας'),
  })

  const closeOrder = useMutation({
    mutationFn: () => client.post(`/api/orders/${orderId}/close`),
    onSuccess: () => { toast.success('Παραγγελία έκλεισε'); navigate('/tables') },
    onError: () => toast.error('Σφάλμα κλεισίματος'),
  })

  const assignWaiter = useMutation({
    mutationFn: (waiter_id) => client.put(`/api/orders/${orderId}/assign-waiter`, { waiter_id }),
    onSuccess: () => { toast.success('Σερβιτόρος προστέθηκε'); invalidate() },
    onError: () => toast.error('Σφάλμα'),
  })

  const removeWaiter = useMutation({
    mutationFn: (wid) => client.delete(`/api/orders/${orderId}/waiters/${wid}`),
    onSuccess: () => { toast.success('Σερβιτόρος αφαιρέθηκε'); invalidate() },
    onError: () => toast.error('Σφάλμα'),
  })

  const payItems = useMutation({
    mutationFn: (item_ids) => client.post(`/api/orders/${orderId}/pay`, { item_ids }),
    onSuccess: () => { toast.success('Πληρώθηκε'); invalidate() },
    onError: () => toast.error('Σφάλμα πληρωμής'),
  })

  function handleConfirm() {
    if (!confirmAction) return
    const { type, payload } = confirmAction
    if (type === 'cancelItem') cancelItem.mutate(payload)
    if (type === 'cancelOrder') cancelOrder.mutate()
    if (type === 'closeOrder') closeOrder.mutate()
    setConfirmAction(null)
  }

  if (isLoading) return <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
  if (!order) return <div className="text-center py-16 text-gray-400">Παραγγελία δεν βρέθηκε.</div>

  const activeItems = order.items.filter(i => i.status === 'active')
  const total = order.items
    .filter(i => i.status !== 'cancelled')
    .reduce((s, i) => s + i.unit_price * i.quantity, 0)

  const isOpen = ['open', 'partially_paid'].includes(order.status)

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      {!propOrderId && (
        <button onClick={() => navigate(-1)} className="btn btn-ghost text-sm">← Πίσω</button>
      )}

      {/* Header */}
      <div className="card p-5 flex flex-wrap gap-4 items-start justify-between">
        <div>
          <h1 className="text-xl font-bold text-gray-800">Παραγγελία #{order.id}</h1>
          <p className="text-sm text-gray-500 mt-1">
            Τραπέζι {order.table_id} · Ανοίχτηκε {formatDate(order.opened_at)}
            {order.closed_at && ` · Έκλεισε ${formatDate(order.closed_at)}`}
          </p>
        </div>
        <div className="flex items-center gap-3">
          <StatusBadge status={order.status} />
          <span className="text-lg font-bold text-gray-800">€{total.toFixed(2)}</span>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 border-b border-gray-200">
        {[['overview', 'Επισκόπηση'], ['audit', 'Ιστορικό Συναλλαγών']].map(([key, label]) => (
          <button
            key={key}
            onClick={() => setTab(key)}
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${tab === key ? 'border-primary-600 text-primary-700' : 'border-transparent text-gray-500 hover:text-gray-700'}`}
          >
            {label}
          </button>
        ))}
      </div>

      {tab === 'overview' && <>
        {/* Waiters */}
        <div className="card p-4">
          <h2 className="text-sm font-semibold text-gray-700 mb-3">Προσωπικό</h2>
          <div className="flex flex-wrap gap-2">
            {order.waiters.map(w => (
              <div key={w.waiter_id} className="flex items-center gap-2 bg-gray-100 rounded-full px-3 py-1">
                <span className="text-sm">{waiterMap[w.waiter_id] || `#${w.waiter_id}`}</span>
                {isOpen && !readOnly && (
                  <button
                    onClick={() => removeWaiter.mutate(w.waiter_id)}
                    className="text-gray-400 hover:text-red-500 text-xs leading-none"
                  >
                    ✕
                  </button>
                )}
              </div>
            ))}
            {isOpen && !readOnly && (
              <select
                className="text-sm border border-gray-300 rounded-full pl-3 pr-8 py-1 focus:outline-none focus:ring-1 focus:ring-primary-600"
                defaultValue=""
                onChange={e => { if (e.target.value) assignWaiter.mutate(Number(e.target.value)) }}
              >
                <option value="">+ Πρόσθεσε</option>
                {waiters.filter(w => !assignedIds.has(w.id)).map(w => (
                  <option key={w.id} value={w.id}>{w.nickname || w.full_name || w.username}</option>
                ))}
              </select>
            )}
          </div>
        </div>

        {/* Items */}
        <div className="card divide-y divide-gray-100">
          <div className="px-4 py-3">
            <h2 className="text-sm font-semibold text-gray-700">Αντικείμενα</h2>
          </div>
          {order.items.length === 0 && (
            <p className="px-4 py-6 text-center text-gray-400 text-sm">Κανένα αντικείμενο.</p>
          )}
          {order.items.map(item => (
            <div key={item.id} className={`flex items-center gap-3 px-4 py-3 ${item.status === 'cancelled' ? 'opacity-40 line-through' : ''}`}>
              <div className="flex-1 min-w-0">
                <p className="font-medium text-gray-800 text-sm">{item.product?.name ?? `#${item.product_id}`}</p>
                {item.notes && <p className="text-xs text-gray-400">{item.notes}</p>}
                <p className="text-xs text-gray-500">x{item.quantity} · €{item.unit_price.toFixed(2)}/τμχ</p>
                {item.paid_by && (
                  <p className="text-xs text-green-600 mt-0.5">
                    Πληρώθηκε: {waiterMap[item.paid_by] ?? `#${item.paid_by}`}
                    {item.paid_at ? ` · ${formatDate(item.paid_at)}` : ''}
                  </p>
                )}
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <StatusBadge status={item.status} />
                <span className="text-sm font-semibold text-gray-700 w-14 text-right">€{itemTotal(item)}</span>
                {isOpen && !readOnly && item.status === 'active' && (
                  <>
                    <button
                      onClick={() => payItems.mutate([item.id])}
                      className="btn btn-secondary text-xs px-2 py-1 min-h-0 h-8"
                    >
                      Πληρωμή
                    </button>
                    <button
                      onClick={() => setConfirmAction({ type: 'cancelItem', payload: item.id })}
                      className="btn btn-danger text-xs px-2 py-1 min-h-0 h-8"
                    >
                      Ακύρωση
                    </button>
                  </>
                )}
              </div>
            </div>
          ))}
        </div>

        {/* Actions */}
        <div className="flex flex-wrap gap-3">
          {isOpen && !readOnly && activeItems.length > 0 && (
            <button
              onClick={() => payItems.mutate(activeItems.map(i => i.id))}
              className="btn btn-primary"
            >
              Πληρωμή όλων
            </button>
          )}
          {isOpen && !readOnly && (
            <>
              <button
                onClick={() => setConfirmAction({ type: 'closeOrder' })}
                className="btn btn-secondary"
              >
                Κλείσιμο παραγγελίας
              </button>
              <button
                onClick={() => setConfirmAction({ type: 'cancelOrder' })}
                className="btn btn-danger"
              >
                Ακύρωση παραγγελίας
              </button>
            </>
          )}
          <button
            onClick={() => setShowPrintModal(true)}
            className="btn btn-secondary"
          >
            🖨 Εκτύπωση
          </button>
        </div>
      </>}

      {tab === 'audit' && (
        <div className="card divide-y divide-gray-100">
          <AuditTab order={order} waiterMap={waiterMap} />
        </div>
      )}

      {confirmAction && (
        <ConfirmModal
          title={
            confirmAction.type === 'cancelItem' ? 'Ακύρωση αντικειμένου;' :
            confirmAction.type === 'cancelOrder' ? 'Ακύρωση παραγγελίας;' :
            'Κλείσιμο παραγγελίας;'
          }
          message={
            confirmAction.type === 'cancelOrder'
              ? 'Η παραγγελία θα ακυρωθεί οριστικά.'
              : undefined
          }
          confirmLabel={confirmAction.type === 'closeOrder' ? 'Κλείσιμο' : 'Ακύρωση'}
          confirmClass={confirmAction.type === 'closeOrder' ? 'btn-primary' : 'btn-danger'}
          onConfirm={handleConfirm}
          onCancel={() => setConfirmAction(null)}
        />
      )}

      {showPrintModal && printers.length > 0 && (
        <PrintOrderModal
          printers={printers}
          onClose={() => setShowPrintModal(false)}
          onPrint={(printerId) => printOrder.mutate(printerId)}
        />
      )}
      {showPrintModal && printers.length === 0 && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
          <div className="bg-white rounded-2xl p-6 max-w-sm w-full mx-4 space-y-4">
            <p className="text-gray-700">Δεν βρέθηκαν ενεργοί εκτυπωτές.</p>
            <button onClick={() => setShowPrintModal(false)} className="btn btn-secondary w-full">Κλείσιμο</button>
          </div>
        </div>
      )}
    </div>
  )
}
