"use client"

import { useEffect, useMemo, useState } from "react"
import { useMutation, useQuery } from "convex/react"
import { formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"
import { toast } from "sonner"

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 { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { MultiValueInput } from "@/components/ui/multi-value-input"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Skeleton } from "@/components/ui/skeleton"

const STATUS_OPTIONS = [
  { value: "investigating", label: "Investigando" },
  { value: "identified", label: "Identificado" },
  { value: "mitigated", label: "Mitigado" },
  { value: "resolved", label: "Resolvido" },
]

const SEVERITY_OPTIONS = [
  { value: "low", label: "Baixa" },
  { value: "medium", label: "Média" },
  { value: "high", label: "Alta" },
  { value: "critical", label: "Crítica" },
]

const STATUS_TONE: Record<string, { badge: string; border: string; label: string }> = {
  investigating: { badge: "bg-amber-100 text-amber-900", border: "border-amber-200", label: "Investigando" },
  identified: { badge: "bg-orange-100 text-orange-900", border: "border-orange-200", label: "Identificado" },
  mitigated: { badge: "bg-blue-100 text-blue-900", border: "border-blue-200", label: "Mitigado" },
  resolved: { badge: "bg-emerald-100 text-emerald-900", border: "border-emerald-200", label: "Resolvido" },
}

const SEVERITY_COLORS: Record<string, string> = {
  low: "bg-slate-100 text-slate-800",
  medium: "bg-amber-100 text-amber-900",
  high: "bg-orange-100 text-orange-900",
  critical: "bg-rose-100 text-rose-900",
}

type IncidentRecord = {
  _id: string
  tenantId: string
  title: string
  status: string
  severity: string
  impactSummary?: string | null
  affectedQueues: string[]
  ownerName?: string | null
  ownerEmail?: string | null
  startedAt: number
  updatedAt: number
  resolvedAt?: number | null
  timeline: Array<{
    id: string
    authorId: Id<"users">
    authorName?: string | null
    message: string
    type?: string | null
    createdAt: number
  }>
}

type IncidentWorkspaceProps = {
  autoOpenDrawer?: boolean
}

export function IncidentWorkspace({ autoOpenDrawer = false }: IncidentWorkspaceProps) {
  const { session, convexUserId, isStaff } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const canLoad = Boolean(convexUserId && isStaff)
  const incidentsRemote = useQuery(
    api.incidents.list,
    canLoad ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
  ) as IncidentRecord[] | undefined
  const createIncident = useMutation(api.incidents.createIncident)
  const updateStatus = useMutation(api.incidents.updateIncidentStatus)
  const bulkUpdateStatus = useMutation(api.incidents.bulkUpdateIncidentStatus)
  const addUpdate = useMutation(api.incidents.addIncidentUpdate)

  const incidents = useMemo(() => incidentsRemote ?? [], [incidentsRemote])
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [severityFilter, setSeverityFilter] = useState("all")
  const [selectedIds, setSelectedIds] = useState<string[]>([])
  const [selectedIncidentId, setSelectedIncidentId] = useState<string | null>(null)
  const [drawerOpen, setDrawerOpen] = useState(autoOpenDrawer)
  const [bulkStatus, setBulkStatus] = useState<string | null>(null)
  const [updateMessage, setUpdateMessage] = useState("")
  const [updateStatusSelection, setUpdateStatusSelection] = useState<string>("")
  const [isSubmittingUpdate, setIsSubmittingUpdate] = useState(false)

  useEffect(() => {
    if (!selectedIncidentId && incidents.length > 0) {
      setSelectedIncidentId(incidents[0]._id)
    }
  }, [incidents, selectedIncidentId])

  useEffect(() => {
    if (autoOpenDrawer) {
      setDrawerOpen(true)
    }
  }, [autoOpenDrawer])

  const filteredIncidents = useMemo(() => {
    return incidents.filter((incident) => {
      if (statusFilter !== "all" && incident.status !== statusFilter) return false
      if (severityFilter !== "all" && incident.severity !== severityFilter) return false
      if (searchTerm.trim().length > 0) {
        const term = searchTerm.trim().toLowerCase()
        const haystack = `${incident.title} ${incident.impactSummary ?? ""}`.toLowerCase()
        if (!haystack.includes(term)) return false
      }
      return true
    })
  }, [incidents, searchTerm, severityFilter, statusFilter])

  const stats = useMemo(() => {
    const totals: Record<string, number> = {}
    STATUS_OPTIONS.forEach((option) => {
      totals[option.value] = incidents.filter((incident) => incident.status === option.value).length
    })
    return totals
  }, [incidents])

  const selectedIncident = incidents.find((incident) => incident._id === selectedIncidentId) ?? null
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedIds(filteredIncidents.map((incident) => incident._id))
    } else {
      setSelectedIds([])
    }
  }

  const handleBulkStatus = async () => {
    if (!bulkStatus || selectedIds.length === 0 || !convexUserId) return
    try {
      await bulkUpdateStatus({
        tenantId,
        actorId: convexUserId as Id<"users">,
        incidentIds: selectedIds as Id<"incidents">[],
        status: bulkStatus,
      })
      toast.success("Status atualizado para os incidentes selecionados.")
      setSelectedIds([])
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível atualizar os incidentes.")
    }
  }

  const handleSubmitUpdate = async () => {
    if (!selectedIncident || !convexUserId || updateMessage.trim().length < 3) return
    setIsSubmittingUpdate(true)
    try {
      await addUpdate({
        tenantId,
        actorId: convexUserId as Id<"users">,
        incidentId: selectedIncident._id as Id<"incidents">,
        message: updateMessage,
        status: updateStatusSelection || undefined,
      })
      setUpdateMessage("")
      setUpdateStatusSelection("")
      toast.success("Atualização registrada.")
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível registrar a atualização.")
    } finally {
      setIsSubmittingUpdate(false)
    }
  }

  if (!isStaff) {
    return (
      <Card className="rounded-3xl border border-border/60 bg-white/90 shadow-sm">
        <CardContent className="p-6 text-sm text-neutral-600">
          Apenas membros da equipe interna podem acessar o módulo de incidentes.
        </CardContent>
      </Card>
    )
  }

  const handleCreateIncident = async (payload: NewIncidentPayload) => {
    if (!convexUserId) return
    try {
      await createIncident({
        tenantId,
        actorId: convexUserId as Id<"users">,
        title: payload.title,
        severity: payload.severity,
        impactSummary: payload.impactSummary,
        affectedQueues: payload.affectedQueues,
        initialUpdate: payload.initialUpdate,
      } as never)
      toast.success("Incidente criado com sucesso.")
      setDrawerOpen(false)
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível criar o incidente.")
    }
  }

  const handleStatusShortcut = async (status: string) => {
    if (!selectedIncident || !convexUserId) return
    try {
      await updateStatus({
        tenantId,
        actorId: convexUserId as Id<"users">,
        incidentId: selectedIncident._id as Id<"incidents">,
        status,
      })
      toast.success(`Status atualizado para ${STATUS_TONE[status]?.label ?? status}.`)
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível atualizar o status do incidente.")
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-end gap-2">
        <Button
          variant="ghost"
          onClick={() => incidentsRemote && toast.info("Dados atualizados automaticamente.")}
          className="text-sm"
        >
          Atualizar
        </Button>
        <Button onClick={() => setDrawerOpen(true)}>Novo incidente</Button>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {STATUS_OPTIONS.map((option) => {
          const tone = STATUS_TONE[option.value]
          const total = stats[option.value] ?? 0
          return (
            <Card
              key={option.value}
              className={cn(
                "rounded-3xl border bg-white/90 shadow-sm",
                tone?.border ?? "border-border/60"
              )}
            >
              <CardHeader className="flex flex-row items-center justify-between space-y-0 px-4 py-3">
                <CardTitle className="text-sm font-medium text-neutral-600">{option.label}</CardTitle>
                <Badge variant="secondary" className={tone?.badge ?? "bg-slate-100 text-slate-800"}>
                  {total}
                </Badge>
              </CardHeader>
              <CardContent className="px-4 pb-4">
                <p className="text-2xl font-semibold text-neutral-900">{total}</p>
                <p className="text-xs text-neutral-500">{total === 1 ? "Incidente" : "Incidentes"}</p>
              </CardContent>
            </Card>
          )
        })}
      </div>

      <Card className="rounded-3xl border border-border/60 bg-white/90 shadow-sm">
        <CardContent className="space-y-4 p-4">
          <div className="flex flex-wrap items-center gap-3">
            <Input
              placeholder="Buscar por título ou impacto"
              value={searchTerm}
              onChange={(event) => setSearchTerm(event.target.value)}
              className="min-w-[240px] flex-1"
            />
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-[160px]">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todos os status</SelectItem>
                {STATUS_OPTIONS.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={severityFilter} onValueChange={setSeverityFilter}>
              <SelectTrigger className="w-[160px]">
                <SelectValue placeholder="Severidade" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todas as severidades</SelectItem>
                {SEVERITY_OPTIONS.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="overflow-x-auto rounded-xl border border-slate-200">
            <table className="min-w-full divide-y divide-slate-200 text-left text-sm">
              <thead className="bg-slate-50 text-xs font-semibold uppercase tracking-wide text-neutral-500">
                <tr>
                  <th className="px-3 py-2">
                    <Checkbox
                      checked={selectedIds.length > 0 && selectedIds.length === filteredIncidents.length}
                      onCheckedChange={(checked) => handleSelectAll(Boolean(checked))}
                    />
                  </th>
                  <th className="px-3 py-2">Título</th>
                  <th className="px-3 py-2">Severidade</th>
                  <th className="px-3 py-2">Status</th>
                  <th className="px-3 py-2">Owner</th>
                  <th className="px-3 py-2">Atualizado</th>
                </tr>
              </thead>
              <tbody>
                {filteredIncidents.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="px-3 py-6 text-center text-sm text-neutral-500">
                      Nenhum incidente encontrado.
                    </td>
                  </tr>
                ) : (
                  filteredIncidents.map((incident) => {
                    const severityClass = SEVERITY_COLORS[incident.severity] ?? SEVERITY_COLORS.medium
                    const tone = STATUS_TONE[incident.status]
                    const isSelected = selectedIds.includes(incident._id)
                    return (
                      <tr
                        key={incident._id}
                        className={`cursor-pointer border-b border-slate-100 transition hover:bg-slate-50 ${selectedIncidentId === incident._id ? "bg-slate-50" : "bg-white"}`}
                        onClick={() => setSelectedIncidentId(incident._id)}
                      >
                        <td className="px-3 py-2">
                          <Checkbox
                            checked={isSelected}
                            onCheckedChange={(checked) => {
                              if (checked) {
                                setSelectedIds((prev) => (prev.includes(incident._id) ? prev : [...prev, incident._id]))
                              } else {
                                setSelectedIds((prev) => prev.filter((item) => item !== incident._id))
                              }
                            }}
                            onClick={(event) => event.stopPropagation()}
                          />
                        </td>
                        <td className="px-3 py-2 font-semibold text-neutral-900">
                          {incident.title}
                        </td>
                        <td className="px-3 py-2">
                          <Badge variant="secondary" className={severityClass}>
                            {SEVERITY_OPTIONS.find((option) => option.value === incident.severity)?.label ?? incident.severity}
                          </Badge>
                        </td>
                        <td className="px-3 py-2">
                          <Badge variant="secondary" className={tone?.badge ?? "bg-slate-100 text-slate-800"}>
                            {tone?.label ?? incident.status}
                          </Badge>
                        </td>
                        <td className="px-3 py-2 text-neutral-600">{incident.ownerName ?? incident.ownerEmail ?? "—"}</td>
                        <td className="px-3 py-2 text-xs text-neutral-500">
                          {formatDistanceToNow(incident.updatedAt, { addSuffix: true, locale: ptBR })}
                        </td>
                      </tr>
                    )
                  })
                )}
              </tbody>
            </table>
          </div>

          <div className="flex flex-wrap items-center justify-between gap-2">
            <p className="text-xs text-neutral-500">
              {filteredIncidents.length} incidente{filteredIncidents.length === 1 ? "" : "s"} listados
            </p>
            <div className="flex items-center gap-2">
              <Select value={bulkStatus ?? undefined} onValueChange={(value) => setBulkStatus(value)}>
                <SelectTrigger className="w-[200px]">
                  <SelectValue placeholder="Status em massa" />
                </SelectTrigger>
                <SelectContent>
                  {STATUS_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Button variant="outline" onClick={handleBulkStatus} disabled={!bulkStatus || selectedIds.length === 0}>
                Atualizar status
              </Button>
              {bulkStatus ? (
                <Button variant="ghost" size="sm" onClick={() => setBulkStatus(null)}>
                  Limpar
                </Button>
              ) : null}
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-6 lg:grid-cols-[1.5fr_1fr]">
      <Card className="rounded-3xl border border-border/60 bg-white/90 shadow-sm">
          <CardHeader>
            <CardTitle className="text-base font-semibold text-neutral-900">Atualizações do incidente</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {!selectedIncident ? (
              <Skeleton className="h-48 w-full rounded-2xl" />
            ) : (
              <>
                <ScrollArea className="h-64 rounded-xl border border-slate-100">
                  <div className="space-y-4 p-4">
                    {selectedIncident.timeline.length === 0 ? (
                      <p className="text-sm text-neutral-500">Nenhuma atualização registrada.</p>
                    ) : (
                      selectedIncident.timeline
                        .slice()
                        .sort((a, b) => a.createdAt - b.createdAt)
                        .map((entry) => (
                          <div key={entry.id} className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm">
                            <p className="font-semibold text-neutral-900">{entry.authorName ?? "Equipe"}</p>
                            <p className="text-xs text-neutral-500">
                              {formatDistanceToNow(entry.createdAt, { addSuffix: true, locale: ptBR })}
                            </p>
                            <p className="mt-1 text-neutral-700">{entry.message}</p>
                          </div>
                        ))
                    )}
                  </div>
                </ScrollArea>
                <div className="space-y-2">
                  <Textarea
                    value={updateMessage}
                    onChange={(event) => setUpdateMessage(event.target.value)}
                    placeholder="Compartilhe o progresso ou instruções para a equipe..."
                    rows={3}
                  />
                  <div className="flex flex-wrap items-center gap-2">
                    <Select value={updateStatusSelection || undefined} onValueChange={setUpdateStatusSelection}>
                      <SelectTrigger className="w-[220px]">
                        <SelectValue placeholder="Manter status" />
                      </SelectTrigger>
                      <SelectContent>
                        {STATUS_OPTIONS.map((option) => (
                          <SelectItem key={option.value} value={option.value}>
                            {option.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    {updateStatusSelection ? (
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="text-xs"
                        onClick={() => setUpdateStatusSelection("")}
                      >
                        Limpar
                      </Button>
                    ) : null}
                    <Button onClick={handleSubmitUpdate} disabled={isSubmittingUpdate || updateMessage.trim().length < 3}>
                      {isSubmittingUpdate ? "Registrando..." : "Registrar atualização"}
                    </Button>
                  </div>
                </div>
              </>
            )}
          </CardContent>
        </Card>
        <Card className="rounded-3xl border border-border/60 bg-white/90 shadow-sm">
          <CardHeader>
            <CardTitle className="text-base font-semibold text-neutral-900">Resumo</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4 text-sm text-neutral-600">
            {!selectedIncident ? (
              <Skeleton className="h-48 w-full rounded-2xl" />
            ) : (
              <>
                <div className="space-y-1">
                  <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Título</p>
                  <p className="font-semibold text-neutral-900">{selectedIncident.title}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Impacto</p>
                  <p>{selectedIncident.impactSummary ?? "Sem descrição."}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Filas afetadas</p>
                  <div className="flex flex-wrap gap-2">
                    {selectedIncident.affectedQueues.length === 0 ? (
                      <span className="text-neutral-500">Não informado</span>
                    ) : (
                      selectedIncident.affectedQueues.map((queue) => (
                        <Badge key={queue} variant="secondary" className="bg-slate-100 text-slate-800">
                          {queue}
                        </Badge>
                      ))
                    )}
                  </div>
                </div>
                <div className="flex flex-wrap gap-2">
                  {STATUS_OPTIONS.map((option) => (
                    <Button
                      key={option.value}
                      variant={selectedIncident.status === option.value ? "default" : "outline"}
                      size="sm"
                      onClick={() => handleStatusShortcut(option.value)}
                    >
                      {option.label}
                    </Button>
                  ))}
                </div>
              </>
            )}
          </CardContent>
        </Card>
      </div>

      <NewIncidentDrawer open={drawerOpen} onOpenChange={setDrawerOpen} onSubmit={handleCreateIncident} />
    </div>
  )
}

type NewIncidentPayload = {
  title: string
  severity: string
  impactSummary: string
  affectedQueues: string[]
  initialUpdate: string
}

function NewIncidentDrawer({
  open,
  onOpenChange,
  onSubmit,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  onSubmit: (payload: NewIncidentPayload) => Promise<void>
}) {
  const [title, setTitle] = useState("")
  const [severity, setSeverity] = useState("high")
  const [impactSummary, setImpactSummary] = useState("")
  const [affectedQueues, setAffectedQueues] = useState<string[]>([])
  const [initialUpdate, setInitialUpdate] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)

  useEffect(() => {
    if (!open) {
      setTitle("")
      setSeverity("high")
      setImpactSummary("")
      setAffectedQueues([])
      setInitialUpdate("")
      setIsSubmitting(false)
    }
  }, [open])

  const handleSubmit = async () => {
    if (title.trim().length < 3) {
      toast.error("Informe um título válido.")
      return
    }
    setIsSubmitting(true)
    try {
      await onSubmit({
        title: title.trim(),
        severity,
        impactSummary: impactSummary.trim(),
        affectedQueues,
        initialUpdate: initialUpdate.trim(),
      })
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível criar o incidente.")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="flex w-full flex-col gap-6 overflow-y-auto p-0 sm:max-w-xl">
        <div className="space-y-6 px-6 py-6">
          <SheetHeader>
            <SheetTitle>Novo incidente</SheetTitle>
            <SheetDescription>Detalhe o incidente, defina prioridade e informe o impacto inicial.</SheetDescription>
          </SheetHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <p className="text-sm font-medium text-neutral-800">Título</p>
              <Input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="Ex.: Instabilidade no e-mail corporativo" />
            </div>
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <p className="text-sm font-medium text-neutral-800">Severidade</p>
                <Select value={severity} onValueChange={setSeverity}>
                  <SelectTrigger>
                    <SelectValue placeholder="Selecione" />
                  </SelectTrigger>
                  <SelectContent>
                    {SEVERITY_OPTIONS.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium text-neutral-800">Impacto resumido</p>
              <Textarea
                value={impactSummary}
                onChange={(event) => setImpactSummary(event.target.value)}
                rows={3}
                placeholder="Descreva o efeito para clientes e equipes."
              />
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium text-neutral-800">Filas afetadas</p>
              <MultiValueInput
                placeholder="Adicionar fila"
                values={affectedQueues}
                onChange={setAffectedQueues}
              />
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium text-neutral-800">Atualização inicial</p>
              <Textarea
                value={initialUpdate}
                onChange={(event) => setInitialUpdate(event.target.value)}
                rows={4}
                placeholder="Compartilhe contexto para a equipe."
              />
            </div>
          </div>
        </div>
        <SheetFooter className="border-t border-slate-200 px-6 py-4">
          <div className="flex w-full items-center justify-end gap-2">
            <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
              Cancelar
            </Button>
            <Button onClick={handleSubmit} disabled={isSubmitting}>
              {isSubmitting ? "Criando..." : "Registrar incidente"}
            </Button>
          </div>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}
