"use client"

import { useState, useEffect, useCallback } from "react"
import { RoleProtected } from "@/components/role-protected"
import { Card } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Loader2, RefreshCw, Award, Receipt, HandCoins, Users } from "lucide-react"
import { toast } from "@/hooks/use-toast"
import { useSede } from "@/lib/sede-context"
import { getLocalDateString } from "@/lib/utils"

interface MeseroFila {
  staffId: string | null
  nombre: string
  username: string | null
  cargo: string | null
  cuentas: number
  ventasUSD: number
  propinasUSD: number
  promedioUSD: number
  mesasAbiertasAhora: number
}

interface Reporte {
  desde: string
  hasta: string
  meseros: MeseroFila[]
  totales: { cuentas: number; ventasUSD: number; propinasUSD: number }
}

/**
 * Quincenas en la fecha del dispositivo (el personal está en Venezuela).
 * offset 0 = quincena en curso, 1 = la anterior, etc.
 */
function rangoQuincena(offset: number): { desde: string; hasta: string; etiqueta: string } {
  const hoy = new Date(getLocalDateString() + "T12:00:00")
  let year = hoy.getFullYear()
  let month = hoy.getMonth() // 0-index
  // Índice de quincena absoluto: 2 por mes
  let q = month * 2 + (hoy.getDate() <= 15 ? 0 : 1) - offset
  year += Math.floor(q / 24)
  q = ((q % 24) + 24) % 24
  month = Math.floor(q / 2)
  const primera = q % 2 === 0
  const mm = String(month + 1).padStart(2, "0")
  const ultimoDia = new Date(year, month + 1, 0).getDate()
  const desde = primera ? `${year}-${mm}-01` : `${year}-${mm}-16`
  const hasta = primera ? `${year}-${mm}-15` : `${year}-${mm}-${String(ultimoDia).padStart(2, "0")}`
  const nombreMes = new Date(year, month, 1).toLocaleDateString("es-VE", { month: "long" })
  const etiqueta = `${primera ? "1ra" : "2da"} quincena de ${nombreMes}`
  return { desde, hasta, etiqueta }
}

function money(n: number): string {
  return `$${n.toFixed(2)}`
}

