"use client"

import { useMemo, useState } from "react"
import { useQuery } from "convex/react"
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts"

import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { useAuth } from "@/lib/auth-client"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { usePersistentCompanyFilter } from "@/lib/use-company-filter"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { ReportsFilterToolbar } from "@/components/reports/report-filter-toolbar"
import { SearchableCombobox, type SearchableComboboxOption } from "@/components/ui/searchable-combobox"
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart"
import { formatDateDM } from "@/lib/utils"
import { Skeleton } from "@/components/ui/skeleton"

type MachineCategoryDailyItem = {
  date: string
  machineId: string | null
  machineHostname: string | null
  companyId: string | null
  companyName: string | null
  categoryId: string | null
  categoryName: string
  total: number
}

type MachineCategoryReportData = {
  rangeDays: number
  items: MachineCategoryDailyItem[]
}

export function MachineCategoryReport() {
  const [timeRange, setTimeRange] = useState("30d")
  const [companyId, setCompanyId] = usePersistentCompanyFilter("all")
  const { session, convexUserId, isStaff } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID

  const canView = Boolean(isStaff)
  const enabled = Boolean(canView && convexUserId)

  const data = useQuery(
    api.reports.ticketsByMachineAndCategory,
    enabled
      ? ({
          tenantId,
          viewerId: convexUserId as Id<"users">,
          range: timeRange,
          companyId: companyId === "all" ? undefined : (companyId as Id<"companies">),
        } as const)
      : "skip"
  ) as MachineCategoryReportData | undefined

  const companies = useQuery(
    api.companies.list,
    enabled ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
  ) as Array<{ id: Id<"companies">; name: string }> | undefined

  const companyOptions = useMemo<SearchableComboboxOption[]>(() => {
    const base: SearchableComboboxOption[] = [{ value: "all", label: "Todas as empresas" }]
    if (!companies || companies.length === 0) {
      return base
    }
    const sorted = [...companies].sort((a, b) => a.name.localeCompare(b.name, "pt-BR"))
    return [
      base[0],
      ...sorted.map((company) => ({
        value: company.id,
        label: company.name,
      })),
    ]
  }, [companies])

  const items = useMemo(() => data?.items ?? [], [data])

  const totals = useMemo(
    () =>
      items.reduce(
        (acc, item) => {
          acc.totalTickets += item.total
          acc.machines.add(item.machineId ?? item.machineHostname ?? "sem-maquina")
          acc.categories.add(item.categoryName)
          return acc
        },
        {
          totalTickets: 0,
          machines: new Set<string>(),
          categories: new Set<string>(),
        }
      ),
    [items]
  )

  const dailySeries = useMemo(
    () => {
      const map = new Map<string, number>()
      for (const item of items) {
        const current = map.get(item.date) ?? 0
        map.set(item.date, current + item.total)
      }
      return Array.from(map.entries())
        .map(([date, total]) => ({ date, total }))
        .sort((a, b) => a.date.localeCompare(b.date))
    },
    [items]
  )

  const tableRows = useMemo(
    () =>
      [...items].sort((a, b) => {
        if (a.date !== b.date) return b.date.localeCompare(a.date)
        const machineA = (a.machineHostname ?? "").toLowerCase()
        const machineB = (b.machineHostname ?? "").toLowerCase()
        if (machineA !== machineB) return machineA.localeCompare(machineB)
        return a.categoryName.localeCompare(b.categoryName, "pt-BR")
      }),
    [items]
  )

  if (!canView) {
    return (
      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">Máquinas x categorias</CardTitle>
          <CardDescription className="text-neutral-600">
            Este relatório está disponível apenas para a equipe interna.
          </CardDescription>
        </CardHeader>
      </Card>
    )
  }

  if (!data) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-16 rounded-2xl" />
        <Skeleton className="h-64 rounded-2xl" />
        <Skeleton className="h-80 rounded-2xl" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <ReportsFilterToolbar
        companyId={companyId}
        onCompanyChange={(value) => setCompanyId(value)}
        companyOptions={companyOptions}
        timeRange={timeRange as "90d" | "30d" | "7d"}
        onTimeRangeChange={(value) => setTimeRange(value)}
      />

      <div className="grid gap-4 md:grid-cols-3">
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="text-xs font-semibold uppercase tracking-wide text-neutral-500">
              Chamados analisados
            </CardTitle>
            <CardDescription className="text-neutral-600">
              Total de tickets com máquina vinculada no período.
            </CardDescription>
          </CardHeader>
          <CardContent className="text-3xl font-semibold text-neutral-900">
            {totals.totalTickets}
          </CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="text-xs font-semibold uppercase tracking-wide text-neutral-500">
              Máquinas únicas
            </CardTitle>
            <CardDescription className="text-neutral-600">
              Quantidade de dispositivos diferentes com chamados no período.
            </CardDescription>
          </CardHeader>
          <CardContent className="text-3xl font-semibold text-neutral-900">
            {totals.machines.size}
          </CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="text-xs font-semibold uppercase tracking-wide text-neutral-500">
              Categorias
            </CardTitle>
            <CardDescription className="text-neutral-600">
              Categorias distintas associadas aos tickets dessas máquinas.
            </CardDescription>
          </CardHeader>
          <CardContent className="text-3xl font-semibold text-neutral-900">
            {totals.categories.size}
          </CardContent>
        </Card>
      </div>

      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">
            Volume diário por máquina (total)
          </CardTitle>
          <CardDescription className="text-neutral-600">
            Quantidade de chamados com máquina vinculada, somando todas as categorias, por dia.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {dailySeries.length === 0 ? (
            <p className="rounded-lg border border-dashed border-slate-200 p-6 text-sm text-neutral-500">
              Nenhum ticket com máquina vinculada foi encontrado para o período selecionado.
            </p>
          ) : (
            <ChartContainer config={{}} className="aspect-auto h-[260px] w-full">
              <BarChart data={dailySeries} margin={{ top: 8, left: 20, right: 20, bottom: 32 }}>
                <CartesianGrid vertical={false} />
                <XAxis
                  dataKey="date"
                  tickLine={false}
                  axisLine={false}
                  tickMargin={8}
                  minTickGap={24}
                  tickFormatter={(value) => formatDateDM(new Date(String(value)))}
                />
                <ChartTooltip
                  content={
                    <ChartTooltipContent
                      className="w-[180px]"
                      labelFormatter={(value) => formatDateDM(new Date(String(value)))}
                    />
                  }
                />
                <Bar dataKey="total" fill="var(--chart-1)" radius={[4, 4, 0, 0]} name="Chamados" />
              </BarChart>
            </ChartContainer>
          )}
        </CardContent>
      </Card>

      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">
            Detalhamento diário por máquina e categoria
          </CardTitle>
          <CardDescription className="text-neutral-600">
            Cada linha representa o total de chamados abertos em uma data específica, agrupados por
            máquina e categoria.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {tableRows.length === 0 ? (
            <p className="rounded-lg border border-dashed border-slate-200 p-6 text-sm text-neutral-500">
              Nenhum ticket com máquina vinculada foi encontrado para o período selecionado.
            </p>
          ) : (
            <div className="overflow-hidden rounded-2xl border border-slate-200">
              <table className="w-full text-sm">
                <thead className="bg-slate-50 text-xs uppercase tracking-wide text-neutral-500">
                  <tr>
                    <th className="px-4 py-3 text-left">Data</th>
                    <th className="px-4 py-3 text-left">Máquina</th>
                    <th className="px-4 py-3 text-left">Empresa</th>
                    <th className="px-4 py-3 text-left">Categoria</th>
                    <th className="px-4 py-3 text-right">Chamados</th>
                  </tr>
                </thead>
                <tbody>
                  {tableRows.map((row, index) => {
                    const machineLabel =
                      row.machineHostname && row.machineHostname.trim().length > 0
                        ? row.machineHostname
                        : "Sem hostname"
                    const companyLabel = row.companyName ?? "Sem empresa"
                    return (
                      <tr key={`${row.date}-${machineLabel}-${row.categoryName}-${index}`} className="border-t border-slate-100">
                        <td className="px-4 py-2 text-neutral-800">
                          {formatDateDM(new Date(`${row.date}T00:00:00Z`))}
                        </td>
                        <td className="px-4 py-2 text-neutral-800">{machineLabel}</td>
                        <td className="px-4 py-2 text-neutral-700">{companyLabel}</td>
                        <td className="px-4 py-2 text-neutral-700">{row.categoryName}</td>
                        <td className="px-4 py-2 text-right font-semibold text-neutral-900">{row.total}</td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
