"use client"

import { useState, useEffect, useCallback, useMemo } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Loader2, RefreshCw, Scissors, Gift, Percent, XCircle, AlertTriangle, Download } from "lucide-react"
import { toast } from "@/hooks/use-toast"
import { useSede } from "@/lib/sede-context"
import { getLocalDateString } from "@/lib/utils"
import { cn } from "@/lib/utils"

type TipoFila = "VOID" | "COMP" | "DISCOUNT" | "CANCEL_MESA" | "CANCEL_PEDIDO" | "PAGO_ANULADO"

interface Fila {
  fecha: string
  tipo: TipoFila
  etiqueta: string
  mesa: string | null
  que: string
  motivo: string
  montoUSD: number
  mesero: string | null
  hizo: string
  autorizo: string | null
  preparado?: boolean
}

interface Agregado {
  clave: string
  nombre: string
  cantidad: number
  montoUSD: number
}

interface Reporte {
  desde: string
  hasta: string
  totales: {
    ventasUSD: number
    anulacionesUSD: number
    anulaciones: number
    anulacionesPreparadas: number
    cortesiasUSD: number
    cortesias: number
    descuentosUSD: number
    descuentos: number
    ajustesUSD: number
    porcentajeSobreVentas: number
    alerta: boolean
    cuentasCanceladas: number
    cuentasCanceladasUSD: number
    pedidosCancelados: number
    pedidosCanceladosUSD: number
    pagosAnulados: number
    pagosAnuladosUSD: number
  }
  porMesero: Agregado[]
  porAutoriza: Agregado[]
  porMotivo: Agregado[]
  detalle: Fila[]
}

/** Quincenas en la fecha del dispositivo; offset 0 = en curso, 1 = anterior. */
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()
  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" })
  return { desde, hasta, etiqueta: `${primera ? "1ra" : "2da"} quincena de ${nombreMes}` }
}

const money = (n: number) => `$${n.toFixed(2)}`

const COLOR: Record<TipoFila, string> = {
  VOID: "bg-red-100 text-red-800",
  COMP: "bg-emerald-100 text-emerald-800",
  DISCOUNT: "bg-amber-100 text-amber-900",
  CANCEL_MESA: "bg-red-600 text-white",
  CANCEL_PEDIDO: "bg-red-600 text-white",
  PAGO_ANULADO: "bg-slate-700 text-white",
}

/**
 * Anulaciones y cortesías (v1.83.0): lo que se le quitó a la caja y por qué,
 * por mesero, por quien autorizó y por motivo. Gerencia lo revisa a diario;
 * la referencia es que anulaciones + cortesías no pasen del 2 % de las ventas.
 */
