"use client"

import { useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { useQuery } from "convex/react"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { useAuth } from "@/lib/auth-client"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  ChartConfig,
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart"
import { Area, AreaChart, CartesianGrid, XAxis, Bar, BarChart, Pie, PieChart } from "recharts"
import { SearchableCombobox, type SearchableComboboxOption } from "@/components/ui/searchable-combobox"
import { TicketPriorityPill } from "@/components/tickets/priority-pill"
import { TicketStatusBadge } from "@/components/tickets/status-badge"
import { formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"
import type { TicketPriority, TicketStatus } from "@/lib/schemas/ticket"

type CompanyRecord = { id: Id<"companies">; name: string }

const STATUS_LABELS: Record<string, string> = {
  PENDING: "Pendente",
  AWAITING_ATTENDANCE: "Em andamento",
  PAUSED: "Pausado",
  RESOLVED: "Resolvido",
}

const TICKET_TREND_CONFIG = {
  opened: {
    label: "Abertos",
    color: "var(--chart-1)",
  },
  resolved: {
    label: "Resolvidos",
    color: "var(--chart-2)",
  },
} satisfies ChartConfig

const MACHINE_STATUS_CONFIG = {
  online: { label: "Online", color: "var(--chart-1)" },
  offline: { label: "Offline", color: "var(--chart-2)" },
  stale: { label: "Sem sinal", color: "var(--chart-3)" },
  maintenance: { label: "Manutenção", color: "var(--chart-4)" },
  blocked: { label: "Bloqueada", color: "var(--chart-5)" },
  deactivated: { label: "Desativada", color: "var(--chart-6)" },
  unknown: { label: "Desconhecida", color: "var(--muted)" },
} satisfies ChartConfig

export function CompanyReport() {
  const { session, convexUserId, isStaff } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const [selectedCompany, setSelectedCompany] = useState<string>("")
  const [timeRange, setTimeRange] = useState<"7d" | "30d" | "90d">("30d")

  const companies = useQuery(
    api.companies.list,
    isStaff && convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
  ) as CompanyRecord[] | undefined

  const companyOptions = useMemo<SearchableComboboxOption[]>(
    () =>
      (companies ?? []).map((company) => ({
        value: company.id as string,
        label: company.name,
      })),
    [companies]
  )

  useEffect(() => {
    if (!selectedCompany && companyOptions.length > 0) {
      setSelectedCompany(companyOptions[0]?.value ?? "")
    }
  }, [companyOptions, selectedCompany])

  const report = useQuery(
    api.reports.companyOverview,
    selectedCompany && convexUserId && isStaff
      ? {
          tenantId,
          viewerId: convexUserId as Id<"users">,
          companyId: selectedCompany as Id<"companies">,
          range: timeRange,
        }
      : "skip"
  )

  const isLoading = selectedCompany !== "" && report === undefined

  const openTickets = ((report?.tickets.open ?? []) as Array<{
    id: string
    reference: number
    subject: string
    status: string
    priority: string
    updatedAt: number
  }>).slice(0, 6)

  const openTicketCount = (() => {
    const source = report?.tickets.byStatus ?? {}
    return Object.entries(source).reduce((acc, [status, total]) => {
      if (status === "RESOLVED") return acc
      return acc + (typeof total === "number" ? total : 0)
    }, 0)
  })()

  const statusData = Object.entries(report?.tickets.byStatus ?? {}).map(([status, value]) => ({
    status,
    value: typeof value === "number" ? value : 0,
  }))

  const osData = (report?.machines.byOs ?? []).map((item: { label: string; value: number }, index: number) => ({
    ...item,
    fill: `var(--chart-${(index % 6) + 1})`,
  }))

  if (!isStaff) {
    return (
      <Card className="border-slate-200">
        <CardContent className="p-6">
          <p className="text-sm text-muted-foreground">Somente a equipe interna pode acessar este relatório.</p>
        </CardContent>
      </Card>
    )
  }

  if (companies && companies.length === 0) {
    return (
      <Card className="border-slate-200">
        <CardContent className="p-6">
          <p className="text-sm text-muted-foreground">Nenhuma empresa disponível para gerar relatórios.</p>
        </CardContent>
      </Card>
    )
  }

  return (
    <div className="space-y-8">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="space-y-1">
          <h2 className="text-xl font-semibold text-neutral-900">Visão consolidada por empresa</h2>
          <p className="text-sm text-neutral-500">Acompanhe tickets, inventário e colaboradores de um cliente específico.</p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <div className="w-[260px]">
            <SearchableCombobox
              value={selectedCompany || null}
              onValueChange={(value) => {
                if (value) setSelectedCompany(value)
              }}
              options={companyOptions}
              placeholder="Selecionar empresa"
              searchPlaceholder="Buscar empresa..."
              emptyText="Nenhuma empresa encontrada."
              disabled={!companyOptions.length}
            />
          </div>
          <Select value={timeRange} onValueChange={(value) => setTimeRange(value as typeof timeRange)}>
            <SelectTrigger className="w-[160px] rounded-xl border-slate-200">
              <SelectValue placeholder="Período" />
            </SelectTrigger>
            <SelectContent className="rounded-xl">
              <SelectItem value="7d">Últimos 7 dias</SelectItem>
              <SelectItem value="30d">Últimos 30 dias</SelectItem>
              <SelectItem value="90d">Últimos 90 dias</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {!report || isLoading ? (
        <div className="space-y-6">
          <Skeleton className="h-24 w-full rounded-2xl" />
          <Skeleton className="h-72 w-full rounded-2xl" />
          <div className="grid gap-6 md:grid-cols-2">
            <Skeleton className="h-72 w-full rounded-2xl" />
            <Skeleton className="h-72 w-full rounded-2xl" />
          </div>
        </div>
      ) : (
        <>
          <div className="grid gap-4 lg:grid-cols-3">
            <Card className="border-slate-200">
              <CardHeader>
                <CardTitle className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Tickets em aberto</CardTitle>
                <CardDescription className="text-neutral-600">Chamados associados a esta empresa.</CardDescription>
              </CardHeader>
              <CardContent className="text-3xl font-semibold text-neutral-900">{openTicketCount}</CardContent>
            </Card>
            <Card className="border-slate-200">
              <CardHeader>
                <CardTitle className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Dispositivos monitoradas</CardTitle>
                <CardDescription className="text-neutral-600">Inventário registrado nesta empresa.</CardDescription>
              </CardHeader>
              <CardContent className="text-3xl font-semibold text-neutral-900">{report.machines.total}</CardContent>
            </Card>
            <Card className="border-slate-200">
              <CardHeader>
                <CardTitle className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Colaboradores ativos</CardTitle>
                <CardDescription className="text-neutral-600">Usuários vinculados à empresa.</CardDescription>
              </CardHeader>
              <CardContent className="text-3xl font-semibold text-neutral-900">{report.users.total}</CardContent>
            </Card>
          </div>

          <Card className="border-slate-200">
            <CardHeader className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <CardTitle className="text-lg font-semibold text-neutral-900">Abertura x resolução de tickets</CardTitle>
                <CardDescription className="text-neutral-600">
                  Comparativo diário no período selecionado.
                </CardDescription>
              </div>
            </CardHeader>
            <CardContent className="px-2 pb-6 sm:px-6">
              <ChartContainer config={TICKET_TREND_CONFIG} className="aspect-auto h-[280px] w-full">
                <AreaChart data={report.tickets.trend}>
                  <defs>
                    <linearGradient id="trendOpened" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="var(--color-opened)" stopOpacity={0.8} />
                      <stop offset="95%" stopColor="var(--color-opened)" stopOpacity={0.1} />
                    </linearGradient>
                    <linearGradient id="trendResolved" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="var(--color-resolved)" stopOpacity={0.8} />
                      <stop offset="95%" stopColor="var(--color-resolved)" stopOpacity={0.1} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid vertical={false} />
                  <XAxis
                    dataKey="date"
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                    minTickGap={32}
                    tickFormatter={(value) => {
                      const date = new Date(value)
                      return date.toLocaleDateString("pt-BR", { day: "2-digit", month: "short" })
                    }}
                  />
                  <ChartTooltip
                    content={
                      <ChartTooltipContent
                        labelFormatter={(value) =>
                          new Date(value).toLocaleDateString("pt-BR", {
                            day: "2-digit",
                            month: "long",
                            year: "numeric",
                          })
                        }
                      />
                    }
                  />
                  <Area dataKey="opened" type="monotone" stroke="var(--color-opened)" fill="url(#trendOpened)" strokeWidth={2} />
                  <Area dataKey="resolved" type="monotone" stroke="var(--color-resolved)" fill="url(#trendResolved)" strokeWidth={2} />
                  <ChartLegend content={<ChartLegendContent />} />
                </AreaChart>
              </ChartContainer>
            </CardContent>
          </Card>

          <div className="grid gap-6 lg:grid-cols-[1.2fr_1fr]">
            <Card className="border-slate-200">
              <CardHeader>
                <CardTitle className="text-lg font-semibold text-neutral-900">Distribuição de status dos tickets</CardTitle>
                <CardDescription className="text-neutral-600">Status atuais dos chamados da empresa.</CardDescription>
              </CardHeader>
              <CardContent className="px-2 pb-6 sm:px-6">
                <ChartContainer config={{}} className="aspect-auto h-[280px] w-full">
                  <BarChart data={statusData}>
                    <CartesianGrid vertical={false} />
                    <XAxis
                      dataKey="status"
                      tickLine={false}
                      axisLine={false}
                      tickMargin={8}
                      tickFormatter={(value) => STATUS_LABELS[value] ?? value}
                    />
                    <ChartTooltip
                      content={
                        <ChartTooltipContent
                          nameKey="value"
                          labelFormatter={(value) => STATUS_LABELS[value] ?? value}
                        />
                      }
                    />
                    <Bar dataKey="value" fill="var(--chart-3)" radius={[4, 4, 0, 0]} />
                  </BarChart>
                </ChartContainer>
              </CardContent>
            </Card>

            <Card className="border-slate-200">
              <CardHeader>
                <CardTitle className="text-lg font-semibold text-neutral-900">Sistemas operacionais</CardTitle>
                <CardDescription className="text-neutral-600">Inventário das dispositivos desta empresa.</CardDescription>
              </CardHeader>
              <CardContent className="pb-6">
                <ChartContainer config={MACHINE_STATUS_CONFIG} className="mx-auto aspect-square max-h-[240px]">
                  <PieChart>
                    <ChartTooltip content={<ChartTooltipContent hideLabel />} />
                    <Pie data={osData} dataKey="value" nameKey="label" label />
                  </PieChart>
                </ChartContainer>
              </CardContent>
            </Card>
          </div>

          <Card className="border-slate-200">
            <CardHeader>
              <CardTitle className="text-lg font-semibold text-neutral-900">Tickets recentes</CardTitle>
              <CardDescription className="text-neutral-600">Chamados em aberto para a empresa selecionada.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              {openTickets.length === 0 ? (
                <p className="rounded-xl border border-dashed border-slate-200 p-6 text-sm text-neutral-500">
                  Nenhum chamado aberto no período selecionado.
                </p>
              ) : (
                <div className="space-y-3">
                  {openTickets.map((ticket) => (
                    <Link
                      key={ticket.id}
                      href={`/tickets/${ticket.id}`}
                      className="group flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm shadow-sm transition hover:-translate-y-0.5 hover:border-slate-300 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-300 focus-visible:ring-offset-2"
                    >
                      <div className="min-w-0 flex-1">
                        <p className="truncate text-sm font-semibold text-neutral-900">
                          #{ticket.reference} · {ticket.subject}
                        </p>
                        <p className="text-xs text-neutral-500">
                          Atualizado{" "}
                          {formatDistanceToNow(new Date(ticket.updatedAt), {
                            addSuffix: true,
                            locale: ptBR,
                          })}
                        </p>
                      </div>
                      <div className="flex items-center gap-2">
                        <TicketPriorityPill
                          priority={ticket.priority as TicketPriority}
                          className="h-8 rounded-full px-3 text-xs"
                        />
                        <TicketStatusBadge
                          status={ticket.status as TicketStatus}
                          className="h-8 px-3 text-xs font-semibold"
                        />
                      </div>
                    </Link>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </>
      )}
    </div>
  )
}
