"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { toast } from "sonner";
import {
  Search,
  SlidersHorizontal,
  Plus,
  UploadCloud,
  Eye,
  SquarePen,
  Trash2,
  Tags,
  FolderPlus,
  ArrowUp,
  ArrowDown,
  MoreHorizontal,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  Download,
  List as ListIcon,
  ShieldOff,
  User,
} from "lucide-react";

import { Breadcrumb } from "@/shared/components/ui/breadcrumb";
import { Card, CardContent } from "@/shared/components/ui/card";
import { Badge } from "@/shared/components/ui/badge";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import { Checkbox } from "@/shared/components/ui/checkbox";
import { Skeleton } from "@/shared/components/ui/skeleton";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/shared/components/ui/table";
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle, DrawerFooter, DrawerClose, DrawerTrigger } from "@/shared/components/ui/drawer";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/shared/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogCancel,
  AlertDialogAction,
} from "@/shared/components/ui/alert-dialog";
import { useDebouncedValue } from "@/shared/hooks/use-debounced-value";
import { buildPageNumbers } from "@/shared/utils/build-page-numbers";
import { getAvatarColor, getInitials } from "../utils/get-avatar-color";
import { ContactFormModal } from "../components/contact-form-modal";
import { AddTagsModal } from "../components/add-tags-modal";
import { getAllContactListsAction } from "../actions/get-all-contact-lists-action";
import { getContactsPaginatedAction } from "../actions/get-contacts-paginated-action";
import { bulkUpdateContactsAction } from "../actions/bulk-update-contacts-action";
import { useImportContactsModal } from "../context/import-contacts-modal-context";

type ContactStatus = "ACTIVE" | "UNSUBSCRIBED" | "BOUNCED";
type SortBy = "name" | "email" | "createdAt";
type SortDir = "asc" | "desc";

interface ContactRow {
  id: string;
  email: string;
  name: string | null;
  phone: string | null;
  tags: string[];
  source: "MANUAL" | "IMPORT" | "API";
  status: ContactStatus;
  createdAt: string;
  listMemberships: { list: { id: string; name: string } }[];
}

interface ContactsResponse {
  items: ContactRow[];
  total: number;
  page: number;
  pageSize: number;
}

interface ContactListOption {
  id: string;
  name: string;
  _count: { memberships: number };
}

const STATUS_LABEL: Record<ContactStatus, string> = {
  ACTIVE: "Ativo",
  UNSUBSCRIBED: "Descadastrado",
  BOUNCED: "Inválido",
};

const STATUS_BADGE_STYLE: Record<ContactStatus, string> = {
  ACTIVE: "border-emerald-200 text-emerald-800 bg-emerald-50",
  UNSUBSCRIBED: "border-zinc-300 text-zinc-700 bg-zinc-100",
  BOUNCED: "border-rose-200 text-rose-800 bg-rose-50",
};

const SOURCE_LABEL: Record<ContactRow["source"], string> = {
  MANUAL: "Manual",
  IMPORT: "Importação",
  API: "API",
};

const PAGE_SIZE_OPTIONS = [20, 50, 100];

interface ContactsListPageViewProps {
  initialListId?: string;
  initialStatus?: ContactStatus;
}