export default function AnulacionesPage() {
  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 [filtroTipo, setFiltroTipo] = useState<string>("all")

  const cargar = useCallback(
    async (d: string, h: string) => {
      if (!sedeId) return
      setLoading(true)
      try {
        const res = await fetch(`/api/reports/adjustments?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 hoy = () => {
    const d = getLocalDateString()
    setDesde(d)
    setHasta(d)
    setEtiqueta("Hoy")
    cargar(d, d)
  }

  const detalle = useMemo(
    () => (reporte?.detalle ?? []).filter((f) => filtroTipo === "all" || f.tipo === filtroTipo),
    [reporte, filtroTipo]
  )

  const exportarCSV = () => {
    if (!reporte) return
    const filas = [
      ["Fecha", "Tipo", "Mesa", "Qué", "Motivo", "Monto USD", "Mesero", "Lo hizo", "Autorizó", "Preparado"].join(","),
      ...detalle.map((f) =>
        [
          new Date(f.fecha).toLocaleString("es-VE"),
          f.etiqueta,
          f.mesa ?? "",
          `"${f.que.replace(/"/g, '""')}"`,
          `"${f.motivo.replace(/"/g, '""')}"`,
          f.montoUSD.toFixed(2),
          f.mesero ?? "",
          f.hizo,
          f.autorizo ?? "",
          f.preparado === undefined ? "" : f.preparado ? "sí" : "no",
        ].join(",")
      ),
    ]
    const blob = new Blob(["﻿" + filas.join("\n")], { type: "text/csv;charset=utf-8" })
    const url = URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = `anulaciones_${reporte.desde}_${reporte.hasta}.csv`
    a.click()
    URL.revokeObjectURL(url)
  }

  const t = reporte?.totales

  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">
              <Scissors className="h-6 w-6" />
              Anulaciones y cortesías
            </h1>
            <p className="text-sm text-muted-foreground mt-1">
              Todo lo que se le quitó a la cuenta o a la caja, con motivo, quién lo hizo y quién lo autorizó. Revísalo a diario.
            </p>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={exportarCSV} disabled={!reporte || detalle.length === 0}>
              <Download className="h-4 w-4 mr-2" />
              CSV
            </Button>
            <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>
        </div>

        <Card className="p-4">
          <div className="flex flex-wrap items-end gap-3">
            <Button size="sm" variant="default" onClick={hoy}>Hoy</Button>
            <Button size="sm" variant="outline" 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={() => { setEtiqueta("Rango personalizado"); cargar(desde, hasta) }}>
                Aplicar
              </Button>
            </div>
            <div className="ml-auto text-sm text-muted-foreground">
              {etiqueta}{reporte && <> · {reporte.desde} → {reporte.hasta}</>}
            </div>
          </div>
        </Card>

        {t && (
          <>
            <div className={cn("rounded-lg border p-4 flex flex-wrap items-center gap-4", t.alerta ? "border-red-300 bg-red-50" : "border-emerald-200 bg-emerald-50")}>
              {t.alerta ? <AlertTriangle className="h-8 w-8 text-red-600" /> : <Scissors className="h-8 w-8 text-emerald-700" />}
              <div>
                <p className="text-xs text-muted-foreground">Anulaciones + cortesías + descuentos sobre las ventas del rango</p>
                <p className={cn("text-2xl font-bold", t.alerta ? "text-red-700" : "text-emerald-800")}>
                  {t.porcentajeSobreVentas.toFixed(2)} %
                  <span className="text-sm font-normal text-muted-foreground ml-2">
                    {money(t.ajustesUSD)} de {money(t.ventasUSD)} vendidos
                  </span>
                </p>
                <p className="text-xs text-muted-foreground">Referencia del sector: por debajo del 2 %. {t.alerta ? "Está por encima: revisa el detalle." : "Dentro de lo normal."}</p>
              </div>
            </div>

            <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
              <Card className="p-4 flex items-center gap-3">
                <Scissors className="h-7 w-7 text-red-600" />
                <div>
                  <p className="text-xs text-muted-foreground">Anulaciones</p>
                  <p className="text-xl font-bold">{money(t.anulacionesUSD)}</p>
                  <p className="text-xs text-muted-foreground">{t.anulaciones} · {t.anulacionesPreparadas} ya preparadas (merma)</p>
                </div>
              </Card>
              <Card className="p-4 flex items-center gap-3">
                <Gift className="h-7 w-7 text-emerald-700" />
                <div>
                  <p className="text-xs text-muted-foreground">Cortesías</p>
                  <p className="text-xl font-bold">{money(t.cortesiasUSD)}</p>
                  <p className="text-xs text-muted-foreground">{t.cortesias}</p>
                </div>
              </Card>
              <Card className="p-4 flex items-center gap-3">
                <Percent className="h-7 w-7 text-amber-700" />
                <div>
                  <p className="text-xs text-muted-foreground">Descuentos</p>
                  <p className="text-xl font-bold">{money(t.descuentosUSD)}</p>
                  <p className="text-xs text-muted-foreground">{t.descuentos}</p>
                </div>
              </Card>
              <Card className="p-4 flex items-center gap-3">
                <XCircle className="h-7 w-7 text-red-700" />
                <div>
                  <p className="text-xs text-muted-foreground">Cancelaciones y pagos anulados</p>
                  <p className="text-xl font-bold">{money(t.cuentasCanceladasUSD + t.pedidosCanceladosUSD)}</p>
                  <p className="text-xs text-muted-foreground">
                    {t.cuentasCanceladas} cuentas · {t.pedidosCancelados} pedidos · {t.pagosAnulados} pagos ({money(t.pagosAnuladosUSD)})
                  </p>
                </div>
              </Card>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
              {[
                { titulo: "Por mesero de la mesa", filas: reporte!.porMesero, nota: "Ajustes sobre las mesas que abrió cada mesero" },
                { titulo: "Por quien autorizó", filas: reporte!.porAutoriza, nota: "Quién dio el visto bueno (por rol o por PIN)" },
                { titulo: "Por motivo", filas: reporte!.porMotivo, nota: "Incluye cancelaciones de cuenta y de pedido" },
              ].map((b) => (
                <Card key={b.titulo} className="overflow-hidden">
                  <div className="px-3 py-2 border-b bg-muted/50">
                    <p className="font-semibold text-sm">{b.titulo}</p>
                    <p className="text-[11px] text-muted-foreground">{b.nota}</p>
                  </div>
                  {b.filas.length === 0 ? (
                    <p className="p-3 text-sm text-muted-foreground">Nada en este rango.</p>
                  ) : (
                    <table className="w-full text-sm">
                      <tbody>
                        {b.filas.map((f) => (
                          <tr key={f.clave} className="border-b last:border-0">
                            <td className="p-2 truncate max-w-[12rem]">{f.nombre}</td>
                            <td className="p-2 text-right tabular-nums text-muted-foreground">{f.cantidad}</td>
                            <td className="p-2 text-right tabular-nums font-medium">{money(f.montoUSD)}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </Card>
              ))}
            </div>
          </>
        )}

        <Card className="overflow-x-auto">
          <div className="px-3 py-2 border-b bg-muted/50 flex flex-wrap items-center justify-between gap-2">
            <p className="font-semibold text-sm">Detalle</p>
            <Select value={filtroTipo} onValueChange={setFiltroTipo}>
              <SelectTrigger className="h-8 w-56 text-xs"><SelectValue placeholder="Todo" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todo</SelectItem>
                <SelectItem value="VOID">Anulaciones</SelectItem>
                <SelectItem value="COMP">Cortesías</SelectItem>
                <SelectItem value="DISCOUNT">Descuentos</SelectItem>
                <SelectItem value="CANCEL_MESA">Cuentas canceladas</SelectItem>
                <SelectItem value="CANCEL_PEDIDO">Pedidos web cancelados</SelectItem>
                <SelectItem value="PAGO_ANULADO">Pagos anulados</SelectItem>
              </SelectContent>
            </Select>
          </div>
          {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>
          ) : detalle.length === 0 ? (
            <div className="p-10 text-center text-muted-foreground">Nada que mostrar en este rango.</div>
          ) : (
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-muted/30 text-left">
                  <th className="p-2 font-semibold">Cuándo</th>
                  <th className="p-2 font-semibold">Tipo</th>
                  <th className="p-2 font-semibold">Mesa</th>
                  <th className="p-2 font-semibold">Qué</th>
                  <th className="p-2 font-semibold">Motivo</th>
                  <th className="p-2 font-semibold text-right">Monto</th>
                  <th className="p-2 font-semibold">Mesero</th>
                  <th className="p-2 font-semibold">Lo hizo</th>
                </tr>
              </thead>
              <tbody>
                {detalle.map((f, i) => (
                  <tr key={`${f.fecha}-${i}`} className="border-b last:border-0 hover:bg-muted/30 align-top">
                    <td className="p-2 whitespace-nowrap text-muted-foreground">
                      {new Date(f.fecha).toLocaleString("es-VE", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}
                    </td>
                    <td className="p-2">
                      <Badge className={cn("text-[11px]", COLOR[f.tipo])}>{f.etiqueta}</Badge>
                      {f.preparado && <span className="block text-[10px] text-red-700 mt-0.5">ya preparado</span>}
                    </td>
                    <td className="p-2 tabular-nums">{f.mesa ?? "—"}</td>
                    <td className="p-2">{f.que}</td>
                    <td className="p-2 max-w-[16rem]">{f.motivo}</td>
                    <td className="p-2 text-right tabular-nums font-medium whitespace-nowrap">−{money(f.montoUSD)}</td>
                    <td className="p-2">{f.mesero ?? "—"}</td>
                    <td className="p-2">
                      {f.hizo}
                      {f.autorizo && <span className="block text-[11px] text-muted-foreground">autorizó {f.autorizo}</span>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </Card>

        <p className="text-xs text-muted-foreground">
          Las anulaciones, cortesías y descuentos existen desde el 2026-09-04 (v1.81.0); las cancelaciones anteriores no tienen motivo. El
          porcentaje compara ajustes de línea contra las ventas registradas en caja del rango (mesa, web y POS). Una anulación «ya preparada» es
          merma real: el plato se hizo y no se cobró.
        </p>
      </div>
    </RoleProtected>
  )
}
