"use client"

import { useState, useEffect, useMemo } from "react"
import { createClient } from "@/lib/supabase/client"
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table"
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select"
import {
  Popover, PopoverContent, PopoverTrigger,
} from "@/components/ui/popover"
import { cn } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend,
} from "recharts"
import { TrendingUp, TrendingDown, Minus, Trash2, X, ArrowUp, Filter, Download } from "lucide-react"
import * as XLSX from "xlsx"
import { toast } from "sonner"
import { ConfirmDeleteDialog } from "@/components/admin/confirm-delete-dialog"
import type { Database } from "@/lib/supabase/database.types"

// ─── Types ────────────────────────────────────────────────────────────────────

type ResourceTypeRow = Database["public"]["Tables"]["resource_types"]["Row"]

type Reservation = Database["public"]["Tables"]["reservations"]["Row"] & {
  resources: {
    name: string
    resource_type_id: string | null
    resource_types: { name: string } | null
  } | null
  users: { full_name: string | null; email: string } | null
}

// ─── Constants ────────────────────────────────────────────────────────────────

const MONTHS_ES = ["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"]
const DAYS_ES   = ["Dom","Lun","Mar","Mié","Jue","Vie","Sáb"]

const STATUS_LABELS: Record<string, string> = {
  confirmed: "Confirmada", checked_in: "Check-in",
  completed: "Completada", cancelled: "Cancelada", no_show: "No show",
}
const STATUS_STYLES: Record<string, string> = {
  confirmed: "rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-blueprimary-100)] ds-type-global-xxs ds-type-semibold text-[var(--ds-blueprimary-800)]",
  checked_in: "rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-success-100)] ds-type-global-xxs ds-type-semibold text-[var(--ds-success-700)]",
  completed: "rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-neutral-100)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]",
  cancelled: "rounded-[var(--ds-radius-s)] border border-[var(--ds-neutral-300)] bg-[var(--background)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]",
  no_show: "rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-error-100)] ds-type-global-xxs text-[var(--ds-error-700)]",
}
const ACTIVE_STATUSES = ["confirmed", "checked_in", "completed"]
const CHART_GRID_COLOR = "var(--ds-neutral-200)"
const CHART_TICK_STYLE = {
  fontSize: "var(--ds-font-size-global-xxs)",
  fill: "var(--ds-text-neutral-lighter)",
}
const CHART_TOOLTIP_STYLE = {
  borderRadius: "var(--ds-radius-m)",
  border: "1px solid var(--ds-neutral-200)",
  fontSize: "var(--ds-font-size-global-xxs)",
  backgroundColor: "var(--background)",
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

function formatDateTime(iso: string) {
  return new Date(iso).toLocaleString("es-AR", {
    day: "2-digit", month: "2-digit", year: "numeric",
    hour: "2-digit", minute: "2-digit",
  })
}

function deltaPercent(cur: number, prev: number) {
  if (prev === 0) return cur > 0 ? 100 : 0
  return Math.round(((cur - prev) / prev) * 100)
}

// ─── KPI Card ─────────────────────────────────────────────────────────────────

function KpiCard({
  label, value, sub, delta, positiveIsGood = true,
}: {
  label: string; value: string | number; sub?: string
  delta?: number; positiveIsGood?: boolean
}) {
  const neutral  = delta === undefined || delta === 0
  const positive = (delta ?? 0) > 0
  const good     = positiveIsGood ? positive : !positive

  return (
    <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-[var(--background)] p-[var(--ds-space-3x)] shadow-[var(--ds-shadow-4dp)]">
      <p className="mb-[var(--ds-space-1x)] ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">{label}</p>
      <p className="mb-[var(--ds-space-15x)] ds-type-global-xl ds-type-semibold leading-none text-[var(--ds-text-neutral-default)]">
        {value}
      </p>
      <div className="flex items-center gap-[var(--ds-space-1x)]">
        {delta !== undefined && !neutral && (
          <span className={`flex items-center gap-[var(--ds-space-025x)] ds-type-global-xxs ds-type-semibold ${good ? "text-[var(--ds-success-700)]" : "text-[var(--ds-error-700)]"}`}>
            {positive ? (
              <TrendingUp className="h-[var(--ds-space-15x)] w-[var(--ds-space-15x)]" />
            ) : (
              <TrendingDown className="h-[var(--ds-space-15x)] w-[var(--ds-space-15x)]" />
            )}
            {Math.abs(delta)}%
          </span>
        )}
        {delta !== undefined && neutral && (
          <span className="flex items-center gap-[var(--ds-space-025x)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
            <Minus className="h-[var(--ds-space-15x)] w-[var(--ds-space-15x)]" /> Sin cambios
          </span>
        )}
        {sub && <span className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">{sub}</span>}
      </div>
    </div>
  )
}

type TabId = "dashboard" | "reservations"

const PAGE_SIZE = 10

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function MetricsPage() {
  const [reservations,        setReservations]        = useState<Reservation[]>([])
  const [resourceTypes,       setResourceTypes]       = useState<ResourceTypeRow[]>([])
  const [activeResourcesCount, setActiveResourcesCount] = useState(1)
  const [activeResourcesByType, setActiveResourcesByType] = useState<Record<string, number>>({})
  const [loading,             setLoading]             = useState(true)
  const [deleteTarget,        setDeleteTarget]        = useState<Reservation | null>(null)
  const [activeTab,           setActiveTab]           = useState<TabId>("dashboard")
  const [visibleCount,        setVisibleCount]        = useState(PAGE_SIZE)

  // Filters for the reservations table (independent from dashboard filters)
  const [tableFilterResourceType, setTableFilterResourceType] = useState<string>("all")
  const [tableFilterStatus,   setTableFilterStatus]   = useState<string>("all")
  const [tableFilterDateFrom, setTableFilterDateFrom] = useState<string>("")
  const [tableFilterDateTo,   setTableFilterDateTo]   = useState<string>("")
  const [filterOpen,          setFilterOpen]          = useState(false)

  // Filters (dashboard tab only)
  const [filterResourceType, setFilterResourceType] = useState<string>("all")
  const [filterDateFrom, setFilterDateFrom] = useState<string>("")
  const [filterDateTo,   setFilterDateTo]   = useState<string>("")

  const supabase = createClient()
  const hasFilter = filterResourceType !== "all" || !!filterDateFrom || !!filterDateTo

  // ─── Fetch ─────────────────────────────────────────────────────────────────

  const fetchData = async () => {
    const [{ data }, { data: typesData }, { data: activeRows }] = await Promise.all([
      supabase
        .from("reservations")
        .select(
          `*, resources(name, resource_type_id, resource_types(name)), users(full_name, email)`,
        )
        .order("start_at", { ascending: false }),
      supabase.from("resource_types").select("*").eq("is_active", true).order("name"),
      supabase.from("resources").select("resource_type_id").eq("is_active", true),
    ])
    if (data) setReservations(data as Reservation[])
    if (typesData) setResourceTypes(typesData as ResourceTypeRow[])

    const rows = activeRows ?? []
    setActiveResourcesCount(Math.max(1, rows.length))
    const byType: Record<string, number> = {}
    for (const row of rows) {
      if (row.resource_type_id) {
        byType[row.resource_type_id] = (byType[row.resource_type_id] ?? 0) + 1
      }
    }
    setActiveResourcesByType(byType)
    setLoading(false)
  }

  useEffect(() => {
    fetchData()
    const ch = supabase
      .channel("metrics-realtime")
      .on("postgres_changes", { event: "*", schema: "public", table: "reservations" }, fetchData)
      .subscribe()
    return () => { supabase.removeChannel(ch) }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // ─── Filtered data ──────────────────────────────────────────────────────────

  // Resource type filter (used as base for "previous period" in KPIs)
  const typeFiltered = useMemo(() => {
    if (filterResourceType === "all") return reservations
    return reservations.filter(
      (r) => r.resources?.resource_type_id === filterResourceType,
    )
  }, [reservations, filterResourceType])

  // Room + date filter (used for charts and as "current period")
  const filteredData = useMemo(() => {
    return typeFiltered.filter((r) => {
      const d = new Date(r.start_at)
      if (filterDateFrom && d < new Date(filterDateFrom))             return false
      if (filterDateTo   && d > new Date(filterDateTo + "T23:59:59")) return false
      return true
    })
  }, [typeFiltered, filterDateFrom, filterDateTo])

  // ─── KPIs ──────────────────────────────────────────────────────────────────

  const kpis = useMemo(() => {
    const now = new Date()
    const isCustomPeriod = !!(filterDateFrom || filterDateTo)
    const resCount =
      filterResourceType === "all"
        ? activeResourcesCount
        : Math.max(1, activeResourcesByType[filterResourceType] ?? 1)

    let curStart: Date, curEnd: Date, prevStart: Date, prevEnd: Date

    if (isCustomPeriod) {
      curStart = filterDateFrom ? new Date(filterDateFrom) : new Date(0)
      curEnd   = filterDateTo   ? new Date(filterDateTo + "T23:59:59") : new Date()
      const dur = Math.max(curEnd.getTime() - curStart.getTime(), 86_400_000)
      prevEnd   = new Date(curStart.getTime() - 1)
      prevStart = new Date(prevEnd.getTime() - dur)
    } else {
      curStart  = new Date(now.getFullYear(), now.getMonth(), 1)
      curEnd    = new Date()
      prevStart = new Date(now.getFullYear(), now.getMonth() - 1, 1)
      prevEnd   = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59)
    }

    const inRange = (r: Reservation, from: Date, to: Date) => {
      const d = new Date(r.start_at)
      return d >= from && d <= to
    }

    const cur  = typeFiltered.filter((r) => inRange(r, curStart, curEnd))
    const prev = typeFiltered.filter((r) => inRange(r, prevStart, prevEnd))

    const curTotal  = cur.filter((r)  => r.status !== "cancelled").length
    const prevTotal = prev.filter((r) => r.status !== "cancelled").length

    const curCancel  = cur.filter((r)  => r.status === "cancelled").length
    const prevCancel = prev.filter((r) => r.status === "cancelled").length

    const hoursIn = (list: Reservation[]) =>
      list.filter((r) => ACTIVE_STATUSES.includes(r.status))
          .reduce((s, r) => s + (new Date(r.end_at).getTime() - new Date(r.start_at).getTime()) / 3_600_000, 0)

    const daysInCur  = Math.max(1, Math.round((curEnd.getTime()  - curStart.getTime())  / 86_400_000))
    const daysInPrev = Math.max(1, Math.round((prevEnd.getTime() - prevStart.getTime()) / 86_400_000))
    const curOcc  = Math.min((hoursIn(cur)  / (resCount * daysInCur  * 8)) * 100, 100)
    const prevOcc = Math.min((hoursIn(prev) / (resCount * daysInPrev * 8)) * 100, 100)

    const resCounts: Record<string, { name: string; count: number }> = {}
    cur.filter((r) => r.status !== "cancelled" && r.resources).forEach((r) => {
      if (!resCounts[r.resource_id]) resCounts[r.resource_id] = { name: r.resources!.name, count: 0 }
      resCounts[r.resource_id].count++
    })
    const topResource = Object.values(resCounts).sort((a, b) => b.count - a.count)[0]

    const periodLabel = isCustomPeriod ? "en el período" : "este mes"
    const prevLabel   = isCustomPeriod ? "vs período anterior" : `vs ${prevTotal} el mes anterior`

    return {
      curTotal, prevTotal, curCancel, prevCancel,
      curOcc: Math.round(curOcc), prevOcc: Math.round(prevOcc),
      topResource, periodLabel, prevLabel,
    }
  }, [
    typeFiltered,
    filterResourceType,
    filterDateFrom,
    filterDateTo,
    activeResourcesCount,
    activeResourcesByType,
  ])

  // ─── Monthly chart (last 6 months, filtered) ───────────────────────────────

  const monthlyData = useMemo(() => {
    const now = new Date()
    return Array.from({ length: 6 }, (_, i) => {
      const d     = new Date(now.getFullYear(), now.getMonth() - (5 - i), 1)
      const start = new Date(d.getFullYear(), d.getMonth(), 1)
      const end   = new Date(d.getFullYear(), d.getMonth() + 1, 0, 23, 59, 59)
      const month = filteredData.filter((r) => {
        const rd = new Date(r.start_at)
        return rd >= start && rd <= end
      })
      return {
        mes: MONTHS_ES[d.getMonth()],
        Reservas: month.filter((r) => r.status !== "cancelled").length,
        Cancelaciones: month.filter((r) => r.status === "cancelled").length,
      }
    })
  }, [filteredData])

  // ─── Day of week (filtered) ─────────────────────────────────────────────────

  const dowData = useMemo(() => {
    const now = new Date()
    const rangeStart = filterDateFrom
      ? new Date(filterDateFrom)
      : new Date(now.getFullYear(), now.getMonth() - 3, 1)
    const rangeEnd = filterDateTo ? new Date(filterDateTo + "T23:59:59") : now

    const recent = filteredData.filter((r) => {
      const d = new Date(r.start_at)
      return d >= rangeStart && d <= rangeEnd && r.status !== "cancelled"
    })
    const counts = [0, 0, 0, 0, 0, 0, 0]
    recent.forEach((r) => counts[new Date(r.start_at).getDay()]++)
    const weeks = Math.max(1, Math.round((rangeEnd.getTime() - rangeStart.getTime()) / (7 * 86_400_000)))
    return DAYS_ES.map((day, i) => ({
      día: day,
      Promedio: parseFloat((counts[i] / weeks).toFixed(1)),
    }))
  }, [filteredData, filterDateFrom, filterDateTo])

  // ─── Top 5 (filtered) ───────────────────────────────────────────────────────

  const top5 = useMemo(() => {
    const now = new Date()
    const rangeStart = filterDateFrom
      ? new Date(filterDateFrom)
      : new Date(now.getFullYear(), now.getMonth() - 3, 1)
    const rangeEnd = filterDateTo ? new Date(filterDateTo + "T23:59:59") : now

    const counts: Record<string, { name: string; count: number }> = {}
    filteredData
      .filter((r) => {
        const d = new Date(r.start_at)
        return d >= rangeStart && d <= rangeEnd && r.status !== "cancelled" && r.resources
      })
      .forEach((r) => {
        if (!counts[r.resource_id]) counts[r.resource_id] = { name: r.resources!.name, count: 0 }
        counts[r.resource_id].count++
      })
    return Object.values(counts).sort((a, b) => b.count - a.count).slice(0, 5)
  }, [filteredData, filterDateFrom, filterDateTo])

  const top5Max = top5[0]?.count ?? 1

  // ─── Table filtered data ────────────────────────────────────────────────────

  const tableHasFilter =
    tableFilterResourceType !== "all" ||
    tableFilterStatus !== "all" ||
    !!tableFilterDateFrom ||
    !!tableFilterDateTo

  const filteredTableData = useMemo(() => {
    return reservations.filter((r) => {
      if (
        tableFilterResourceType !== "all" &&
        r.resources?.resource_type_id !== tableFilterResourceType
      )
        return false
      if (tableFilterStatus !== "all" && r.status      !== tableFilterStatus) return false
      const d = new Date(r.start_at)
      if (tableFilterDateFrom && d < new Date(tableFilterDateFrom))               return false
      if (tableFilterDateTo   && d > new Date(tableFilterDateTo + "T23:59:59"))   return false
      return true
    })
  }, [
    reservations,
    tableFilterResourceType,
    tableFilterStatus,
    tableFilterDateFrom,
    tableFilterDateTo,
  ])

  const clearTableFilters = () => {
    setTableFilterResourceType("all")
    setTableFilterStatus("all")
    setTableFilterDateFrom("")
    setTableFilterDateTo("")
    setVisibleCount(PAGE_SIZE)
  }

  // ─── Excel export ────────────────────────────────────────────────────────────

  const downloadReport = () => {
    const rows = filteredTableData.map((r) => ({
      "Usuario":    r.users?.full_name || r.users?.email?.split("@")[0] || "—",
      "Email":      r.users?.email ?? "",
      "Sala":       r.resources?.name ?? "—",
      "Tipo":       r.resources?.resource_types?.name ?? "",
      "Inicio":     formatDateTime(r.start_at),
      "Fin":        formatDateTime(r.end_at),
      "Estado":     STATUS_LABELS[r.status] ?? r.status,
    }))
    const ws = XLSX.utils.json_to_sheet(rows)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, "Reservas")
    XLSX.writeFile(wb, `reservas-${new Date().toISOString().split("T")[0]}.xlsx`)
  }

  // ─── Delete ─────────────────────────────────────────────────────────────────

  const handleDelete = async (id: string) => {
    const { error } = await supabase.from("reservations").delete().eq("id", id)
    if (error) { toast.error(error.message); return }
    toast.success("Reserva eliminada")
    fetchData()
  }

  // ─── Render ─────────────────────────────────────────────────────────────────

  return (
    <div className="space-y-[var(--ds-space-4x)]">

      {/* Tabs nav — same style as AdminTabs */}
      <div className="border-b border-[var(--ds-neutral-200)]">
        <nav className="flex gap-[var(--ds-space-3x)]">
          {([
            { id: "dashboard",    label: "Dashboard" },
            { id: "reservations", label: "Todas las reservas" },
          ] as { id: TabId; label: string }[]).map((tab) => (
            <button
              key={tab.id}
              type="button"
              onClick={() => { setActiveTab(tab.id); setVisibleCount(PAGE_SIZE) }}
              className={cn(
                "relative pb-3 ds-type-global-xs transition-colors",
                activeTab === tab.id
                  ? "ds-type-semibold text-[var(--ds-text-neutral-default)]"
                  : "text-[var(--ds-text-neutral-lighter)] hover:text-[var(--ds-text-neutral-default)]",
              )}
            >
              {tab.label}
              {activeTab === tab.id && (
                <span className="absolute inset-x-0 bottom-0 h-[var(--ds-space-025x)] rounded-full bg-[var(--ds-brand-400)]" />
              )}
            </button>
          ))}
        </nav>
      </div>

        {/* ── Tab Dashboard ── */}
        {activeTab === "dashboard" && (
        <div className="space-y-[var(--ds-space-4x)]">
          <h1 className="ds-type-global-l ds-type-semibold text-[var(--ds-text-neutral-default)]">
            Dashboard
          </h1>

          {/* Filter bar */}
          <div className="flex flex-wrap items-center gap-[var(--ds-space-2x)] rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-[var(--background)] px-[var(--ds-space-2x)] py-[var(--ds-space-15x)] shadow-[var(--ds-shadow-4dp)]">
            {/* Tipo de recurso */}
            <Select value={filterResourceType} onValueChange={setFilterResourceType}>
              <SelectTrigger className="h-[var(--ds-space-5x)] w-[calc(var(--ds-space-5x)*5)] rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs text-[var(--ds-text-neutral-default)]">
                <SelectValue placeholder="Todos los tipos de recurso" />
              </SelectTrigger>
              <SelectContent className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-200)] shadow-[var(--ds-shadow-8dp)]">
                <SelectItem value="all" className="ds-type-global-xs">Todos los tipos de recurso</SelectItem>
                {resourceTypes.map((t) => (
                  <SelectItem key={t.id} value={t.id} className="ds-type-global-xs">{t.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>

            {/* Date from */}
            <div className="flex items-center gap-2">
              <label className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)] whitespace-nowrap">
                Desde
              </label>
              <input
                type="date"
                value={filterDateFrom}
                onChange={(e) => setFilterDateFrom(e.target.value)}
                className="h-[var(--ds-space-5x)] rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-300)] px-[var(--ds-space-15x)] ds-type-global-xs text-[var(--ds-text-neutral-default)] focus:outline-none focus:ring-2 focus:ring-[var(--ds-brand-400)]"
              />
            </div>

            {/* Date to */}
            <div className="flex items-center gap-2">
              <label className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)] whitespace-nowrap">
                Hasta
              </label>
              <input
                type="date"
                value={filterDateTo}
                min={filterDateFrom || undefined}
                onChange={(e) => setFilterDateTo(e.target.value)}
                className="h-[var(--ds-space-5x)] rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-300)] px-[var(--ds-space-15x)] ds-type-global-xs text-[var(--ds-text-neutral-default)] focus:outline-none focus:ring-2 focus:ring-[var(--ds-brand-400)]"
              />
            </div>

            {/* Clear */}
            {hasFilter && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => { setFilterResourceType("all"); setFilterDateFrom(""); setFilterDateTo("") }}
                className="h-[var(--ds-space-5x)] gap-[var(--ds-space-05x)] rounded-[var(--ds-radius-m)] ds-type-global-xs text-[var(--ds-text-neutral-lighter)] hover:text-[var(--ds-text-neutral-default)]"
              >
                <X className="h-[var(--ds-space-15x)] w-[var(--ds-space-15x)]" />
                Limpiar filtros
              </Button>
            )}
          </div>

          {loading ? (
            <div className="flex items-center justify-center py-[calc(var(--ds-space-5x)*2)]">
              <div className="h-[var(--ds-space-4x)] w-[var(--ds-space-4x)] animate-spin rounded-full border-[var(--ds-space-05x)] border-[var(--ds-brand-400)] border-t-transparent" />
            </div>
          ) : (
            <>
              {/* KPIs */}
              <div className="grid grid-cols-2 gap-[var(--ds-space-3x)] xl:grid-cols-4">
                <KpiCard
                  label={`Reservas ${kpis.periodLabel}`}
                  value={kpis.curTotal}
                  sub={kpis.prevLabel}
                  delta={deltaPercent(kpis.curTotal, kpis.prevTotal)}
                  positiveIsGood
                />
                <KpiCard
                  label="Tasa de ocupación"
                  value={`${kpis.curOcc}%`}
                  sub={`vs ${kpis.prevOcc}% período anterior`}
                  delta={deltaPercent(kpis.curOcc, kpis.prevOcc)}
                  positiveIsGood
                />
                <KpiCard
                  label={`Cancelaciones ${kpis.periodLabel}`}
                  value={kpis.curCancel}
                  sub={`vs ${kpis.prevCancel} período anterior`}
                  delta={deltaPercent(kpis.curCancel, kpis.prevCancel)}
                  positiveIsGood={false}
                />
                <KpiCard
                  label="Recurso más reservado"
                  value={kpis.topResource?.name ?? "—"}
                  sub={
                    kpis.topResource
                      ? `${kpis.topResource.count} ${kpis.topResource.count === 1 ? "reserva" : "reservas"} ${kpis.periodLabel}`
                      : `Sin reservas ${kpis.periodLabel}`
                  }
                />
              </div>

              {/* Charts row */}
              <div className="grid grid-cols-1 gap-[var(--ds-space-3x)] xl:grid-cols-2">
                {/* Monthly */}
                <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-[var(--background)] p-[var(--ds-space-3x)] shadow-[var(--ds-shadow-4dp)]">
                  <p className="mb-[var(--ds-space-05x)] ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)]">
                    Reservas y cancelaciones por mes
                  </p>
                  <p className="mb-[var(--ds-space-3x)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                    Últimos 6 meses{filterResourceType !== "all" && ` · ${resourceTypes.find((t) => t.id === filterResourceType)?.name}`}
                  </p>
                  <ResponsiveContainer width="100%" height={220}>
                    <BarChart data={monthlyData} barCategoryGap="30%" barGap={4}>
                      <CartesianGrid strokeDasharray="3 3" stroke={CHART_GRID_COLOR} vertical={false} />
                      <XAxis dataKey="mes" tick={CHART_TICK_STYLE} axisLine={false} tickLine={false} />
                      <YAxis allowDecimals={false} tick={CHART_TICK_STYLE} axisLine={false} tickLine={false} />
                      <Tooltip contentStyle={CHART_TOOLTIP_STYLE} />
                      <Legend
                        wrapperStyle={{
                          fontSize: "var(--ds-font-size-global-xxs)",
                          paddingTop: "var(--ds-space-15x)",
                        }}
                        iconType="circle"
                        iconSize={8}
                      />
                      <Bar dataKey="Reservas" fill="var(--ds-brand-400)" />
                      <Bar dataKey="Cancelaciones" fill="var(--ds-error-700)" />
                    </BarChart>
                  </ResponsiveContainer>
                </div>

                {/* Day of week */}
                <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-[var(--background)] p-[var(--ds-space-3x)] shadow-[var(--ds-shadow-4dp)]">
                  <p className="mb-[var(--ds-space-05x)] ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)]">
                    Promedio de reservas por día
                  </p>
                  <p className="mb-[var(--ds-space-3x)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                    {filterDateFrom || filterDateTo ? "Período seleccionado" : "Últimos 3 meses"}
                    {filterResourceType !== "all" && ` · ${resourceTypes.find((t) => t.id === filterResourceType)?.name}`}
                  </p>
                  <ResponsiveContainer width="100%" height={220}>
                    <BarChart data={dowData} barCategoryGap="30%">
                      <CartesianGrid strokeDasharray="3 3" stroke={CHART_GRID_COLOR} vertical={false} />
                      <XAxis dataKey="día" tick={CHART_TICK_STYLE} axisLine={false} tickLine={false} />
                      <YAxis allowDecimals tick={CHART_TICK_STYLE} axisLine={false} tickLine={false} />
                      <Tooltip contentStyle={CHART_TOOLTIP_STYLE} />
                      <Bar dataKey="Promedio" fill="var(--ds-brand-400)" />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </div>

              {/* Top 5 */}
              <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-[var(--background)] p-[var(--ds-space-3x)] shadow-[var(--ds-shadow-4dp)]">
                <p className="mb-[var(--ds-space-05x)] ds-type-global-s ds-type-semibold text-[var(--ds-text-neutral-default)]">
                  Top 5 recursos más reservados
                </p>
                <p className="mb-[var(--ds-space-3x)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                  {filterDateFrom || filterDateTo ? "Período seleccionado" : "Últimos 3 meses"}
                </p>
                {top5.length === 0 ? (
                  <p className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)] text-center py-6">
                    Sin datos para el período seleccionado
                  </p>
                ) : (
                  <div className="space-y-[var(--ds-space-3x)]">
                    {top5.map((r, i) => (
                      <div key={r.name} className="flex items-center gap-[var(--ds-space-2x)]">
                        <span className="w-[var(--ds-space-2x)] text-right ds-type-global-xxs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">{i + 1}</span>
                        <span className="w-[calc(var(--ds-space-5x)*4)] shrink-0 truncate ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">{r.name}</span>
                        <div className="flex-1 h-2 rounded-full bg-[var(--ds-neutral-100)] overflow-hidden">
                          <div
                            className="h-2 rounded-full bg-[var(--ds-brand-400)] transition-all duration-500"
                            style={{ width: `${(r.count / top5Max) * 100}%` }}
                          />
                        </div>
                        <span className="w-[var(--ds-space-4x)] text-right ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">{r.count}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </>
          )}
        </div>
        )}

        {/* ── Tab Todas las reservas ── */}
        {activeTab === "reservations" && (
        <div className="space-y-[var(--ds-space-4x)]">
          <h1 className="ds-type-global-l ds-type-semibold text-[var(--ds-text-neutral-default)]">
            Todas las reservas
          </h1>
          <div className="rounded-[var(--ds-radius-l)] border border-[var(--ds-neutral-200)] bg-[var(--background)] shadow-[var(--ds-shadow-4dp)]">
            <div className="flex items-center justify-between px-[var(--ds-space-3x)] py-[var(--ds-space-2x)]">
              <span className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
                {filteredTableData.length} {filteredTableData.length === 1 ? "reserva" : "reservas"}
                {tableHasFilter ? " (filtradas)" : " en total"}
              </span>
              <div className="flex items-center gap-2">
                {/* Filter popover */}
                <Popover open={filterOpen} onOpenChange={setFilterOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      size="sm"
                      className={cn(
                        "h-[var(--ds-space-5x)] gap-[var(--ds-space-1x)] rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs ds-type-semibold",
                        tableHasFilter
                          ? "border-[var(--ds-brand-400)] text-[var(--ds-brand-400)]"
                          : "text-[var(--ds-text-neutral-default)]",
                      )}
                    >
                      <Filter className="h-[var(--ds-space-15x)] w-[var(--ds-space-15x)]" />
                      Filtrar
                      {tableHasFilter && (
                        <span className="flex h-[var(--ds-space-2x)] w-[var(--ds-space-2x)] items-center justify-center rounded-full bg-[var(--ds-brand-400)] text-[var(--ds-font-size-global-xxxs)] ds-type-semibold text-[var(--background)]">
                          {[tableFilterResourceType !== "all", tableFilterStatus !== "all", !!tableFilterDateFrom, !!tableFilterDateTo].filter(Boolean).length}
                        </span>
                      )}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent
                    align="end"
                    className="w-[calc(var(--ds-space-9x)*4)] rounded-[var(--ds-radius-l)] border-[var(--ds-neutral-200)] p-[var(--ds-space-2x)] shadow-[var(--ds-shadow-8dp)]"
                  >
                    <div className="space-y-[var(--ds-space-2x)]">
                      <p className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                        Filtros
                      </p>

                      {/* Tipo de recurso */}
                      <div className="space-y-1.5">
                        <label className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">Tipo de recurso</label>
                        <Select value={tableFilterResourceType} onValueChange={(v) => { setTableFilterResourceType(v); setVisibleCount(PAGE_SIZE) }}>
                          <SelectTrigger className="h-[var(--ds-space-5x)] w-full rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs">
                            <SelectValue placeholder="Todos los tipos de recurso" />
                          </SelectTrigger>
                          <SelectContent className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-200)] shadow-[var(--ds-shadow-8dp)]">
                            <SelectItem value="all" className="ds-type-global-xs">Todos los tipos de recurso</SelectItem>
                            {resourceTypes.map((t) => (
                              <SelectItem key={t.id} value={t.id} className="ds-type-global-xs">{t.name}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Estado */}
                      <div className="space-y-1.5">
                        <label className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">Estado</label>
                        <Select value={tableFilterStatus} onValueChange={(v) => { setTableFilterStatus(v); setVisibleCount(PAGE_SIZE) }}>
                          <SelectTrigger className="h-[var(--ds-space-5x)] w-full rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs">
                            <SelectValue placeholder="Todos los estados" />
                          </SelectTrigger>
                          <SelectContent className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-200)] shadow-[var(--ds-shadow-8dp)]">
                            <SelectItem value="all" className="ds-type-global-xs">Todos los estados</SelectItem>
                            {Object.entries(STATUS_LABELS).map(([val, label]) => (
                              <SelectItem key={val} value={val} className="ds-type-global-xs">{label}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Fecha desde */}
                      <div className="space-y-1.5">
                        <label className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">Desde</label>
                        <input
                          type="date"
                          value={tableFilterDateFrom}
                          onChange={(e) => { setTableFilterDateFrom(e.target.value); setVisibleCount(PAGE_SIZE) }}
                          className="h-[var(--ds-space-5x)] w-full rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-300)] px-[var(--ds-space-15x)] ds-type-global-xs text-[var(--ds-text-neutral-default)] focus:outline-none focus:ring-2 focus:ring-[var(--ds-brand-400)]"
                        />
                      </div>

                      {/* Fecha hasta */}
                      <div className="space-y-1.5">
                        <label className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">Hasta</label>
                        <input
                          type="date"
                          value={tableFilterDateTo}
                          min={tableFilterDateFrom || undefined}
                          onChange={(e) => { setTableFilterDateTo(e.target.value); setVisibleCount(PAGE_SIZE) }}
                          className="h-[var(--ds-space-5x)] w-full rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-300)] px-[var(--ds-space-15x)] ds-type-global-xs text-[var(--ds-text-neutral-default)] focus:outline-none focus:ring-2 focus:ring-[var(--ds-brand-400)]"
                        />
                      </div>

                      {tableHasFilter && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => { clearTableFilters(); setFilterOpen(false) }}
                          className="w-full gap-[var(--ds-space-05x)] rounded-[var(--ds-radius-m)] ds-type-global-xs text-[var(--ds-text-neutral-lighter)] hover:text-[var(--ds-text-neutral-default)]"
                        >
                          <X className="h-[var(--ds-space-15x)] w-[var(--ds-space-15x)]" />
                          Limpiar filtros
                        </Button>
                      )}
                    </div>
                  </PopoverContent>
                </Popover>

                {/* Download */}
                <Button
                  variant="outline"
                  size="sm"
                  onClick={downloadReport}
                  className="h-[var(--ds-space-5x)] gap-[var(--ds-space-1x)] rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]"
                >
                  <Download className="h-[var(--ds-space-15x)] w-[var(--ds-space-15x)]" />
                  Descargar reporte
                </Button>
              </div>
            </div>
            {loading ? (
              <div className="flex items-center justify-center py-[calc(var(--ds-space-3x)*2)]">
                <div className="h-[var(--ds-space-4x)] w-[var(--ds-space-4x)] animate-spin rounded-full border-[var(--ds-space-05x)] border-[var(--ds-brand-400)] border-t-transparent" />
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow className="border-[var(--ds-neutral-200)]">
                    <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">Usuario</TableHead>
                    <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">Recurso</TableHead>
                    <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">Inicio</TableHead>
                    <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">Fin</TableHead>
                    <TableHead className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-lighter)]">Estado</TableHead>
                    <TableHead className="w-[calc(var(--ds-space-3x)*2)]" />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredTableData.slice(0, visibleCount).map((r) => (
                    <TableRow key={r.id} className="border-[var(--ds-neutral-200)] hover:bg-[var(--ds-neutral-100)]">
                      <TableCell className="ds-type-global-xs">
                        <div className="ds-type-semibold text-[var(--ds-text-neutral-default)]">
                          {r.users?.full_name || r.users?.email?.split("@")[0] || "—"}
                        </div>
                        <div className="text-[var(--ds-text-neutral-lighter)]">{r.users?.email ?? ""}</div>
                      </TableCell>
                      <TableCell className="ds-type-global-xs">
                        <div className="ds-type-semibold text-[var(--ds-text-neutral-default)]">{r.resources?.name ?? "—"}</div>
                        <div className="text-[var(--ds-text-neutral-lighter)]">{r.resources?.resource_types?.name ?? ""}</div>
                      </TableCell>
                      <TableCell className="ds-type-global-xs text-[var(--ds-text-neutral-default)]">{formatDateTime(r.start_at)}</TableCell>
                      <TableCell className="ds-type-global-xs text-[var(--ds-text-neutral-default)]">{formatDateTime(r.end_at)}</TableCell>
                      <TableCell>
                        <Badge className={STATUS_STYLES[r.status] ?? STATUS_STYLES.confirmed}>
                          {STATUS_LABELS[r.status] ?? r.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="w-[calc(var(--ds-space-3x)*2)] text-right">
                        <Button
                          variant="ghost" size="icon"
                          className="h-[var(--ds-space-4x)] w-[var(--ds-space-4x)] rounded-[var(--ds-radius-m)] text-[var(--ds-text-neutral-lighter)] hover:bg-[var(--ds-error-100)] hover:text-[var(--ds-error-700)]"
                          onClick={() => setDeleteTarget(r)}
                        >
                          <Trash2 className="h-[var(--ds-space-2x)] w-[var(--ds-space-2x)]" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                  {filteredTableData.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={6} className="py-12 text-center ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
                        {tableHasFilter ? "No hay reservas para los filtros seleccionados" : "No hay reservas registradas"}
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            )}

            {/* Cargar más */}
            {!loading && visibleCount < filteredTableData.length && (
              <div className="flex items-center justify-center gap-[var(--ds-space-3x)] border-t border-[var(--ds-neutral-200)] px-[var(--ds-space-3x)] py-[var(--ds-space-2x)]">
                <Button
                  variant="outline"
                  onClick={() => setVisibleCount((n) => n + PAGE_SIZE)}
                  className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]"
                >
                  Cargar más
                </Button>
                <span className="ds-type-global-xs text-[var(--ds-text-neutral-lighter)]">
                  {Math.min(visibleCount, filteredTableData.length)} de {filteredTableData.length}
                </span>
                <button
                  type="button"
                  onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
                  className="flex h-[var(--ds-space-4x)] w-[var(--ds-space-4x)] items-center justify-center rounded-[var(--ds-radius-m)] border border-[var(--ds-neutral-300)] text-[var(--ds-text-neutral-lighter)] hover:bg-[var(--ds-neutral-100)] hover:text-[var(--ds-text-neutral-default)]"
                  aria-label="Ir arriba"
                >
                  <ArrowUp className="h-[var(--ds-space-2x)] w-[var(--ds-space-2x)]" />
                </button>
              </div>
            )}
          </div>
        </div>
        )}

      <ConfirmDeleteDialog
        open={!!deleteTarget}
        onOpenChange={(open) => { if (!open) setDeleteTarget(null) }}
        title="¿Eliminar esta reserva?"
        description={
          deleteTarget
            ? `Se eliminará la reserva de ${deleteTarget.users?.full_name || deleteTarget.users?.email || "este usuario"} para ${deleteTarget.resources?.name ?? "este recurso"}. Esta acción no se puede deshacer.`
            : ""
        }
        onConfirm={async () => {
          if (deleteTarget) await handleDelete(deleteTarget.id)
          setDeleteTarget(null)
        }}
      />
    </div>
  )
}