export default function MeserosPage() {
  const { sedeId } = useSede()
  const [reporte, setReporte] = useState<Reporte | null>(null)
  const [loading, setLoading] = useState(true)
  const [desde, setDesde] = useState(() => rangoQuincena(0).desde)
  const [hasta, setHasta] = useState(() => rangoQuincena(0).hasta)
  const [etiqueta, setEtiqueta] = useState(() => rangoQuincena(0).etiqueta)

  const cargar = useCallback(async (d: string, h: string) => {
    if (!sedeId) return
    setLoading(true)
    try {
      const res = await fetch(
        `/api/reports/waiter-sales?locationId=${sedeId}&startDate=${d}&endDate=${h}`
      )
      if (!res.ok) throw new Error((await res.json()).error || "Error cargando el reporte")
      setReporte(await res.json())
    } catch (e) {
      toast({
        title: "Error",
        description: e instanceof Error ? e.message : "No se pudo cargar el reporte",
        variant: "destructive",
      })
    } finally {
      setLoading(false)
    }
  }, [sedeId])

  useEffect(() => {
    cargar(desde, hasta)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sedeId])

  const irAQuincena = (offset: number) => {
    const r = rangoQuincena(offset)
    setDesde(r.desde)
    setHasta(r.hasta)
    setEtiqueta(r.etiqueta)
    cargar(r.desde, r.hasta)
  }

  const aplicarFechas = () => {
    setEtiqueta("Rango personalizado")
    cargar(desde, hasta)
  }

  return (
    <RoleProtected allowedRoles={["ADMIN", "MANAGER"]}>
      <div className="p-4 md:p-6 space-y-4">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <h1 className="text-2xl font-bold text-verde-bosque flex items-center gap-2">
              <Award className="h-6 w-6" />
              Ventas por mesero
            </h1>
            <p className="text-sm text-muted-foreground mt-1">
              La venta es del mesero cuyo PIN abrió la cuenta, sin importar quién la cobre.
              Base para las comisiones por quincena.
            </p>
          </div>
          <Button variant="outline" size="sm" onClick={() => cargar(desde, hasta)} disabled={loading}>
            {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
            <span className="ml-2">Actualizar</span>
          </Button>
        </div>

        {/* Selector de quincena */}
        <Card className="p-4">
          <div className="flex flex-wrap items-end gap-3">
            <Button size="sm" variant="default" onClick={() => irAQuincena(0)}>
              Quincena actual
            </Button>
            <Button size="sm" variant="outline" onClick={() => irAQuincena(1)}>
              Quincena anterior
            </Button>
            <div className="flex items-end gap-2">
              <div>
                <Label htmlFor="desde" className="text-xs">Desde</Label>
                <Input id="desde" type="date" value={desde} onChange={(e) => setDesde(e.target.value)} className="h-9" />
              </div>
              <div>
                <Label htmlFor="hasta" className="text-xs">Hasta</Label>
                <Input id="hasta" type="date" value={hasta} onChange={(e) => setHasta(e.target.value)} className="h-9" />
              </div>
              <Button size="sm" variant="secondary" onClick={aplicarFechas}>Aplicar</Button>
            </div>
            <div className="ml-auto text-sm text-muted-foreground">
              {etiqueta}{reporte && <> · {reporte.desde} → {reporte.hasta}</>}
            </div>
          </div>
        </Card>

        {/* Totales */}
        {reporte && (
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
            <Card className="p-4 flex items-center gap-3">
              <Receipt className="h-8 w-8 text-verde-bosque" />
              <div>
                <p className="text-xs text-muted-foreground">Ventas de mesa</p>
                <p className="text-xl font-bold">{money(reporte.totales.ventasUSD)}</p>
              </div>
            </Card>
            <Card className="p-4 flex items-center gap-3">
              <HandCoins className="h-8 w-8 text-naranja-vip" />
              <div>
                <p className="text-xs text-muted-foreground">Propinas</p>
                <p className="text-xl font-bold">{money(reporte.totales.propinasUSD)}</p>
              </div>
            </Card>
            <Card className="p-4 flex items-center gap-3">
              <Users className="h-8 w-8 text-verde-bosque" />
              <div>
                <p className="text-xs text-muted-foreground">Cuentas cobradas</p>
                <p className="text-xl font-bold">{reporte.totales.cuentas}</p>
              </div>
            </Card>
          </div>
        )}

        {/* Tabla por mesero */}
        <Card className="overflow-x-auto">
          {loading && !reporte ? (
            <div className="p-10 text-center text-muted-foreground">
              <Loader2 className="h-6 w-6 animate-spin mx-auto mb-2" />
              Cargando…
            </div>
          ) : !reporte || reporte.meseros.length === 0 ? (
            <div className="p-10 text-center text-muted-foreground">
              Sin ventas de mesa en este rango.
            </div>
          ) : (
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-muted/50 text-left">
                  <th className="p-3 font-semibold">Mesero</th>
                  <th className="p-3 font-semibold text-center">Mesas ahora</th>
                  <th className="p-3 font-semibold text-right">Cuentas</th>
                  <th className="p-3 font-semibold text-right">Ventas</th>
                  <th className="p-3 font-semibold text-right">Propinas</th>
                  <th className="p-3 font-semibold text-right">Promedio/cuenta</th>
                </tr>
              </thead>
              <tbody>
                {reporte.meseros.map((m) => (
                  <tr key={m.staffId ?? "sin-mesero"} className="border-b last:border-0 hover:bg-muted/30">
                    <td className="p-3">
                      <div className="font-medium">{m.nombre}</div>
                      <div className="flex items-center gap-2 mt-0.5">
                        {m.cargo && <Badge variant="outline" className="text-xs">{m.cargo}</Badge>}
                        {m.username && <span className="text-xs text-muted-foreground">{m.username}</span>}
                        {!m.staffId && (
                          <span className="text-xs text-muted-foreground">
                            cuentas abiertas antes del PIN de apertura
                          </span>
                        )}
                      </div>
                    </td>
                    <td className="p-3 text-center">
                      {m.mesasAbiertasAhora > 0 ? (
                        <Badge className="bg-verde-bosque text-white">{m.mesasAbiertasAhora}</Badge>
                      ) : (
                        <span className="text-muted-foreground">—</span>
                      )}
                    </td>
                    <td className="p-3 text-right tabular-nums">{m.cuentas}</td>
                    <td className="p-3 text-right tabular-nums font-semibold">{money(m.ventasUSD)}</td>
                    <td className="p-3 text-right tabular-nums">{money(m.propinasUSD)}</td>
                    <td className="p-3 text-right tabular-nums text-muted-foreground">{money(m.promedioUSD)}</td>
                  </tr>
                ))}
              </tbody>
              <tfoot>
                <tr className="bg-muted/50 font-semibold">
                  <td className="p-3">Total</td>
                  <td className="p-3" />
                  <td className="p-3 text-right tabular-nums">{reporte.totales.cuentas}</td>
                  <td className="p-3 text-right tabular-nums">{money(reporte.totales.ventasUSD)}</td>
                  <td className="p-3 text-right tabular-nums">{money(reporte.totales.propinasUSD)}</td>
                  <td className="p-3" />
                </tr>
              </tfoot>
            </table>
          )}
        </Card>

        <p className="text-xs text-muted-foreground">
          Incluye SOLO ventas de cuentas de mesa (cobros de caja, pagos online del comensal y pagos
          parciales). Delivery, pickup y POS no comisionan aquí. Las cuentas abiertas antes del
          2026-08-24 no tienen mesero registrado.
        </p>
      </div>
    </RoleProtected>
  )
}
