"use client"

import { useMemo, useState } from "react"
import { useMutation, useQuery } from "convex/react"
import { toast } from "sonner"
import { IconAlarm, IconBolt, IconTargetArrow } 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 { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Skeleton } from "@/components/ui/skeleton"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"

type SlaPolicy = {
  id: string
  name: string
  description: string
  timeToFirstResponse: number | null
  timeToResolution: number | null
}

function formatMinutes(value: number | null) {
  if (value === null) return "—"
  if (value < 60) return `${Math.round(value)} min`
  const hours = Math.floor(value / 60)
  const minutes = Math.round(value % 60)
  if (minutes === 0) return `${hours}h`
  return `${hours}h ${minutes}min`
}

export function SlasManager() {
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID

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

  const createSla = useMutation(api.slas.create)
  const updateSla = useMutation(api.slas.update)
  const removeSla = useMutation(api.slas.remove)

  const [name, setName] = useState("")
  const [description, setDescription] = useState("")
  const [firstResponse, setFirstResponse] = useState<string>("")
  const [resolution, setResolution] = useState<string>("")
  const [saving, setSaving] = useState(false)
  const [editingSla, setEditingSla] = useState<SlaPolicy | null>(null)

  const { bestFirstResponse, bestResolution } = useMemo(() => {
    if (!slas) return { bestFirstResponse: null, bestResolution: null }

    const response = slas.reduce<number | null>((acc, sla) => {
      if (sla.timeToFirstResponse === null) return acc
      return acc === null ? sla.timeToFirstResponse : Math.min(acc, sla.timeToFirstResponse)
    }, null)

    const resolution = slas.reduce<number | null>((acc, sla) => {
      if (sla.timeToResolution === null) return acc
      return acc === null ? sla.timeToResolution : Math.min(acc, sla.timeToResolution)
    }, null)

    return { bestFirstResponse: response, bestResolution: resolution }
  }, [slas])

  const resetForm = () => {
    setName("")
    setDescription("")
    setFirstResponse("")
    setResolution("")
  }

  const parseNumber = (value: string) => {
    const parsed = Number(value)
    return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined
  }

  const handleCreate = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (!name.trim()) {
      toast.error("Informe um nome para a política")
      return
    }
    if (!convexUserId) {
      toast.error("Sessão não sincronizada com o Convex")
      return
    }
    setSaving(true)
    toast.loading("Criando SLA...", { id: "sla" })
    try {
      await createSla({
        tenantId,
        actorId: convexUserId as Id<"users">,
        name: name.trim(),
        description: description.trim() || undefined,
        timeToFirstResponse: parseNumber(firstResponse),
        timeToResolution: parseNumber(resolution),
      })
      toast.success("Política criada", { id: "sla" })
      resetForm()
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível criar a política", { id: "sla" })
    } finally {
      setSaving(false)
    }
  }

  const openEdit = (policy: SlaPolicy) => {
    setEditingSla(policy)
    setName(policy.name)
    setDescription(policy.description)
    setFirstResponse(policy.timeToFirstResponse ? String(policy.timeToFirstResponse) : "")
    setResolution(policy.timeToResolution ? String(policy.timeToResolution) : "")
  }

  const handleUpdate = async () => {
    if (!editingSla) return
    if (!name.trim()) {
      toast.error("Informe um nome para a política")
      return
    }
    if (!convexUserId) {
      toast.error("Sessão não sincronizada com o Convex")
      return
    }
    setSaving(true)
    toast.loading("Salvando alterações...", { id: "sla-edit" })
    try {
      await updateSla({
        tenantId,
        policyId: editingSla.id as Id<"slaPolicies">,
        actorId: convexUserId as Id<"users">,
        name: name.trim(),
        description: description.trim() || undefined,
        timeToFirstResponse: parseNumber(firstResponse),
        timeToResolution: parseNumber(resolution),
      })
      toast.success("Política atualizada", { id: "sla-edit" })
      setEditingSla(null)
      resetForm()
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível atualizar a política", { id: "sla-edit" })
    } finally {
      setSaving(false)
    }
  }

  const handleRemove = async (policy: SlaPolicy) => {
    const confirmed = window.confirm(`Excluir a política ${policy.name}?`)
    if (!confirmed) return
    if (!convexUserId) {
      toast.error("Sessão não sincronizada com o Convex")
      return
    }
    toast.loading("Removendo política...", { id: `sla-remove-${policy.id}` })
    try {
      await removeSla({
        tenantId,
        policyId: policy.id as Id<"slaPolicies">,
        actorId: convexUserId as Id<"users">,
      })
      toast.success("Política removida", { id: `sla-remove-${policy.id}` })
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível remover a política", { id: `sla-remove-${policy.id}` })
    }
  }

  return (
    <div className="space-y-8">
      <div className="grid gap-4 md:grid-cols-3">
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-neutral-600">
              <IconTargetArrow className="size-4" /> Políticas criadas
            </CardTitle>
            <CardDescription>Regras aplicadas às filas e tickets.</CardDescription>
          </CardHeader>
          <CardContent className="text-3xl font-semibold text-neutral-900">
            {slas ? slas.length : <Skeleton className="h-8 w-16" />}
          </CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-neutral-600">
              <IconAlarm className="size-4" /> Resposta (média)
            </CardTitle>
            <CardDescription>Tempo mínimo para primeira resposta.</CardDescription>
          </CardHeader>
          <CardContent className="text-xl font-semibold text-neutral-900">
            {slas ? formatMinutes(bestFirstResponse ?? null) : <Skeleton className="h-8 w-24" />}
          </CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-neutral-600">
              <IconBolt className="size-4" /> Resolução (média)
            </CardTitle>
            <CardDescription>Alvo para encerrar chamados.</CardDescription>
          </CardHeader>
          <CardContent className="text-xl font-semibold text-neutral-900">
            {slas ? formatMinutes(bestResolution ?? null) : <Skeleton className="h-8 w-24" />}
          </CardContent>
        </Card>
      </div>

      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">Nova política de SLA</CardTitle>
          <CardDescription>Defina metas de resposta e resolução para garantir previsibilidade no atendimento.</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleCreate} className="grid gap-4 md:grid-cols-[minmax(0,320px)_minmax(0,1fr)]">
            <div className="space-y-3">
              <div className="space-y-2">
                <Label htmlFor="sla-name">Nome da política</Label>
                <Input
                  id="sla-name"
                  placeholder="Ex.: Resposta prioritária"
                  value={name}
                  onChange={(event) => setName(event.target.value)}
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="sla-first-response">Primeira resposta (minutos)</Label>
                <Input
                  id="sla-first-response"
                  type="number"
                  min={1}
                  value={firstResponse}
                  onChange={(event) => setFirstResponse(event.target.value)}
                  placeholder="Opcional"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="sla-resolution">Resolução (minutos)</Label>
                <Input
                  id="sla-resolution"
                  type="number"
                  min={1}
                  value={resolution}
                  onChange={(event) => setResolution(event.target.value)}
                  placeholder="Opcional"
                />
              </div>
            </div>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="sla-description">Descrição</Label>
                <textarea
                  id="sla-description"
                  className="min-h-[120px] w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-neutral-700 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/10"
                  placeholder="Como esta política será aplicada"
                  value={description}
                  onChange={(event) => setDescription(event.target.value)}
                />
              </div>
              <div className="flex justify-end">
                <Button type="submit" disabled={saving}>
                  Criar política
                </Button>
              </div>
            </div>
          </form>
        </CardContent>
      </Card>

      <div className="space-y-4">
        {slas === undefined ? (
          <div className="space-y-4">
            {Array.from({ length: 3 }).map((_, index) => (
              <Skeleton key={index} className="h-32 rounded-2xl" />
            ))}
          </div>
        ) : slas.length === 0 ? (
          <Card className="border-dashed border-slate-300 bg-slate-50/80">
            <CardHeader>
              <CardTitle className="text-lg font-semibold text-neutral-900">Nenhuma política cadastrada</CardTitle>
              <CardDescription className="text-neutral-600">
                Crie SLAs para monitorar o tempo de resposta e resolução dos seus chamados.
              </CardDescription>
            </CardHeader>
          </Card>
        ) : (
          slas.map((policy) => (
            <Card key={policy.id} className="border-slate-200">
              <CardHeader>
                <div className="flex items-start justify-between gap-4">
                  <div className="space-y-2">
                    <CardTitle className="text-xl font-semibold text-neutral-900">{policy.name}</CardTitle>
                    {policy.description ? (
                      <CardDescription className="text-neutral-600">{policy.description}</CardDescription>
                    ) : null}
                  </div>
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" onClick={() => openEdit(policy)}>
                      Editar
                    </Button>
                    <Button variant="destructive" size="sm" onClick={() => handleRemove(policy)}>
                      Excluir
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <dl className="grid gap-4 md:grid-cols-2">
                  <div>
                    <dt className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Primeira resposta</dt>
                    <dd className="text-lg font-semibold text-neutral-900">{formatMinutes(policy.timeToFirstResponse)}</dd>
                  </div>
                  <div>
                    <dt className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Resolução</dt>
                    <dd className="text-lg font-semibold text-neutral-900">{formatMinutes(policy.timeToResolution)}</dd>
                  </div>
                </dl>
              </CardContent>
            </Card>
          ))
        )}
      </div>

      <Dialog open={Boolean(editingSla)} onOpenChange={(value) => (!value ? setEditingSla(null) : null)}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Editar política de SLA</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="space-y-2">
              <Label htmlFor="edit-sla-name">Nome</Label>
              <Input
                id="edit-sla-name"
                value={name}
                onChange={(event) => setName(event.target.value)}
                autoFocus
              />
            </div>
            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="edit-sla-first">Primeira resposta (minutos)</Label>
                <Input
                  id="edit-sla-first"
                  type="number"
                  min={1}
                  value={firstResponse}
                  onChange={(event) => setFirstResponse(event.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="edit-sla-resolution">Resolução (minutos)</Label>
                <Input
                  id="edit-sla-resolution"
                  type="number"
                  min={1}
                  value={resolution}
                  onChange={(event) => setResolution(event.target.value)}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-sla-description">Descrição</Label>
              <textarea
                id="edit-sla-description"
                className="min-h-[120px] w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm text-neutral-700 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-900/10"
                value={description}
                onChange={(event) => setDescription(event.target.value)}
              />
            </div>
          </div>
          <DialogFooter className="gap-2">
            <Button variant="outline" onClick={() => setEditingSla(null)}>
              Cancelar
            </Button>
            <Button onClick={handleUpdate} disabled={saving}>
              Salvar alterações
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
