"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { getSupabaseClient } from "@/lib/supabase";
import { getCompanyContext } from "@/lib/company-context";
import { Check, Copy, Eye, Plus, Search, User, MapPin, Phone, Mail, LayoutGrid, List, Trash2, AlertTriangle } from "lucide-react";
import { ClientFormModal } from "@/components/clients/client-form-modal";
import { Client } from "@/types/client";
import { PageHeader } from "@/components/ui/page-header";
import { Button } from "@/components/ui/button";
import { usePermissoes } from "@/lib/permissoes-do-usuario";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

interface ClientRow extends Client {
  // Joins for list display
  orders?: { id: string; number: number; created_at: string }[];
  quotes?: { id: string; number: number; created_at: string }[];
  is_deleted?: boolean | null;
  deleted_at?: string | null;
}

const QUICK_PLACEHOLDER_NAME = "cliente pendente";
const QUICK_PLACEHOLDER_COMPANY = "orcamento rapido";

function isQuickPlaceholderClient(client: ClientRow) {
  if (client.is_system_placeholder) return true;
  const name = (client.name || "").trim().toLowerCase();
  const company = (client.company_name || "").trim().toLowerCase();
  return name === QUICK_PLACEHOLDER_NAME && company === QUICK_PLACEHOLDER_COMPANY && client.active === false;
}