export function ContactsListPageView({ initialListId, initialStatus }: ContactsListPageViewProps = {}) {
  const { openImportModal } = useImportContactsModal();
  const [items, setItems] = useState<ContactRow[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [sortBy, setSortBy] = useState<SortBy>("createdAt");
  const [sortDir, setSortDir] = useState<SortDir>("desc");
  const [isLoading, setIsLoading] = useState(true);

  const [searchInput, setSearchInput] = useState("");
  const search = useDebouncedValue(searchInput, 400);
  const [status, setStatus] = useState<ContactStatus | "">(initialStatus ?? "");
  const [tag, setTag] = useState("");
  const [listId, setListId] = useState(initialListId ?? "");
  const [openedWithin30, setOpenedWithin30] = useState(false);
  const [subscribedWithin30, setSubscribedWithin30] = useState(false);

  const [lists, setLists] = useState<ContactListOption[]>([]);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  const [formModal, setFormModal] = useState<{ open: boolean; contact?: ContactRow }>({ open: false });
  const [deleteTarget, setDeleteTarget] = useState<{ ids: string[] } | null>(null);
  const [tagModalIds, setTagModalIds] = useState<string[] | null>(null);
  const [tagModalValue, setTagModalValue] = useState("");
  const [listModalIds, setListModalIds] = useState<string[] | null>(null);
  const [listModalValue, setListModalValue] = useState("");

  useEffect(() => {
    getAllContactListsAction()
      .then((data) => setLists(data.lists ?? []))
      .catch(() => {});
  }, []);

  useEffect(() => {
    setPage(1);
  }, [search, status, tag, listId, openedWithin30, subscribedWithin30, sortBy, sortDir, pageSize]);

  const load = useCallback(() => {
    setIsLoading(true);

    getContactsPaginatedAction({
      page,
      pageSize,
      sortBy,
      sortDir,
      search: search || undefined,
      tag: tag || undefined,
      listId: listId || undefined,
      status: status || undefined,
      openedWithinDays: openedWithin30 ? 30 : undefined,
      subscribedWithinDays: subscribedWithin30 ? 30 : undefined,
    })
      .then((data: ContactsResponse) => {
        setItems(data.items ?? []);
        setTotal(data.total ?? 0);
      })
      .catch(() => {})
      .finally(() => setIsLoading(false));
  }, [page, pageSize, sortBy, sortDir, search, status, tag, listId, openedWithin30, subscribedWithin30]);

  useEffect(() => {
    load();
  }, [load]);

  const totalPages = Math.max(1, Math.ceil(total / pageSize));
  const pageNumbers = useMemo(() => buildPageNumbers(page, totalPages), [page, totalPages]);

  function toggleSort(column: SortBy) {
    if (sortBy === column) {
      setSortDir((prev) => (prev === "asc" ? "desc" : "asc"));
    } else {
      setSortBy(column);
      setSortDir("asc");
    }
  }

  function toggleSelected(id: string) {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  function toggleSelectAll() {
    setSelectedIds((prev) => (prev.size === items.length ? new Set() : new Set(items.map((i) => i.id))));
  }

  async function handleBulkDelete(ids: string[]) {
    try {
      await bulkUpdateContactsAction({ ids, action: "delete" });
      toast.success(`${ids.length} contato(s) excluído(s).`);
      setSelectedIds(new Set());
      setDeleteTarget(null);
      load();
    } catch {
      toast.error("Não foi possível excluir os contatos selecionados.");
    }
  }

  async function handleAddTags(ids: string[], tags: string[]) {
    try {
      await bulkUpdateContactsAction({ ids, action: "addTags", payload: { tags } });
      toast.success("Tags adicionadas.");
      setTagModalIds(null);
      setTagModalValue("");
      setSelectedIds(new Set());
      load();
    } catch {
      toast.error("Não foi possível adicionar as tags.");
    }
  }

  async function handleAddToList(ids: string[], targetListId: string) {
    try {
      await bulkUpdateContactsAction({ ids, action: "addToList", payload: { listId: targetListId } });
      toast.success("Contato(s) adicionado(s) à lista.");
      setListModalIds(null);
      setListModalValue("");
      setSelectedIds(new Set());
      load();
    } catch {
      toast.error("Não foi possível adicionar à lista.");
    }
  }

  const activeAdvancedFilters = [
    status && { key: "status", label: `Status: ${STATUS_LABEL[status]}`, clear: () => setStatus("") },
    tag && { key: "tag", label: `Tag: ${tag}`, clear: () => setTag("") },
    listId && { key: "list", label: `Lista: ${lists.find((l) => l.id === listId)?.name ?? listId}`, clear: () => setListId("") },
  ].filter((f): f is { key: string; label: string; clear: () => void } => !!f);

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <Breadcrumb
          className="text-sm"
          items={[
            { label: "Início", href: "/" },
            { label: "Contatos" },
          ]}
        />
        <div className="flex items-center gap-2">

          {/* 
            <DropdownMenu>
                        <DropdownMenuTrigger render={<Button variant="outline" className="h-9" />}>
                          <MoreHorizontal className="w-4 h-4" />
                          Mais Ações
                        </DropdownMenuTrigger>
                        <DropdownMenuContent>
                          <DropdownMenuItem render={<Link href="/contacts/lists" />}>
                            <ListIcon className="w-4 h-4" />
                            Listas
                          </DropdownMenuItem>
                          <DropdownMenuItem render={<Link href="/contacts/export" />}>
                            <Download className="w-4 h-4" />
                            Exportar
                          </DropdownMenuItem>
                          <DropdownMenuItem render={<Link href="/contacts/suppression" />}>
                            <ShieldOff className="w-4 h-4" />
                            Supressão
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
          */}
         
          <Button variant="outline" className="h-9" onClick={() => openImportModal()}>
            <UploadCloud className="w-4 h-4" />
            Importar
          </Button>
          <Button onClick={() => setFormModal({ open: true })} className="h-9">
            <Plus className="w-4 h-4" />
            Adicionar contato
          </Button>
        </div>
      </div>

      <div className="text-center space-y-4 py-2">
        <h1 className="text-2xl sm:text-[26px] font-extrabold text-zinc-900 leading-snug">
          Encontre os contatos que você precisa
        </h1>

        <div className="relative max-w-xl mx-auto">
          <Search className="w-4 h-4 text-zinc-400 absolute left-4 top-1/2 -translate-y-1/2 pointer-events-none" />
          <Input
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            placeholder="Pesquisar contatos"
            className="pl-10 h-11 rounded-full"
          />
        </div>

        <div className="flex flex-wrap items-center justify-center gap-2">
          <Drawer>
            <DrawerTrigger
              render={
                <Button variant="outline" size="sm" className="shrink-0">
                  <SlidersHorizontal className="w-4 h-4" />
                  Pesquisa avançada
                  {activeAdvancedFilters.length > 0 && (
                    <Badge className="ml-1.5 bg-indigo-600">{activeAdvancedFilters.length}</Badge>
                  )}
                </Button>
              }
            />
            <DrawerContent>
              <DrawerHeader>
                <DrawerTitle>Pesquisa avançada</DrawerTitle>
              </DrawerHeader>
              <div className="space-y-4 text-left">
                <div className="space-y-1.5">
                  <Label>Status</Label>
                  <select
                    value={status}
                    onChange={(e) => setStatus(e.target.value as ContactStatus | "")}
                    className="w-full h-9 rounded-lg border border-zinc-300 bg-white px-2.5 text-xs"
                  >
                    <option value="">Todos</option>
                    <option value="ACTIVE">Ativo</option>
                    <option value="UNSUBSCRIBED">Descadastrado</option>
                    <option value="BOUNCED">Inválido</option>
                  </select>
                </div>
                <div className="space-y-1.5">
                  <Label>Lista</Label>
                  <select
                    value={listId}
                    onChange={(e) => setListId(e.target.value)}
                    className="w-full h-9 rounded-lg border border-zinc-300 bg-white px-2.5 text-xs"
                  >
                    <option value="">Todas</option>
                    {lists.map((list) => (
                      <option key={list.id} value={list.id}>
                        {list.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="space-y-1.5">
                  <Label>Tag</Label>
                  <Input value={tag} onChange={(e) => setTag(e.target.value)} placeholder="Nome da tag" className="h-9" />
                </div>
              </div>
              <DrawerFooter>
                <DrawerClose render={<Button variant="outline" />}>Fechar</DrawerClose>
              </DrawerFooter>
            </DrawerContent>
          </Drawer>

          <Button
            type="button"
            variant={openedWithin30 ? "default" : "outline"}
            size="sm"
            onClick={() => setOpenedWithin30((v) => !v)}
            className="shrink-0"
          >
            Abriu um e-mail — últimos 30 dias
          </Button>
          <Button
            type="button"
            variant={subscribedWithin30 ? "default" : "outline"}
            size="sm"
            onClick={() => setSubscribedWithin30((v) => !v)}
            className="shrink-0"
          >
            Inscrito nos últimos 30 dias
          </Button>

          {activeAdvancedFilters.map((filter) => (
            <Badge key={filter.key} variant="outline" className="gap-1.5 border-indigo-200 text-indigo-700 bg-indigo-50">
              {filter.label}
              <button type="button" onClick={filter.clear} className="hover:text-indigo-900">
                ×
              </button>
            </Badge>
          ))}
        </div>
      </div>

      <div>
        <Button type="button" variant="outline" size="sm" onClick={toggleSelectAll} disabled={items.length === 0} className="shrink-0">
          Editar tudo
        </Button>
      </div>

      {selectedIds.size > 0 && (
        <div className="flex items-center justify-between gap-3 bg-indigo-50 border border-indigo-100 rounded-xl px-4 py-2.5">
          <span className="text-xs font-bold text-indigo-900">{selectedIds.size} selecionado(s)</span>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={() => setTagModalIds([...selectedIds])}>
              <Tags className="w-3.5 h-3.5 mr-1.5" />
              Adicionar Tags
            </Button>
            <Button variant="outline" size="sm" onClick={() => setListModalIds([...selectedIds])}>
              <FolderPlus className="w-3.5 h-3.5 mr-1.5" />
              Adicionar à Lista
            </Button>
            <Button variant="destructive" size="sm" onClick={() => setDeleteTarget({ ids: [...selectedIds] })}>
              <Trash2 className="w-3.5 h-3.5 mr-1.5" />
              Excluir
            </Button>
          </div>
        </div>
      )}

      <Card className="bg-white border border-zinc-200/80 rounded-2xl shadow-xs overflow-hidden">
        <CardContent className="p-0">
          <div className="overflow-x-auto w-full">
            <Table className="w-full text-left text-xs">
              <TableHeader className="bg-zinc-50 border-b border-zinc-200">
                <TableRow className="hover:bg-transparent border-zinc-200">
                  <TableHead className="w-10 py-3.5 px-4">
                    <Checkbox checked={items.length > 0 && selectedIds.size === items.length} onCheckedChange={toggleSelectAll} />
                  </TableHead>
                  <TableHead className="text-xs font-bold uppercase text-zinc-700 py-3.5 px-4">
                    <button type="button" onClick={() => toggleSort("name")} className="inline-flex items-center gap-1 cursor-pointer">
                      Nome completo
                      {sortBy === "name" && (sortDir === "asc" ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />)}
                    </button>
                  </TableHead>
                  <TableHead className="text-xs font-bold uppercase text-zinc-700 py-3.5 px-4">
                    <button type="button" onClick={() => toggleSort("email")} className="inline-flex items-center gap-1 cursor-pointer">
                      E-mail
                      {sortBy === "email" && (sortDir === "asc" ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />)}
                    </button>
                  </TableHead>
                  <TableHead className="text-xs font-bold uppercase text-zinc-700 py-3.5 px-4">
                    <button type="button" onClick={() => toggleSort("createdAt")} className="inline-flex items-center gap-1 cursor-pointer">
                      Data de Criação
                      {sortBy === "createdAt" && (sortDir === "asc" ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />)}
                    </button>
                  </TableHead>
                  <TableHead className="text-xs font-bold uppercase text-zinc-700 py-3.5 px-4">Telefone</TableHead>
                  <TableHead className="text-xs font-bold uppercase text-zinc-700 py-3.5 px-4">Tags</TableHead>
                  <TableHead className="text-xs font-bold uppercase text-zinc-700 py-3.5 px-4">Conta</TableHead>
                  <TableHead className="text-xs font-bold uppercase text-zinc-700 text-right w-16 py-3.5 px-4">Ações</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  Array.from({ length: 8 }).map((_, i) => (
                    <TableRow key={i} className="border-b border-zinc-100">
                      {Array.from({ length: 8 }).map((__, j) => (
                        <TableCell key={j} className="py-3.5 px-4">
                          <Skeleton className="h-4 w-full" />
                        </TableCell>
                      ))}
                    </TableRow>
                  ))
                ) : items.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center py-10 text-zinc-500">
                      Nenhum contato encontrado com esses filtros.
                    </TableCell>
                  </TableRow>
                ) : (
                  items.map((contact) => (
                    <TableRow key={contact.id} className="border-b border-zinc-100 hover:bg-zinc-50/80">
                      <TableCell className="py-3.5 px-4">
                        <Checkbox checked={selectedIds.has(contact.id)} onCheckedChange={() => toggleSelected(contact.id)} />
                      </TableCell>
                      <TableCell className="py-3.5 px-4">
                        <Link href={`/contacts/${contact.id}`} className="flex items-center gap-2.5 group">
                          {contact.name ? (
                            <span
                              className={`w-7 h-7 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0 ${getAvatarColor(contact.id)}`}
                            >
                              {getInitials(contact.name)}
                            </span>
                          ) : (
                            <span className="w-7 h-7 rounded-full flex items-center justify-center bg-zinc-100 text-zinc-400 shrink-0">
                              <User className="w-3.5 h-3.5" />
                            </span>
                          )}
                          <span className="font-semibold text-zinc-900 group-hover:text-indigo-600 transition-colors">
                            {contact.name || "Unknown"}
                          </span>
                        </Link>
                      </TableCell>
                      <TableCell className="font-mono text-zinc-600 py-3.5 px-4">{contact.email}</TableCell>
                      <TableCell className="text-zinc-600 py-3.5 px-4">
                        {new Date(contact.createdAt).toLocaleDateString("pt-BR")}
                      </TableCell>
                      <TableCell className="text-zinc-600 py-3.5 px-4">{contact.phone || "—"}</TableCell>
                      <TableCell className="py-3.5 px-4">
                        {contact.tags && contact.tags.length > 0 ? (
                          <div className="flex flex-wrap items-center gap-1 max-w-[220px]">
                            {contact.tags.map((t) => (
                              <Badge
                                key={t}
                                variant="outline"
                                onClick={() => setTag(t)}
                                title={`Filtrar por tag: ${t}`}
                                className="border-indigo-200 text-indigo-700 bg-indigo-50/80 hover:bg-indigo-100 transition-colors cursor-pointer text-[11px] font-medium py-0.5 px-2 rounded-md"
                              >
                                {t}
                              </Badge>
                            ))}
                          </div>
                        ) : (
                          <span className="text-zinc-400">—</span>
                        )}
                      </TableCell>
                      <TableCell className="py-3.5 px-4">
                        <div className="flex flex-wrap items-center gap-1.5">
                          <Badge variant="outline" className="border-zinc-200 text-zinc-700 bg-zinc-50">
                            {SOURCE_LABEL[contact.source]}
                          </Badge>
                          <Badge variant="outline" className={STATUS_BADGE_STYLE[contact.status]}>
                            {STATUS_LABEL[contact.status]}
                          </Badge>
                        </div>
                      </TableCell>
                      <TableCell className="text-right py-3.5 px-4">
                        <div className="flex items-center justify-end gap-1.5">
                          <Link
                            href={`/contacts/${contact.id}`}
                            className="inline-flex items-center gap-1.5 h-8 px-3 rounded-lg border border-zinc-300 text-xs font-semibold text-zinc-700 hover:bg-zinc-100 transition-colors"
                          >
                            <Eye className="w-3.5 h-3.5" />
                            Visualizar
                          </Link>
                          <DropdownMenu>
                            <DropdownMenuTrigger
                              render={
                                <button
                                  type="button"
                                  aria-label="Mais ações"
                                  className="h-8 w-8 shrink-0 inline-flex items-center justify-center rounded-lg border border-zinc-300 text-zinc-500 hover:bg-zinc-100 transition-colors"
                                >
                                  <ChevronDown className="w-3.5 h-3.5" />
                                </button>
                              }
                            />
                            <DropdownMenuContent>
                              <DropdownMenuItem onClick={() => setFormModal({ open: true, contact })}>
                                <SquarePen className="w-3.5 h-3.5" />
                                Editar
                              </DropdownMenuItem>
                              <DropdownMenuItem onClick={() => setTagModalIds([contact.id])}>
                                <Tags className="w-3.5 h-3.5" />
                                Adicionar Tag
                              </DropdownMenuItem>
                              <DropdownMenuItem onClick={() => setListModalIds([contact.id])}>
                                <FolderPlus className="w-3.5 h-3.5" />
                                Adicionar à Lista
                              </DropdownMenuItem>
                              <DropdownMenuItem variant="destructive" onClick={() => setDeleteTarget({ ids: [contact.id] })}>
                                <Trash2 className="w-3.5 h-3.5" />
                                Excluir
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {!isLoading && items.length > 0 && (
        <div className="flex flex-col sm:flex-row items-center justify-between gap-3 pt-1">
          <div className="flex items-center gap-2 text-xs text-zinc-500">
            <span>Linhas:</span>
            <select
              value={pageSize}
              onChange={(e) => setPageSize(Number(e.target.value))}
              className="h-8 rounded-lg border border-zinc-300 bg-white px-2 text-xs"
            >
              {PAGE_SIZE_OPTIONS.map((size) => (
                <option key={size} value={size}>
                  {size}
                </option>
              ))}
            </select>
          </div>

          <div className="flex items-center gap-1.5">
            <button
              type="button"
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page <= 1}
              aria-label="Página anterior"
              className="h-8 w-8 inline-flex items-center justify-center rounded-lg border border-zinc-300 text-zinc-700 hover:bg-zinc-100 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
            >
              <ChevronLeft className="w-4 h-4" />
            </button>
            {pageNumbers.map((p, idx) =>
              p === "..." ? (
                <span key={`ellipsis-${idx}`} className="text-xs text-zinc-400 px-1">
                  ...
                </span>
              ) : (
                <button
                  key={p}
                  type="button"
                  onClick={() => setPage(p)}
                  className={`text-xs font-semibold h-8 w-8 rounded-lg cursor-pointer ${
                    p === page ? "bg-indigo-600 text-white" : "text-zinc-700 hover:bg-zinc-100"
                  }`}
                >
                  {p}
                </button>
              )
            )}
            <button
              type="button"
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              disabled={page >= totalPages}
              aria-label="Próxima página"
              className="h-8 w-8 inline-flex items-center justify-center rounded-lg border border-zinc-300 text-zinc-700 hover:bg-zinc-100 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
            >
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>

          <div className="flex items-center gap-1.5 text-xs text-zinc-500">
            <span>Ir para a página</span>
            <Input
              type="number"
              min={1}
              max={totalPages}
              className="h-8 w-16 px-2"
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  const value = Number((e.target as HTMLInputElement).value);
                  if (value >= 1 && value <= totalPages) setPage(value);
                }
              }}
            />
          </div>
        </div>
      )}

      <ContactFormModal
        open={formModal.open}
        onOpenChange={(open) => setFormModal({ open })}
        lists={lists}
        initialContact={
          formModal.contact
            ? {
                id: formModal.contact.id,
                email: formModal.contact.email,
                name: formModal.contact.name,
                phone: formModal.contact.phone,
                tags: formModal.contact.tags,
                listIds: formModal.contact.listMemberships.map((m) => m.list.id),
              }
            : undefined
        }
        onSaved={load}
      />

      <AddTagsModal
        open={tagModalIds !== null}
        onOpenChange={(open) => !open && setTagModalIds(null)}
        targetContactIds={tagModalIds}
        onTagsAdded={async (ids, tags) => {
          await handleAddTags(ids, tags);
        }}
      />

      <Dialog open={listModalIds !== null} onOpenChange={(open) => !open && setListModalIds(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Adicionar à Lista</DialogTitle>
          </DialogHeader>
          <div className="space-y-1.5">
            <Label htmlFor="bulk-list">Lista</Label>
            <select
              id="bulk-list"
              value={listModalValue}
              onChange={(e) => setListModalValue(e.target.value)}
              className="w-full h-10 rounded-lg border border-zinc-300 bg-white px-2.5 text-sm"
            >
              <option value="">Selecione uma lista</option>
              {lists.map((list) => (
                <option key={list.id} value={list.id}>
                  {list.name}
                </option>
              ))}
            </select>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setListModalIds(null)}>
              Cancelar
            </Button>
            <Button
              onClick={() => {
                if (listModalIds && listModalValue) handleAddToList(listModalIds, listModalValue);
              }}
              disabled={!listModalValue}
            >
              Adicionar
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Excluir contato(s)?</AlertDialogTitle>
            <AlertDialogDescription>Esta ação não pode ser desfeita.</AlertDialogDescription>
          </AlertDialogHeader>
          <div className="py-2 text-sm text-zinc-800 text-center">
            Deseja excluir {deleteTarget?.ids.length} contato(s)?
          </div>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setDeleteTarget(null)}>Cancelar</AlertDialogCancel>
            <AlertDialogAction variant="destructive" onClick={() => deleteTarget && handleBulkDelete(deleteTarget.ids)}>
              <Trash2 className="w-4 h-4 mr-1.5" />
              Sim, excluir
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
