"use client"

import { useState, useMemo } from "react"
import { useQuery } from "convex/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, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { usePersistentCompanyFilter } from "@/lib/use-company-filter"

function formatHours(ms: number) {
  const hours = ms / 3600000
  return hours.toFixed(2)
}

type HoursItem = {
  companyId: string
  name: string
  isAvulso: boolean
  internalMs: number
  externalMs: number
  totalMs: number
  contractedHoursPerMonth?: number | null
}

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

  const data = useQuery(
    api.reports.hoursByClient,
    convexUserId ? { tenantId, viewerId: convexUserId as Id<"users">, range: timeRange } : "skip"
  ) as { rangeDays: number; items: HoursItem[] } | undefined

  const items = data?.items ?? []
  const companies = useQuery(api.companies.list, convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip") as Array<{ id: Id<"companies">; name: string }> | undefined
  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase()
    let list = items
    if (companyId !== "all") list = list.filter((it) => String(it.companyId) === companyId)
    if (q) list = list.filter((it) => it.name.toLowerCase().includes(q))
    return list
  }, [items, query, companyId])

  return (
    <div className="space-y-6">
      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle>Horas por cliente</CardTitle>
          <CardDescription>Horas internas e externas registradas por empresa.</CardDescription>
          <CardAction>
            <div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center sm:justify-end">
              <Input
                placeholder="Pesquisar cliente..."
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                className="h-9 w-full min-w-56 sm:w-72"
              />
              <Select value={companyId} onValueChange={setCompanyId}>
                <SelectTrigger className="w-full min-w-56 sm:w-64">
                  <SelectValue placeholder="Todas as empresas" />
                </SelectTrigger>
                <SelectContent className="rounded-xl">
                  <SelectItem value="all">Todas as empresas</SelectItem>
                  {(companies ?? []).map((c) => (
                    <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <ToggleGroup type="single" value={timeRange} onValueChange={setTimeRange} variant="outline" className="hidden md:flex">
                <ToggleGroupItem value="90d">90 dias</ToggleGroupItem>
                <ToggleGroupItem value="30d">30 dias</ToggleGroupItem>
                <ToggleGroupItem value="7d">7 dias</ToggleGroupItem>
              </ToggleGroup>
              <Button asChild size="sm" variant="outline">
              <a href={`/api/reports/hours-by-client.csv?range=${timeRange}${query ? `&q=${encodeURIComponent(query)}` : ""}${companyId !== "all" ? `&companyId=${companyId}` : ""}`} download>
                Exportar CSV
              </a>
              </Button>
            </div>
          </CardAction>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="min-w-full table-fixed text-sm">
              <thead>
                <tr className="text-left text-xs uppercase tracking-wide text-neutral-500">
                  <th className="py-2 pr-4">Cliente</th>
                  <th className="py-2 pr-4">Avulso</th>
                  <th className="py-2 pr-4">Horas internas</th>
                  <th className="py-2 pr-4">Horas externas</th>
                  <th className="py-2 pr-4">Total</th>
                  <th className="py-2 pr-4">Contratadas/mês</th>
                  <th className="py-2 pr-4">Uso</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-200">
                {filtered.map((row) => {
                  const totalH = Number(formatHours(row.totalMs))
                  const contracted = row.contractedHoursPerMonth ?? null
                  const pct = contracted ? Math.round((totalH / contracted) * 100) : null
                  const pctBadgeVariant: "secondary" | "destructive" = pct !== null && pct >= 90 ? "destructive" : "secondary"
                  return (
                    <tr key={row.companyId}>
                      <td className="py-2 pr-4 font-medium text-neutral-900">{row.name}</td>
                      <td className="py-2 pr-4">{row.isAvulso ? "Sim" : "Não"}</td>
                      <td className="py-2 pr-4">{formatHours(row.internalMs)}</td>
                      <td className="py-2 pr-4">{formatHours(row.externalMs)}</td>
                      <td className="py-2 pr-4 font-semibold text-neutral-900">{formatHours(row.totalMs)}</td>
                      <td className="py-2 pr-4">{contracted ?? "—"}</td>
                      <td className="py-2 pr-4">
                        {pct !== null ? (
                          <Badge variant={pctBadgeVariant} className="rounded-full px-3 py-1 text-[11px] uppercase tracking-wide">
                            {pct}%
                          </Badge>
                        ) : (
                          <span className="text-neutral-500">—</span>
                        )}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