export default function ClientsPage() {
  const { pode } = usePermissoes();
  const podeMexerEmClientes = pode("clients.list.write");
  const podeOrcar = pode("quotes.write");

  const [clients, setClients] = useState<ClientRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [clientFilter, setClientFilter] = useState<"todos" | "novos" | "ativos" | "inativos" | "aguardando">("todos");
  const [profileSlug, setProfileSlug] = useState("");
  const [profileCustomDomain, setProfileCustomDomain] = useState("");
  const [profileCustomDomainVerified, setProfileCustomDomainVerified] = useState(false);
  const [copied, setCopied] = useState(false);
  const [viewMode, setViewMode] = useState<"list" | "grid">("grid");
  const [deleteModalClient, setDeleteModalClient] = useState<ClientRow | null>(null);
  const [deletingClient, setDeletingClient] = useState(false);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const origin = typeof window !== "undefined" ? window.location.origin : "https://ktalogu.com.br";
  const publicCatalogBaseUrl = (process.env.NEXT_PUBLIC_PUBLIC_CATALOG_BASE_URL || origin)
    .replace(":3002", ":3001")
    .replace(/\/\/admin\./, "//")
    .replace(/\/$/, "");

  async function fetchClients() {
    setLoading(true);
    try {
      const supabase = getSupabaseClient();
      const {
        data: { user },
      } = await supabase.auth.getUser();
      if (!user) return;
      const ctx = await getCompanyContext(supabase, user);
      const tenantIds = ctx.tenantIds?.length ? ctx.tenantIds : [user.id];

      const [{ data, error }, { data: profilesData }, { data: domainsData }] = await Promise.all([
        supabase
        .from("clients")
        .select("*, orders(id, number, created_at), quotes(id, number, created_at)")
        .in("user_id", tenantIds)
        .order("company_name", { ascending: true, nullsFirst: false })
        .order("name", { ascending: true }),
        supabase.from("profiles").select("id,slug").in("id", tenantIds),
        supabase.from("profile_custom_domains").select("profile_id,domain,verified").in("profile_id", tenantIds),
      ]);

      if (error) throw error;
      const normalized = ((data as ClientRow[]) || [])
        .filter((client) => !isQuickPlaceholderClient(client))
        .filter((client) => !client.is_deleted)
        .sort((a, b) => {
          const aName = (a.company_name || a.name || "").trim();
          const bName = (b.company_name || b.name || "").trim();
          return aName.localeCompare(bName, "pt-BR", { sensitivity: "base" });
        });
      setClients(normalized);
      const profileSlugValue =
        (profilesData ?? []).find((p) => Boolean((p as { slug?: string | null }).slug)) as
          | { slug?: string | null }
          | undefined;
      setProfileSlug(profileSlugValue?.slug || "");
      const activeDomain = (domainsData ?? []).find(
        (d) => Boolean((d as { verified?: boolean | null }).verified)
      ) as { domain?: string | null; verified?: boolean | null } | undefined;
      setProfileCustomDomain(activeDomain?.domain || "");
      setProfileCustomDomainVerified(Boolean(activeDomain?.verified));
    } catch (err) {
      console.error("Erro ao buscar clientes:", err);
    } finally {
      setLoading(false);
    }
  }

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

  const thirtyDaysAgo = useMemo(() => {
    const d = new Date();
    d.setDate(d.getDate() - 30);
    return d;
  }, []);

  const { newClientsCount, activeClientsCount, inactiveClientsCount, pendingApprovalCount } = useMemo(() => {
    return clients.reduce(
      (acc, c) => {
        if (new Date(c.created_at) >= thirtyDaysAgo) acc.newClientsCount++;
        if (c.active) acc.activeClientsCount++;
        else acc.inactiveClientsCount++;
        /* Cadastro feito pela loja no modo "com aprovação": espera a equipe. */
        if (c.portal_status === "pending") acc.pendingApprovalCount++;
        return acc;
      },
      { newClientsCount: 0, activeClientsCount: 0, inactiveClientsCount: 0, pendingApprovalCount: 0 }
    );
  }, [clients, thirtyDaysAgo]);

  const filtered = useMemo(() => {
    let result = clients;

    // Appy status filter
    if (clientFilter === "novos") {
      result = result.filter(c => new Date(c.created_at) >= thirtyDaysAgo);
    } else if (clientFilter === "ativos") {
      result = result.filter(c => c.active);
    } else if (clientFilter === "inativos") {
      result = result.filter(c => !c.active);
    } else if (clientFilter === "aguardando") {
      result = result.filter(c => c.portal_status === "pending");
    }

    const term = searchTerm.trim().toLowerCase();
    if (!term) return result;

    return result.filter((c) => {
      const haystack = [
        c.name,
        c.company_name || "",
        c.document || "",
        c.email || "",
        c.phone || "",
        c.whatsapp || "",
        (c.tags || []).join(" "),
      ]
        .join(" ")
        .toLowerCase();
      return haystack.includes(term);
    });
  }, [clients, searchTerm, clientFilter, thirtyDaysAgo]);

  async function handleDeleteClient() {
    if (!deleteModalClient || deletingClient) return;
    setDeletingClient(true);
    try {
      const supabase = getSupabaseClient();
      const {
        data: { user },
      } = await supabase.auth.getUser();
      if (!user) throw new Error("Usuário não autenticado");
      const ctx = await getCompanyContext(supabase, user);
      const tenantIds = ctx.tenantIds?.length ? ctx.tenantIds : [user.id];
      const now = new Date().toISOString();

      const { error } = await supabase
        .from("clients")
        .update({ active: false, is_deleted: true, deleted_at: now, updated_at: now })
        .eq("id", deleteModalClient.id)
        .in("user_id", tenantIds);
      if (error) throw error;

      setDeleteModalClient(null);
      await fetchClients();
    } catch (err) {
      console.error("Erro ao excluir cliente:", err);
      alert("Não foi possível excluir o cliente.");
    } finally {
      setDeletingClient(false);
    }
  }

  function getLastInteraction(client: ClientRow) {
    const orders = client.orders || [];
    const quotes = client.quotes || [];
    
    // Combine and sort by date descending
    const allInteractions = [
      ...orders.map(o => ({ type: 'Pedido', number: o.number, date: new Date(o.created_at) })),
      ...quotes.map(q => ({ type: 'Orçamento', number: q.number, date: new Date(q.created_at) }))
    ].sort((a, b) => b.date.getTime() - a.date.getTime());

    if (allInteractions.length === 0) return null;
    return allInteractions[0];
  }

  const copyToClipboard = () => {
    if (!profileSlug && !(profileCustomDomain && profileCustomDomainVerified)) return;
    const baseUrl =
      profileCustomDomain && profileCustomDomainVerified ? `https://${profileCustomDomain}` : `${publicCatalogBaseUrl}/${profileSlug}`;
    const url = `${baseUrl}/cadastro-cliente`;
    navigator.clipboard.writeText(url);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="space-y-6">
      <PageHeader
        title="Clientes"
        subtitle="Cadastre novos contatos, gerencie sua carteira e acompanhe o histórico de todos os seus clientes."
        actions={
          <div className="flex flex-wrap items-center gap-2">
            <div className="hidden md:block w-64">
              <Input
                placeholder="Buscar por nome, empresa ou contato"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                icon={<Search size={14} />}
              />
            </div>
            <div className="flex items-center border border-zinc-200 rounded-lg p-1 bg-white shrink-0 hidden md:flex">
              <button
                onClick={() => setViewMode("list")}
                className={`p-2 rounded-md transition-colors ${
                  viewMode === "list"
                    ? "bg-zinc-100 text-zinc-900"
                    : "text-zinc-400 hover:text-zinc-600 hover:bg-zinc-50"
                }`}
                title="Lista"
              >
                <List size={18} />
              </button>
              <button
                onClick={() => setViewMode("grid")}
                className={`p-2 rounded-md transition-colors ${
                  viewMode === "grid"
                    ? "bg-zinc-100 text-zinc-900"
                    : "text-zinc-400 hover:text-zinc-600 hover:bg-zinc-50"
                }`}
                title="Grade"
              >
                <LayoutGrid size={18} />
              </button>
            </div>
            <Button
              type="button"
              onClick={copyToClipboard}
              variant="secondary"
              icon={copied ? <Check size={16} /> : <Copy size={16} />}
              disabled={!profileSlug && !(profileCustomDomain && profileCustomDomainVerified)}
            >
              {copied ? "Copiado" : "Copiar link"}
            </Button>
            {podeMexerEmClientes ? (
              <Button
                type="button"
                onClick={() => setIsModalOpen(true)}
                icon={<Plus size={16} />}
              >
                Novo cliente
              </Button>
            ) : null}
          </div>
        }
      />

      <div className="md:hidden">
        <Input
          placeholder="Buscar por nome, empresa ou contato"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          icon={<Search size={14} />}
        />
      </div>

      {!loading && clients.length > 0 && (
        <div className="flex flex-col gap-6 mb-6">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="bg-white rounded-2xl border border-gray-100 p-4 flex flex-col gap-1">
              <span className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Total</span>
              <span className="text-2xl font-bold text-gray-900">{clients.length}</span>
            </div>
            <div className="bg-white rounded-2xl border border-gray-100 p-4 flex flex-col gap-1">
              <span className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Novos (30d)</span>
              <span className="text-2xl font-bold text-indigo-600">{newClientsCount}</span>
            </div>
            <div className="bg-white rounded-2xl border border-gray-100 p-4 flex flex-col gap-1">
              <span className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Ativos</span>
              <span className="text-2xl font-bold text-emerald-600">{activeClientsCount}</span>
            </div>
            <div className="bg-white rounded-2xl border border-gray-100 p-4 flex flex-col gap-1">
              <span className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Inativos</span>
              <span className="text-2xl font-bold text-red-600">{inactiveClientsCount}</span>
            </div>
          </div>

          <div className="flex items-center gap-2 overflow-x-auto pb-2 scrollbar-hide">
            <button 
              onClick={() => setClientFilter('todos')}
              className={`px-4 py-2 rounded-xl text-sm font-semibold whitespace-nowrap transition-colors ${clientFilter === 'todos' ? 'bg-[var(--ks-color-brand-dark)] text-white' : 'bg-white border border-gray-100 text-gray-600 hover:bg-gray-50'}`}
            >
              Todos os clientes
            </button>
            <button 
              onClick={() => setClientFilter('novos')}
              className={`px-4 py-2 rounded-xl text-sm font-semibold whitespace-nowrap transition-colors ${clientFilter === 'novos' ? 'bg-indigo-50 text-indigo-700 border border-indigo-100' : 'bg-white border border-gray-100 text-gray-600 hover:bg-gray-50'}`}
            >
              Novos
            </button>
            <button 
              onClick={() => setClientFilter('ativos')}
              className={`px-4 py-2 rounded-xl text-sm font-semibold whitespace-nowrap transition-colors ${clientFilter === 'ativos' ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-white border border-gray-100 text-gray-600 hover:bg-gray-50'}`}
            >
              Ativos
            </button>
            <button
              onClick={() => setClientFilter('inativos')}
              className={`px-4 py-2 rounded-xl text-sm font-semibold whitespace-nowrap transition-colors ${clientFilter === 'inativos' ? 'bg-red-50 text-red-700 border border-red-100' : 'bg-white border border-gray-100 text-gray-600 hover:bg-gray-50'}`}
            >
              Inativos
            </button>
            {/* Quem se cadastrou pela loja e espera a aprovação (Regras da loja,
                cadastro "com aprovação"). O número fica no botão para a pessoa
                ver de longe que tem gente esperando. */}
            <button
              onClick={() => setClientFilter('aguardando')}
              className={`px-4 py-2 rounded-xl text-sm font-semibold whitespace-nowrap transition-colors ${clientFilter === 'aguardando' ? 'bg-amber-50 text-amber-700 border border-amber-100' : 'bg-white border border-gray-100 text-gray-600 hover:bg-gray-50'}`}
            >
              Aguardando aprovação ({pendingApprovalCount})
            </button>
          </div>
        </div>
      )}

      {loading ? (
        <div className="ks-surface flex items-center justify-center py-16">
          <div className="w-6 h-6 border-2 border-[var(--ks-color-primary)] border-t-transparent rounded-full animate-spin" />
        </div>
      ) : filtered.length === 0 ? (
        <div className="ks-surface ks-empty-state">
          <div className="w-10 h-10 rounded-full bg-[rgba(226,232,255,0.8)] flex items-center justify-center mx-auto mb-4 text-[var(--ks-color-text-soft)]">
            <User size={20} />
          </div>
          <h3 className="ks-empty-state-title">Nenhum cliente encontrado</h3>
          <p className="ks-empty-state-subtitle">
            Cadastre o primeiro cliente para começar a registrar orçamentos e pedidos.
          </p>
          <div className="mt-6 flex justify-center">
            <Button type="button" onClick={() => setIsModalOpen(true)} icon={<Plus size={16} />}>
              Adicionar cliente
            </Button>
          </div>
        </div>
      ) : (
        <>
          {/* Mobile List */}
          <div className="md:hidden space-y-4">
            {filtered.map((client) => {
              const lastInteraction = getLastInteraction(client);
              const cityLine =
                [client.address_city || "", client.address_state || ""]
                  .filter(Boolean)
                  .join(" / ") || "-";
              const typeLabel = client.type === "pj" ? "PJ" : "PF";
              const clientName = client.company_name || client.name;
              const newQuoteHref = `/dashboard/quotes/new?client_id=${encodeURIComponent(client.id)}`;

              return (
                <div key={client.id} className="bg-white rounded-2xl border border-gray-100 p-5 flex flex-col relative mb-4">
                  {/* Header */}
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex items-center gap-3 min-w-0">
                      <div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold text-white shrink-0 ${
                           ['bg-blue-600', 'bg-indigo-600', 'bg-purple-600', 'bg-teal-600'][((clientName?.charCodeAt(0) || 0) + (clientName?.length || 0)) % 4]
                        }`}>
                          {clientName?.substring(0, 2).toUpperCase()}
                      </div>
                      <div className="flex flex-col min-w-0">
                        <h3 className="font-semibold text-gray-900 text-base leading-tight truncate" title={clientName}>
                          {clientName}
                        </h3>
                        {client.company_name && (
                          <p className="text-xs text-gray-500 font-medium truncate">{client.name}</p>
                        )}
                      </div>
                    </div>
                    <div className="flex flex-col items-end gap-1 shrink-0 ml-2">
                      <span className={`px-2 py-1 rounded-md text-[10px] font-bold tracking-wide uppercase ${
                        client.type === 'pj'
                          ? 'bg-indigo-50 text-indigo-700'
                          : 'bg-emerald-50 text-emerald-700'
                      }`}>
                        {typeLabel}
                      </span>
                      {!client.active && (
                        <span className="px-2 py-1 rounded-md text-[10px] font-bold tracking-wide uppercase bg-red-50 text-red-600">
                          Inativo
                        </span>
                      )}
                      {client.portal_status === "pending" && (
                        <span className="px-2 py-1 rounded-md text-[10px] font-bold tracking-wide uppercase bg-amber-50 text-amber-700 whitespace-nowrap">
                          Aguardando aprovação
                        </span>
                      )}
                    </div>
                  </div>

                  {/* Body */}
                  <div className="flex flex-col gap-2 text-sm text-gray-600 mb-5">
                    {(client.phone || client.whatsapp) && (
                      <div className="flex items-center gap-2">
                        <Phone size={14} className="text-gray-400 shrink-0" />
                        <span className="truncate">{client.phone || client.whatsapp}</span>
                      </div>
                    )}
                    {client.email && (
                      <div className="flex items-center gap-2">
                        <Mail size={14} className="text-gray-400 shrink-0" />
                        <span className="truncate">{client.email}</span>
                      </div>
                    )}
                    {cityLine !== "-" && (
                      <div className="flex items-center gap-2">
                        <MapPin size={14} className="text-gray-400 shrink-0" />
                        <span className="truncate">{cityLine}</span>
                      </div>
                    )}
                  </div>

                  {/* Footer */}
                  <div className="mt-auto flex flex-col gap-3">
                    <div className="bg-gray-50 rounded-xl p-3 flex items-center justify-between">
                      <div className="flex flex-col min-w-0">
                        <span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-0.5">Última Atividade</span>
                        {lastInteraction ? (
                          <span className="text-xs font-medium text-gray-700 truncate">
                            {lastInteraction.type} #{lastInteraction.number} <span className="text-gray-400 ml-1">({lastInteraction.date.toLocaleDateString("pt-BR")})</span>
                          </span>
                        ) : (
                          <span className="text-xs font-medium text-gray-400">Nenhuma</span>
                        )}
                      </div>
                    </div>
                    
                    <div className="flex items-center gap-2">
                      {podeOrcar ? <Link href={newQuoteHref} className="flex-1">
                        <button className="w-full h-9 rounded-lg bg-indigo-50 text-indigo-700 text-xs font-bold hover:bg-indigo-100 transition-colors flex items-center justify-center gap-1.5" title="Novo orçamento">
                          <Plus size={14} /> Novo
                        </button>
                      </Link> : null}
                      <Link href={`/dashboard/clients/${client.id}`}>
                        <button className="w-9 h-9 rounded-lg border border-gray-200 text-gray-600 flex items-center justify-center hover:bg-gray-50 transition-colors" title="Ver Detalhes">
                          <Eye size={16} />
                        </button>
                      </Link>
                      {podeMexerEmClientes ? <button onClick={() => setDeleteModalClient(client)} className="w-9 h-9 rounded-lg border border-gray-200 text-red-500 flex items-center justify-center hover:bg-red-50 transition-colors" title="Excluir cliente">
                        <Trash2 size={16} />
                      </button> : null}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Desktop Views */}
          <div className="hidden md:block">
            {viewMode === "grid" ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                {filtered.map((client) => {
                  const lastInteraction = getLastInteraction(client);
                  const cityLine =
                    [client.address_city || "", client.address_state || ""]
                      .filter(Boolean)
                      .join(" / ") || "-";
                  const typeLabel = client.type === "pj" ? "PJ" : "PF";
                  const clientName = client.company_name || client.name;
                  const newQuoteHref = `/dashboard/quotes/new?client_id=${encodeURIComponent(client.id)}`;
                  
                  return (
                    <div
                      key={client.id}
                      className="bg-white rounded-2xl border border-gray-100 p-5 hover:border-gray-300 hover:shadow-sm transition-all duration-200 flex flex-col h-full relative"
                    >
                      {/* Header */}
                      <div className="flex items-start justify-between mb-4">
                        <div className="flex items-center gap-3 min-w-0">
                          <div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold text-white shrink-0 ${
                               ['bg-blue-600', 'bg-indigo-600', 'bg-purple-600', 'bg-teal-600'][((clientName?.charCodeAt(0) || 0) + (clientName?.length || 0)) % 4]
                            }`}>
                              {clientName?.substring(0, 2).toUpperCase()}
                          </div>
                          <div className="flex flex-col min-w-0">
                            <h3 className="font-semibold text-gray-900 text-base leading-tight truncate" title={clientName}>
                              {clientName}
                            </h3>
                            {client.company_name && (
                              <p className="text-xs text-gray-500 font-medium truncate">{client.name}</p>
                            )}
                          </div>
                        </div>
                        <div className="flex flex-col items-end gap-1 shrink-0 ml-2">
                          <span className={`px-2 py-1 rounded-md text-[10px] font-bold tracking-wide uppercase ${
                            client.type === 'pj'
                              ? 'bg-indigo-50 text-indigo-700'
                              : 'bg-emerald-50 text-emerald-700'
                          }`}>
                            {typeLabel}
                          </span>
                          {client.portal_status === "pending" && (
                            <span className="px-2 py-1 rounded-md text-[10px] font-bold tracking-wide uppercase bg-amber-50 text-amber-700 whitespace-nowrap">
                              Aguardando aprovação
                            </span>
                          )}
                        </div>
                      </div>

                      {/* Body */}
                      <div className="flex flex-col gap-2 text-sm text-gray-600 mb-5">
                        {(client.phone || client.whatsapp) && (
                          <div className="flex items-center gap-2">
                            <Phone size={14} className="text-gray-400 shrink-0" />
                            <span className="truncate">{client.phone || client.whatsapp}</span>
                          </div>
                        )}
                        {client.email && (
                          <div className="flex items-center gap-2">
                            <Mail size={14} className="text-gray-400 shrink-0" />
                            <span className="truncate">{client.email}</span>
                          </div>
                        )}
                        {cityLine !== "-" && (
                          <div className="flex items-center gap-2">
                            <MapPin size={14} className="text-gray-400 shrink-0" />
                            <span className="truncate">{cityLine}</span>
                          </div>
                        )}
                      </div>

                      {/* Footer */}
                      <div className="mt-auto flex flex-col gap-3">
                        <div className="bg-gray-50 rounded-xl p-3 flex items-center justify-between">
                          <div className="flex flex-col min-w-0">
                            <span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-0.5">Última Atividade</span>
                            {lastInteraction ? (
                              <span className="text-xs font-medium text-gray-700 truncate">
                                {lastInteraction.type} #{lastInteraction.number} <span className="text-gray-400 ml-1">({lastInteraction.date.toLocaleDateString("pt-BR")})</span>
                              </span>
                            ) : (
                              <span className="text-xs font-medium text-gray-400">Nenhuma</span>
                            )}
                          </div>
                        </div>
                        
                        <div className="flex items-center gap-2">
                          {podeOrcar ? <Link href={newQuoteHref} className="flex-1">
                            <button className="w-full h-9 rounded-lg bg-indigo-50 text-indigo-700 text-xs font-bold hover:bg-indigo-100 transition-colors flex items-center justify-center gap-1.5" title="Novo orçamento">
                              <Plus size={14} /> Novo
                            </button>
                          </Link> : null}
                          <Link href={`/dashboard/clients/${client.id}`}>
                            <button className="w-9 h-9 rounded-lg border border-gray-200 text-gray-600 flex items-center justify-center hover:bg-gray-50 transition-colors" title="Ver Detalhes">
                              <Eye size={16} />
                            </button>
                          </Link>
                          {podeMexerEmClientes ? <button onClick={() => setDeleteModalClient(client)} className="w-9 h-9 rounded-lg border border-gray-200 text-red-500 flex items-center justify-center hover:bg-red-50 transition-colors" title="Excluir cliente">
                            <Trash2 size={16} />
                          </button> : null}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="flex flex-col gap-3">
                {filtered.map((client) => {
                  const lastInteraction = getLastInteraction(client);
                  const cityLine =
                    [client.address_city || "", client.address_state || ""]
                      .filter(Boolean)
                      .join(" / ") || "-";
                  const typeLabel = client.type === "pj" ? "PJ" : "PF";
                  const clientName = client.company_name || client.name;
                  const newQuoteHref = `/dashboard/quotes/new?client_id=${encodeURIComponent(client.id)}`;

                  return (
                    <div 
                      key={client.id} 
                      className="group bg-white rounded-2xl p-4 border border-gray-100 hover:border-gray-300 hover:shadow-sm transition-all duration-200 flex flex-col md:flex-row items-center gap-4 relative"
                    >
                      {/* Avatar & Name */}
                      <div className="flex items-center gap-4 flex-1 min-w-[240px]">
                        <div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold text-white shrink-0 ${
                             ['bg-blue-600', 'bg-indigo-600', 'bg-purple-600', 'bg-teal-600'][((clientName?.charCodeAt(0) || 0) + (clientName?.length || 0)) % 4]
                          }`}>
                            {clientName?.substring(0, 2).toUpperCase()}
                        </div>
                        <div className="flex flex-col min-w-0">
                          <div className="flex items-center gap-2">
                            <h3 className="font-semibold text-gray-900 text-base leading-tight truncate" title={clientName}>
                              {clientName}
                            </h3>
                            <span className={`px-2 py-1 rounded-md text-[10px] font-bold tracking-wide uppercase shrink-0 ${
                              client.type === 'pj' 
                                ? 'bg-indigo-50 text-indigo-700' 
                                : 'bg-emerald-50 text-emerald-700'
                            }`}>
                              {typeLabel}
                            </span>
                            {!client.active && (
                              <span className="px-2 py-1 rounded-md text-[10px] font-bold tracking-wide uppercase bg-red-50 text-red-600 shrink-0">
                                Inativo
                              </span>
                            )}
                            {client.portal_status === "pending" && (
                              <span className="px-2 py-1 rounded-md text-[10px] font-bold tracking-wide uppercase bg-amber-50 text-amber-700 shrink-0 whitespace-nowrap">
                                Aguardando aprovação
                              </span>
                            )}
                          </div>
                          {client.company_name && (
                            <p className="text-xs text-gray-500 font-medium truncate mt-0.5">{client.name}</p>
                          )}
                        </div>
                      </div>

                      {/* Contact Info */}
                      <div className="flex flex-col gap-1 min-w-[200px] text-sm text-gray-600 hidden lg:flex">
                        {(client.phone || client.whatsapp) && (
                          <div className="flex items-center gap-2">
                            <Phone size={14} className="text-gray-400 shrink-0" />
                            <span>{client.phone || client.whatsapp}</span>
                          </div>
                        )}
                        {client.email && (
                          <div className="flex items-center gap-2">
                            <Mail size={14} className="text-gray-400 shrink-0" />
                            <span className="truncate max-w-[200px]">{client.email}</span>
                          </div>
                        )}
                      </div>

                      {/* Location */}
                      <div className="flex items-center gap-2 min-w-[150px] text-sm text-gray-600 hidden xl:flex">
                        {cityLine !== "-" && (
                          <>
                            <MapPin size={14} className="text-gray-400 shrink-0" />
                            <span className="truncate">{cityLine}</span>
                          </>
                        )}
                      </div>

                      {/* Last Activity & Actions */}
                      <div className="flex items-center justify-between md:justify-end gap-6 w-full md:w-auto ml-auto">
                        <div className="flex flex-col items-end min-w-[120px]">
                          <span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-0.5">Última Atividade</span>
                          {lastInteraction ? (
                            <div className="flex flex-col items-end">
                              <span className="text-xs font-medium text-gray-700">
                                {lastInteraction.type} #{lastInteraction.number}
                              </span>
                              <span className="text-[10px] text-gray-400">
                                {lastInteraction.date.toLocaleDateString("pt-BR")}
                              </span>
                            </div>
                          ) : (
                            <span className="text-xs font-medium text-gray-400">Nenhuma</span>
                          )}
                        </div>

                        <div className="flex items-center gap-2">
                          {podeOrcar ? <Link href={newQuoteHref}>
                            <button className="h-9 px-3 rounded-lg bg-indigo-50 text-indigo-700 text-xs font-bold hover:bg-indigo-100 transition-colors flex items-center justify-center gap-1.5 whitespace-nowrap" title="Novo orçamento">
                              <Plus size={14} /> Novo
                            </button>
                          </Link> : null}
                          <Link href={`/dashboard/clients/${client.id}`}>
                            <button className="w-9 h-9 rounded-lg border border-gray-200 text-gray-600 flex items-center justify-center hover:bg-gray-50 transition-colors" title="Ver Detalhes">
                              <Eye size={16} />
                            </button>
                          </Link>
                          {podeMexerEmClientes ? <button onClick={() => setDeleteModalClient(client)} className="w-9 h-9 rounded-lg border border-gray-200 text-red-500 flex items-center justify-center hover:bg-red-50 transition-colors" title="Excluir cliente">
                            <Trash2 size={16} />
                          </button> : null}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </>
      )}
      <ClientFormModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onSuccess={fetchClients}
      />
      <Dialog open={Boolean(deleteModalClient)} onOpenChange={(open) => !open && !deletingClient && setDeleteModalClient(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-[var(--ks-color-text-primary)]">
              <AlertTriangle size={18} className="text-[var(--ks-color-status-danger)]" />
              Excluir cliente
            </DialogTitle>
            <DialogDescription>
              {deleteModalClient
                ? `Deseja excluir ${deleteModalClient.company_name || deleteModalClient.name}?`
                : "Confirme a exclusão do cliente."}
            </DialogDescription>
          </DialogHeader>
          {deleteModalClient && ((deleteModalClient.orders?.length || 0) > 0 || (deleteModalClient.quotes?.length || 0) > 0) ? (
            <div className="rounded-lg border border-[rgba(245,158,11,0.35)] bg-[rgba(245,158,11,0.1)] p-3 text-sm text-amber-800">
              Este cliente possui {deleteModalClient.orders?.length || 0} pedido(s) e {deleteModalClient.quotes?.length || 0} orçamento(s) vinculados.
              Ao excluir, os registros continuarão com o nome atual do cliente e badge de cliente excluído.
            </div>
          ) : null}
          <DialogFooter>
            <button
              type="button"
              onClick={() => setDeleteModalClient(null)}
              className="h-10 rounded-lg border border-zinc-200 px-4 text-sm font-semibold text-zinc-700"
              disabled={deletingClient}
            >
              Cancelar
            </button>
            <button
              type="button"
              onClick={handleDeleteClient}
              className="h-10 rounded-lg bg-[var(--ks-color-status-danger)] px-4 text-sm font-semibold text-white disabled:opacity-60"
              disabled={deletingClient}
            >
              {deletingClient ? "Excluindo..." : "Excluir cliente"}
            </button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
