"use client"

import { useMemo, useState } from "react"
import { useQuery } from "convex/react"
import { IconInbox, IconAlertTriangle, IconFilter } from "@tabler/icons-react"
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 {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"
import { usePersistentCompanyFilter } from "@/lib/use-company-filter"
import { Pie, PieChart, Bar, BarChart, CartesianGrid, XAxis } from "recharts"
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart"
import { SearchableCombobox, type SearchableComboboxOption } from "@/components/ui/searchable-combobox"
import { ReportsFilterToolbar } from "@/components/reports/report-filter-toolbar"
import { ReportScheduleDrawer } from "@/components/reports/report-schedule-drawer"

const PRIORITY_LABELS: Record<string, string> = {
  LOW: "Baixa",
  MEDIUM: "Média",
  HIGH: "Alta",
  URGENT: "Crítica",
}

const STATUS_LABELS: Record<string, string> = {
  PENDING: "Pendentes",
  AWAITING_ATTENDANCE: "Em andamento",
  PAUSED: "Pausados",
  RESOLVED: "Resolvidos",
}

const queueBacklogChartConfig = {
  total: {
    label: "Chamados totais",
  },
}

export function BacklogReport() {
  const [timeRange, setTimeRange] = useState<"90d" | "30d" | "7d">("90d")
  const [companyId, setCompanyId] = usePersistentCompanyFilter("all")
  const [schedulerOpen, setSchedulerOpen] = useState(false)
  const [dateFrom, setDateFrom] = useState<string | null>(null)
  const [dateTo, setDateTo] = useState<string | null>(null)
  const { session, convexUserId, isStaff, isAdmin } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const enabled = Boolean(isStaff && convexUserId)

  const dateRangeFilters = useMemo(() => {
    const filters: { dateFrom?: string; dateTo?: string } = {}
    if (dateFrom) filters.dateFrom = dateFrom
    if (dateTo) filters.dateTo = dateTo
    return filters
  }, [dateFrom, dateTo])

  const data = useQuery(
    api.reports.backlogOverview,
    enabled
      ? {
          tenantId,
          viewerId: convexUserId as Id<"users">,
          range: timeRange,
          companyId: companyId === "all" ? undefined : (companyId as Id<"companies">),
          ...dateRangeFilters,
        }
      : "skip"
  )
  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 mostCriticalPriority = useMemo(() => {
    if (!data) return null
    const entries = Object.entries(data.priorityCounts) as Array<[string, number]>
    if (entries.length === 0) return null
    return entries.reduce((prev, current) => (current[1] > prev[1] ? current : prev))
  }, [data])

  const exportHref = useMemo(() => {
    const params = new URLSearchParams()
    params.set("range", timeRange)
    if (companyId !== "all") params.set("companyId", companyId)
    if (dateFrom) params.set("dateFrom", dateFrom)
    if (dateTo) params.set("dateTo", dateTo)
    return `/api/reports/backlog.xlsx?${params.toString()}`
  }, [companyId, dateFrom, dateTo, timeRange])

  if (!data) {
    return (
      <div className="space-y-6">
        {Array.from({ length: 3 }).map((_, index) => (
          <Skeleton key={index} className="h-32 rounded-2xl" />
        ))}
      </div>
    )
  }

  return (
    <div className="space-y-8">
      {isAdmin ? (
        <ReportScheduleDrawer
          open={schedulerOpen}
          onOpenChange={setSchedulerOpen}
          defaultReports={["backlog"]}
          defaultRange={timeRange}
          defaultCompanyId={companyId === "all" ? null : companyId}
          companyOptions={companyOptions}
        />
      ) : null}
      <ReportsFilterToolbar
        companyId={companyId}
        onCompanyChange={(value) => setCompanyId(value)}
        companyOptions={companyOptions}
        timeRange={timeRange}
        onTimeRangeChange={(value) => {
          setTimeRange(value as "90d" | "30d" | "7d")
          setDateFrom(null)
          setDateTo(null)
        }}
        dateFrom={dateFrom}
        dateTo={dateTo}
        onDateRangeChange={({ from, to }) => {
          setDateFrom(from)
          setDateTo(to)
        }}
        exportHref={exportHref}
        onOpenScheduler={isAdmin ? () => setSchedulerOpen(true) : undefined}
      />
      <div className="grid gap-4 md:grid-cols-3">
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
              <IconInbox className="size-4 text-neutral-500" /> Tickets em aberto
            </CardTitle>
            <CardDescription className="text-neutral-600">Backlog total em atendimento.</CardDescription>
          </CardHeader>
          <CardContent className="text-3xl font-semibold text-neutral-900">{data.totalOpen}</CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
              <IconAlertTriangle className="size-4 text-amber-500" /> Prioridade predominante
            </CardTitle>
            <CardDescription className="text-neutral-600">Volume por prioridade no backlog.</CardDescription>
          </CardHeader>
          <CardContent className="text-xl font-semibold text-neutral-900">
            {mostCriticalPriority ? (
              <span>
                {PRIORITY_LABELS[mostCriticalPriority[0]] ?? mostCriticalPriority[0]} ({mostCriticalPriority[1]})
              </span>
            ) : (
              "—"
            )}
          </CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
              <IconFilter className="size-4 text-neutral-500" /> Status acompanhados
            </CardTitle>
            <CardDescription className="text-neutral-600">Distribuição dos tickets por status.</CardDescription>
          </CardHeader>
          <CardContent className="text-xl font-semibold text-neutral-900">
            {Object.keys(data.statusCounts).length}
          </CardContent>
        </Card>
      </div>

      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">Status do backlog</CardTitle>
          <CardDescription className="text-neutral-600">
            Acompanhe a evolução dos tickets pelas fases do fluxo de atendimento.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {(Object.entries(data.statusCounts) as Array<[string, number]>).map(([status, total]) => (
              <div key={status} className="rounded-xl border border-slate-200 p-4">
                <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">
                  {STATUS_LABELS[status] ?? status}
                </p>
                <p className="mt-2 text-2xl font-semibold text-neutral-900">{total}</p>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">Backlog por prioridade</CardTitle>
          <CardDescription className="text-neutral-600">
            Analise a pressão de atendimento conforme o nível de urgência.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {Object.keys(data.priorityCounts).length === 0 ? (
            <p className="rounded-lg border border-dashed border-slate-200 p-6 text-sm text-neutral-500">Sem dados para o período.</p>
          ) : (
            <div className="grid gap-6 md:grid-cols-[1.2fr_1fr]">
              <ChartContainer config={{}} className="aspect-auto h-[260px] w-full">
                <PieChart>
                  <ChartTooltip content={<ChartTooltipContent hideLabel />} />
                  <Pie
                    data={(Object.entries(data.priorityCounts) as Array<[string, number]>).map(([priority, total]) => ({ name: PRIORITY_LABELS[priority] ?? priority, total, fill: `var(--chart-${{LOW:1,MEDIUM:2,HIGH:3,URGENT:4}[priority as keyof typeof PRIORITY_LABELS]||5})` }))}
                    dataKey="total"
                    nameKey="name"
                    label
                  />
                </PieChart>
              </ChartContainer>
              <ul className="space-y-3">
                {(Object.entries(data.priorityCounts) as Array<[string, number]>).map(([priority, total]) => (
                  <li key={priority} className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3">
                    <span className="text-sm font-medium text-neutral-800">{PRIORITY_LABELS[priority] ?? priority}</span>
                    <Badge variant="outline" className="rounded-full border-neutral-300 text-neutral-600">{total} ticket{total === 1 ? "" : "s"}</Badge>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </CardContent>
      </Card>

      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">Filas com maior backlog</CardTitle>
          <CardDescription className="text-neutral-600">
            Identifique onde concentrar esforços de atendimento.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {data.queueCounts.length === 0 ? (
            <p className="rounded-lg border border-dashed border-slate-200 p-6 text-sm text-neutral-500">
              Nenhuma fila com tickets abertos no momento.
            </p>
          ) : (
            <ChartContainer config={queueBacklogChartConfig} className="aspect-auto h-[260px] w-full">
              <BarChart
                data={data.queueCounts.map((q: { name: string; total: number }) => ({ name: q.name, total: q.total }))}
                margin={{ top: 8, left: 20, right: 20, bottom: 56 }}
                barCategoryGap={16}
              >
                <CartesianGrid vertical={false} />
                <XAxis
                  dataKey="name"
                  tickLine={false}
                  axisLine={false}
                  tickMargin={24}
                  interval={0}
                  angle={-30}
                  height={80}
                />
                <Bar dataKey="total" fill="var(--chart-5)" radius={[4, 4, 0, 0]} />
                <ChartTooltip content={<ChartTooltipContent className="w-[180px]" nameKey="total" />} />
              </BarChart>
            </ChartContainer>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
