"use client"

import { useMemo, useState } from "react"
import { useQuery } from "convex/react"
import { Building2, Plus, Search } from "lucide-react"

import { api } from "@/convex/_generated/api"
import { useAuth } from "@/lib/auth-client"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import type { Id } from "@/convex/_generated/dataModel"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { ScrollArea } from "@/components/ui/scroll-area"

import { CompanySlaDrawer } from "./company-sla-drawer"

type CompanyWithSla = {
  companyId: string
  companyName: string
  companySlug: string
  rulesCount: number
}

type Company = {
  _id: string
  name: string
  slug: string
  tenantId: string
}

export function CompanySlaManager() {
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const viewerId = convexUserId ? (convexUserId as Id<"users">) : null

  const [searchQuery, setSearchQuery] = useState("")
  const [dialogSearchQuery, setDialogSearchQuery] = useState("")
  const [selectedCompany, setSelectedCompany] = useState<{ id: string; name: string } | null>(null)
  const [addDialogOpen, setAddDialogOpen] = useState(false)

  // Empresas que já possuem SLA customizado
  const companiesWithSla = useQuery(
    api.companySlas.listCompaniesWithCustomSla,
    viewerId ? { tenantId, viewerId } : "skip"
  ) as CompanyWithSla[] | undefined

  // Todas as empresas (para o dialog de adicionar)
  const allCompanies = useQuery(
    api.companies.list,
    viewerId ? { tenantId, viewerId } : "skip"
  ) as Company[] | undefined

  const filteredCompaniesWithSla = useMemo(() => {
    if (!companiesWithSla) return []
    if (!searchQuery.trim()) return companiesWithSla
    const query = searchQuery.toLowerCase()
    return companiesWithSla.filter(
      (c) => c.companyName.toLowerCase().includes(query) || c.companySlug.toLowerCase().includes(query)
    )
  }, [companiesWithSla, searchQuery])

  // Empresas disponíveis para adicionar (que ainda não têm SLA customizado)
  const availableCompanies = useMemo(() => {
    if (!allCompanies || !companiesWithSla) return []
    const existingIds = new Set(companiesWithSla.map((c) => c.companyId))
    return allCompanies.filter((c) => !existingIds.has(c._id))
  }, [allCompanies, companiesWithSla])

  // Filtra empresas disponíveis pelo termo de busca no dialog
  const filteredAvailableCompanies = useMemo(() => {
    if (!dialogSearchQuery.trim()) return availableCompanies
    const query = dialogSearchQuery.toLowerCase()
    return availableCompanies.filter(
      (c) => c.name.toLowerCase().includes(query) || c.slug.toLowerCase().includes(query)
    )
  }, [availableCompanies, dialogSearchQuery])

  const handleSelectCompanyToAdd = (company: Company) => {
    setAddDialogOpen(false)
    setDialogSearchQuery("")
    setSelectedCompany({ id: company._id, name: company.name })
  }

  return (
    <>
      <Card className="border-slate-200">
        <CardHeader>
          <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
            <div>
              <CardTitle className="flex items-center gap-2 text-lg font-semibold text-neutral-900">
                <Building2 className="size-5" />
                SLA por empresa
              </CardTitle>
              <CardDescription className="mt-1">
                Configure políticas de SLA específicas por cliente. Estas regras têm prioridade sobre as regras por categoria.
              </CardDescription>
            </div>
            <Button
              size="sm"
              onClick={() => setAddDialogOpen(true)}
              disabled={!viewerId || availableCompanies.length === 0}
              className="gap-2 shrink-0"
            >
              <Plus className="size-4" />
              Adicionar empresa
            </Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {companiesWithSla === undefined ? (
            <div className="space-y-2">
              {Array.from({ length: 3 }).map((_, index) => (
                <Skeleton key={`company-sla-skeleton-${index}`} className="h-16 rounded-xl" />
              ))}
            </div>
          ) : companiesWithSla.length === 0 ? (
            <div className="rounded-xl border border-dashed border-slate-300 bg-slate-50/80 p-6 text-center">
              <Building2 className="mx-auto size-8 text-slate-400" />
              <p className="mt-2 text-sm font-medium text-neutral-700">Nenhuma empresa com SLA personalizado</p>
              <p className="mt-1 text-xs text-neutral-500">
                Clique em &quot;Adicionar empresa&quot; para configurar SLA específico para um cliente.
              </p>
            </div>
          ) : (
            <>
              {companiesWithSla.length > 5 && (
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-neutral-400" />
                  <Input
                    placeholder="Buscar empresa..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-9"
                  />
                </div>
              )}
              <div className="space-y-3">
                {filteredCompaniesWithSla.map((company) => (
                  <div
                    key={company.companyId}
                    className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-200 bg-white px-4 py-3"
                  >
                    <div className="space-y-1">
                      <p className="text-sm font-semibold text-neutral-900">{company.companyName}</p>
                      <p className="text-xs text-neutral-500">/{company.companySlug}</p>
                    </div>
                    <div className="flex items-center gap-3">
                      <Badge variant="secondary" className="rounded-full">
                        {company.rulesCount} {company.rulesCount === 1 ? "regra" : "regras"}
                      </Badge>
                      <Button
                        size="sm"
                        variant="secondary"
                        onClick={() => setSelectedCompany({ id: company.companyId, name: company.companyName })}
                        disabled={!viewerId}
                      >
                        Editar SLA
                      </Button>
                    </div>
                  </div>
                ))}
                {filteredCompaniesWithSla.length === 0 && searchQuery && (
                  <p className="py-4 text-center text-sm text-neutral-500">
                    Nenhuma empresa encontrada para &quot;{searchQuery}&quot;
                  </p>
                )}
              </div>
            </>
          )}
        </CardContent>
      </Card>

      {/* Dialog para adicionar nova empresa */}
      <Dialog open={addDialogOpen} onOpenChange={(open) => {
        setAddDialogOpen(open)
        if (!open) setDialogSearchQuery("")
      }}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Adicionar SLA por empresa</DialogTitle>
            <DialogDescription>
              Selecione uma empresa para configurar políticas de SLA personalizadas.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-neutral-400" />
              <Input
                placeholder="Buscar empresa..."
                value={dialogSearchQuery}
                onChange={(e) => setDialogSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>
            <ScrollArea className="h-[280px] rounded-lg border border-slate-200">
              {filteredAvailableCompanies.length === 0 ? (
                <div className="flex h-full items-center justify-center p-6">
                  <p className="text-sm text-neutral-500">Nenhuma empresa disponível.</p>
                </div>
              ) : (
                <div className="p-1">
                  {filteredAvailableCompanies.map((company) => (
                    <button
                      key={company._id}
                      type="button"
                      onClick={() => handleSelectCompanyToAdd(company)}
                      className="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition-colors hover:bg-slate-100"
                    >
                      <Building2 className="size-4 shrink-0 text-neutral-500" />
                      <div className="min-w-0 flex-1">
                        <p className="truncate text-sm font-medium text-neutral-900">{company.name}</p>
                        <p className="truncate text-xs text-neutral-500">/{company.slug}</p>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </ScrollArea>
          </div>
        </DialogContent>
      </Dialog>

      <CompanySlaDrawer
        company={selectedCompany}
        tenantId={tenantId}
        viewerId={viewerId}
        onClose={() => setSelectedCompany(null)}
      />
    </>
  )
}
