import AppLayout from '@/layouts/app-layout';
import Heading from '@/components/heading';
import { EnterpriseLogo } from '@/components/EnterpriseLogo';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { getFlowDomainStyle } from '@/lib/flowTypeColors';
import { cn } from '@/lib/utils';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, router, usePage } from '@inertiajs/react';
import {
    ArrowLeft, Bell, Box, ChevronLeft, ChevronRight, Clock, CornerDownRight, Filter, History, LayoutGrid, Pencil, Plug, Search, ShoppingCart,
    Pause, Play, TriangleAlert, Webhook, Workflow, type LucideIcon,
} from 'lucide-react';
import { useEffect, useState, type ReactNode } from 'react';
import { LogsModal } from '../../modals/LogsModal';
import ConnWithModal from '../../modals/ConnWithModal';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { ConfigPreview } from './ConfigPreview';
import { readFilters, saveFilters } from './filters';
import { fmtUtc, OrdersTable } from './OrdersTable';
import { NotificationsSection } from './Notifications';
import { OverviewSection } from './Overview';
import IntegrationUpdateWithModal from './IntegrationUpdateWithModal';
import NewConnWithModal from './NewConnWithModal';
import { RunButton } from './RunButton';

type Section = { key: string; title: string; description: string; icon: LucideIcon; searchable?: boolean };

const sections: Section[] = [
    { key: 'overview', title: 'Visão geral', description: 'Resumo da atividade desta integração.', icon: LayoutGrid },
    { key: 'pedidos', title: 'Pedidos', description: 'Pedidos desta integração, do mais recente ao mais antigo.', icon: ShoppingCart, searchable: true },
    { key: 'produtos', title: 'Produtos', description: 'Produtos desta integração, do mais recente ao mais antigo.', icon: Box, searchable: true },
    { key: 'webhooks', title: 'Webhooks', description: 'Webhooks recebidos por esta integração.', icon: Webhook },
    { key: 'conexoes', title: 'Conexões', description: 'Conexões do cliente e quantas atividades desta integração usam cada uma.', icon: Plug },
    { key: 'fluxos', title: 'Fluxos', description: 'Atividades de cada fluxo, na ordem de execução.', icon: Workflow },
    { key: 'notificacoes', title: 'Notificações', description: 'Avisos de erro e alertas gerados por esta integração.', icon: Bell },
];

type Paginated<T> = { data: T[]; current_page: number; last_page: number; total: number };

// Datas do banco estão em UTC; exibe no horário local.
const fmtDate = fmtUtc;

function Pill({ ok, yes, no }: { ok: boolean; yes: string; no: string }) {
    return (
        <span
            className={cn(
                'inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold',
                ok
                    ? 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-300'
                    : 'border-border bg-muted text-muted-foreground',
            )}
        >
            {ok ? yes : no}
        </span>
    );
}

function DataTable({ cols, children, empty }: { cols: string[]; children: ReactNode[]; empty: string }) {
    return (
        <div className="overflow-x-auto rounded-xl border border-border bg-card">
            <Table>
                <TableHeader>
                    <TableRow className="bg-muted/50 hover:bg-muted/50">
                        {cols.map((h, i) => (
                            <TableHead key={i} className="h-10 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
                                {h}
                            </TableHead>
                        ))}
                    </TableRow>
                </TableHeader>
                <TableBody>
                    {children.length > 0 ? (
                        children
                    ) : (
                        <TableRow>
                            <TableCell colSpan={cols.length} className="py-14 text-center text-xs text-muted-foreground">
                                {empty}
                            </TableCell>
                        </TableRow>
                    )}
                </TableBody>
            </Table>
        </div>
    );
}

function Pager({ page, onPage }: { page: Paginated<any>; onPage: (p: number) => void }) {
    if (page.last_page <= 1) return null;
    return (
        <div className="flex items-center justify-between text-xs text-muted-foreground">
            <span>
                {page.total} registro{page.total !== 1 ? 's' : ''}
            </span>
            <div className="flex items-center gap-2">
                <Button size="sm" variant="outline" disabled={page.current_page <= 1} onClick={() => onPage(page.current_page - 1)}>
                    <ChevronLeft size={14} />
                </Button>
                <span>
                    {page.current_page} / {page.last_page}
                </span>
                <Button size="sm" variant="outline" disabled={page.current_page >= page.last_page} onClick={() => onPage(page.current_page + 1)}>
                    <ChevronRight size={14} />
                </Button>
            </div>
        </div>
    );
}

// ── fluxos ────────────────────────────────────────────────────────────────────

function everyMinutes(value: any) {
    const n = Number(value);
    if (!value || isNaN(n)) return 'Sem intervalo';
    if (n < 60) return `A cada ${n} min`;
    if (n % 1440 === 0) return `A cada ${n / 1440} dia${n / 1440 > 1 ? 's' : ''}`;
    if (n % 60 === 0) return `A cada ${n / 60}h`;
    return `A cada ${Math.floor(n / 60)}h${String(n % 60).padStart(2, '0')}`;
}

function LastRun({ activityFlowId }: { activityFlowId: number }) {
    const [state, setState] = useState<{ loading: boolean; last_run?: string | null; status?: string }>({ loading: true });

    useEffect(() => {
        let cancelled = false;
        fetch(route('monitor.lastrun.activityflow', { id: activityFlowId }))
            .then((res) => res.json())
            .then((d) => !cancelled && setState({ loading: false, last_run: d.success ? d.last_run : null, status: d.status }))
            .catch(() => !cancelled && setState({ loading: false }));
        return () => {
            cancelled = true;
        };
    }, [activityFlowId]);

    return (
        <span className="inline-flex items-center gap-1.5">
            <History size={12} />
            {state.loading ? (
                'Verificando...'
            ) : state.last_run ? (
                <>
                    Última execução:
                    <strong className={cn('text-foreground', { 'text-rose-600 dark:text-rose-400': state.status === 'error' })}>{state.last_run}</strong>
                </>
            ) : (
                'Sem execuções registradas'
            )}
        </span>
    );
}

function ToggleButton({ aodId, enabled }: { aodId: number; enabled: boolean }) {
    const [busy, setBusy] = useState(false);

    const toggle = () => {
        if (enabled && !confirm('Pausar esta atividade? Ela deixa de rodar até ser ativada de novo.')) return;
        router.put(
            route('integracoes.update', aodId),
            { enabled: enabled ? 0 : 1 },
            { preserveScroll: true, preserveState: true, onStart: () => setBusy(true), onFinish: () => setBusy(false) },
        );
    };

    return (
        <button
            type="button"
            disabled={busy}
            onClick={toggle}
            className={cn(
                'inline-flex items-center gap-1 rounded-md border px-2 py-1 text-[10px] font-semibold transition-colors disabled:opacity-50',
                enabled
                    ? 'border-rose-200 text-rose-600 hover:bg-rose-50 dark:border-rose-800 dark:text-rose-400 dark:hover:bg-rose-950'
                    : 'border-emerald-200 text-emerald-700 hover:bg-emerald-50 dark:border-emerald-800 dark:text-emerald-400 dark:hover:bg-emerald-950',
            )}
        >
            {enabled ? (
                <>
                    <Pause size={10} strokeWidth={2.5} /> Pausar
                </>
            ) : (
                <>
                    <Play size={10} strokeWidth={2.5} /> Ativar
                </>
            )}
        </button>
    );
}

// Formato que o IntegrationUpdateWithModal espera (o mesmo da tela Edit).
function toModalData(aod: any) {
    return {
        ...aod,
        activity_orig_dest_connections: aod.aodc_id
            ? {
                  connection_id: aod.aodc_connection_id,
                  filter: aod.filter,
                  conditions: aod.conditions,
                  default_values: aod.default_values,
                  required_fields: aod.required_fields,
                  fields: aod.fields,
                  configurations: aod.configurations,
              }
            : null,
    };
}

function ActivityStep({ aod, last, connections }: { aod: any; last: boolean; connections: any[] }) {
    const enabled = !!Number(aod.enabled);
    const hasConnection = !!aod.connection_id;

    return (
        <li className="relative flex gap-4 pb-5 last:pb-0">
            {/* linha que liga as etapas */}
            {!last && <span className="absolute top-8 bottom-0 left-[15px] w-px bg-border" />}

            <span
                className={cn(
                    'relative z-10 flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full border text-xs font-semibold',
                    enabled
                        ? 'border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-300'
                        : 'border-border bg-muted text-muted-foreground',
                )}
            >
                {aod.stream_position}
            </span>

            <div className={cn('min-w-0 flex-1 rounded-lg border border-border p-3', { 'bg-muted/30': !enabled })}>
                <div className="flex flex-wrap items-start justify-between gap-2">
                    <div className="min-w-0">
                        <p className={cn('text-sm font-medium', { 'text-muted-foreground': !enabled })}>
                            {aod.name ?? aod.activity_name}
                            <span className="ml-1.5 font-mono text-[10px] font-normal text-muted-foreground/60">#{aod.id}</span>
                        </p>
                        {aod.name && aod.activity_name && aod.name !== aod.activity_name && (
                            <p className="text-xs text-muted-foreground">Atividade: {aod.activity_name}</p>
                        )}
                    </div>
                    <div className="flex items-center gap-2">
                        <Pill ok={enabled} yes="Ativa" no="Pausada" />
                        {aod.aodc_id && <ToggleButton aodId={aod.id} enabled={enabled} />}
                        {!enabled && <RunButton aodId={aod.id} />}
                        <LogsModal aod={aod} />
                        <IntegrationUpdateWithModal key={`conf_${aod.id}_${aod.aodc_id}`} id={aod.id} data={toModalData(aod)} connections={connections} />
                    </div>
                </div>

                <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-muted-foreground">
                    {hasConnection ? (
                        <span className="inline-flex items-center gap-1.5">
                            <span className="h-5 w-5 overflow-hidden rounded border border-border bg-white">
                                <EnterpriseLogo src={aod.enterprise_logo} alt={aod.enterprise_name ?? ''} />
                            </span>
                            <span className="text-foreground">{aod.connection_name ?? aod.enterprise_name}</span>
                            <span className="font-mono text-[10px] text-muted-foreground/60">#{aod.connection_id}</span>
                            {aod.functionality && <span className="text-[10px] uppercase">{aod.functionality}</span>}
                        </span>
                    ) : (
                        <span className="inline-flex items-center gap-1 text-amber-700 dark:text-amber-400">
                            <TriangleAlert size={12} /> Sem conexão
                        </span>
                    )}
                    <span className="inline-flex items-center gap-1">
                        <Clock size={12} /> {everyMinutes(aod.cron_time)}
                    </span>
                    {!!Number(aod.is_webhook) && (
                        <span className="inline-flex items-center gap-1">
                            <Webhook size={12} /> Recebe webhook
                        </span>
                    )}
                    {aod.filter && (
                        <span className="inline-flex max-w-[260px] items-center gap-1" title={aod.filter}>
                            <Filter size={12} /> <span className="truncate font-mono">{aod.filter}</span>
                        </span>
                    )}
                    {aod.conditions && (
                        <span className="inline-flex items-center gap-1">
                            Condições: <ConfigPreview kind="conditions" raw={aod.conditions} />
                        </span>
                    )}
                    {aod.default_values && (
                        <span className="inline-flex items-center gap-1">
                            Valores padrão: <ConfigPreview kind="default_values" raw={aod.default_values} />
                        </span>
                    )}
                </div>
            </div>
        </li>
    );
}

function ActivityFlowCard({ af, connections, isSub = false }: { af: any; connections: any[]; isSub?: boolean }) {
    const activities: any[] = af.activities ?? [];
    const paused = activities.filter((a) => !Number(a.enabled)).length;

    return (
        <div className={cn('rounded-xl border border-border bg-card', { 'border-dashed': isSub })}>
            <div className="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3">
                <div className="flex items-center gap-2">
                    {isSub && <CornerDownRight size={14} className="text-muted-foreground" />}
                    <span className="text-sm font-semibold">{af.name}</span>
                    <span className="font-mono text-[10px] text-muted-foreground/60">#{af.id}</span>
                    {isSub && <span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Subfluxo</span>}
                </div>
                <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
                    <span className="inline-flex items-center gap-1.5">
                        <Clock size={12} />
                        {af.cron_start ? (
                            <span>
                                Roda entre <strong className="text-foreground">{af.cron_start}</strong> e{' '}
                                <strong className="text-foreground">{af.cron_end}</strong>
                            </span>
                        ) : (
                            <span>
                                Roda <strong className="text-foreground">24h</strong>
                            </span>
                        )}
                    </span>
                    <span>
                        {activities.length} atividade{activities.length !== 1 ? 's' : ''}
                    </span>
                    {paused > 0 && (
                        <span className="inline-flex items-center gap-1 font-semibold text-amber-700 dark:text-amber-400">
                            <TriangleAlert size={12} /> {paused} pausada{paused > 1 ? 's' : ''}
                        </span>
                    )}
                    <LastRun activityFlowId={af.id} />
                </div>
            </div>

            <div className="p-4">
                {activities.length > 0 ? (
                    <ol>
                        {activities.map((aod, i) => (
                            <ActivityStep key={aod.id} aod={aod} last={i === activities.length - 1} connections={connections} />
                        ))}
                    </ol>
                ) : (
                    <p className="py-6 text-center text-xs text-muted-foreground">Nenhuma atividade cadastrada.</p>
                )}
            </div>
        </div>
    );
}

function FlowsSection({ flows, connections }: { flows: any[]; connections: any[] }) {
    if (flows.length === 0) {
        return <p className="rounded-xl border border-dashed border-border py-14 text-center text-xs text-muted-foreground">Nenhum fluxo configurado.</p>;
    }

    return (
        <Tabs defaultValue={String(flows[0].id)}>
            <div className="mb-5 overflow-x-auto border-b border-border">
                <TabsList className="flex h-auto w-max min-w-full gap-0 bg-transparent p-0">
                    {flows.map((flow) => {
                        const style = getFlowDomainStyle(flow.flow_type_id);
                        return (
                            <TabsTrigger
                                key={flow.id}
                                value={String(flow.id)}
                                className={cn(
                                    'inline-flex items-center gap-1.5 rounded-none border-b-2 border-transparent bg-transparent px-4 py-3 text-xs whitespace-nowrap text-muted-foreground shadow-none hover:text-foreground data-[state=active]:font-semibold data-[state=active]:text-foreground',
                                    style.tabActive,
                                )}
                            >
                                <span className={cn('h-1.5 w-1.5 rounded-full', style.dot)} />
                                {flow.name}
                            </TabsTrigger>
                        );
                    })}
                </TabsList>
            </div>

            {flows.map((flow) => {
                const style = getFlowDomainStyle(flow.flow_type_id);
                return (
                    <TabsContent key={flow.id} value={String(flow.id)} className="space-y-4">
                        <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
                            {style.label && (
                                <span className={cn('inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[10px] font-bold uppercase', style.badge)}>
                                    <span className={cn('h-1.5 w-1.5 rounded-full', style.dot)} />
                                    {style.label}
                                </span>
                            )}
                            {flow.flow_type_name && <span>{flow.flow_type_name}</span>}
                        </div>

                        {flow.activity_flows.length > 0 ? (
                            <Tabs defaultValue={String(flow.activity_flows[0].id)}>
                                {/* etapas (activity flows pai) em abas; subfluxos ficam empilhados dentro da aba do pai */}
                                <div className="mb-4 overflow-x-auto border-b border-border">
                                    <TabsList className="flex h-auto w-max min-w-full gap-0 bg-transparent p-0">
                                        {flow.activity_flows.map((af: any) => (
                                            <TabsTrigger
                                                key={af.id}
                                                value={String(af.id)}
                                                className="inline-flex items-center gap-1.5 rounded-none border-b-2 border-transparent bg-transparent px-4 py-2.5 text-xs whitespace-nowrap text-muted-foreground shadow-none hover:text-foreground data-[state=active]:border-primary/60 data-[state=active]:text-foreground"
                                            >
                                                {af.name}
                                                <span className="font-mono text-[10px] opacity-50">{af.id}</span>
                                                {af.sub_flows.length > 0 && (
                                                    <span className="rounded-full bg-muted px-1.5 text-[10px] text-muted-foreground">
                                                        +{af.sub_flows.length} sub
                                                    </span>
                                                )}
                                            </TabsTrigger>
                                        ))}
                                    </TabsList>
                                </div>

                                {flow.activity_flows.map((af: any) => (
                                    <TabsContent key={af.id} value={String(af.id)} className="space-y-3">
                                        <ActivityFlowCard af={af} connections={connections} />
                                        {af.sub_flows.length > 0 && (
                                            <div className="border-l-2 border-border pl-4 md:ml-4">
                                                <div className="mb-3 flex items-center gap-2">
                                                    <span className="text-[10px] font-bold tracking-widest text-muted-foreground uppercase">Subfluxos</span>
                                                    <div className="h-px flex-1 bg-border" />
                                                </div>
                                                <Tabs defaultValue={String(af.sub_flows[0].id)}>
                                                    <div className="mb-3 overflow-x-auto border-b border-border">
                                                        <TabsList className="flex h-auto w-max min-w-full gap-0 bg-transparent p-0">
                                                            {af.sub_flows.map((sub: any) => (
                                                                <TabsTrigger
                                                                    key={sub.id}
                                                                    value={String(sub.id)}
                                                                    className="inline-flex items-center gap-1.5 rounded-none border-b-2 border-transparent bg-transparent px-3 py-2 text-[11px] whitespace-nowrap text-muted-foreground shadow-none hover:text-foreground data-[state=active]:border-amber-400 data-[state=active]:text-foreground"
                                                                >
                                                                    {sub.name}
                                                                    <span className="font-mono text-[10px] opacity-50">{sub.id}</span>
                                                                </TabsTrigger>
                                                            ))}
                                                        </TabsList>
                                                    </div>
                                                    {af.sub_flows.map((sub: any) => (
                                                        <TabsContent key={sub.id} value={String(sub.id)}>
                                                            <ActivityFlowCard af={sub} connections={connections} isSub />
                                                        </TabsContent>
                                                    ))}
                                                </Tabs>
                                            </div>
                                        )}
                                    </TabsContent>
                                ))}
                            </Tabs>
                        ) : (
                            <p className="rounded-xl border border-dashed border-border py-10 text-center text-xs text-muted-foreground">
                                Nenhuma etapa cadastrada para este fluxo.
                            </p>
                        )}
                    </TabsContent>
                );
            })}
        </Tabs>
    );
}

// Lupa da seção Conexões: busca a conexão completa (com credenciais) só no clique e abre o
// mesmo ConnWithModal da tela Edit. Depois de carregada, o botão do próprio modal assume.
function ConnectionEditButton({ integrationId, conn }: { integrationId: number; conn: any }) {
    const [connData, setConnData] = useState<any>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(false);

    const load = async () => {
        setLoading(true);
        setError(false);
        try {
            const res = await fetch(route('integracoes.connection', { id: integrationId, connId: conn.id }), { headers: { Accept: 'application/json' } });
            if (!res.ok) throw new Error();
            setConnData(await res.json());
        } catch {
            setError(true);
        } finally {
            setLoading(false);
        }
    };

    if (connData) {
        return <ConnWithModal connId={conn.id} connName={connData.name ?? conn.enterprise_name} connData={connData} initialOpen />;
    }

    return (
        <Tooltip>
            <TooltipTrigger asChild>
                <button
                    type="button"
                    onClick={load}
                    disabled={loading}
                    className="inline-flex items-center rounded-lg bg-blue-50 p-1.5 transition-colors hover:bg-blue-100 disabled:opacity-50 dark:bg-blue-950 dark:hover:bg-blue-900"
                >
                    <Search size={15} strokeWidth={2.2} className={cn('text-blue-600 dark:text-blue-400', { 'animate-pulse': loading })} />
                </button>
            </TooltipTrigger>
            <TooltipContent>{error ? 'Não foi possível carregar a conexão. Tente de novo.' : `Visualizar Conexão ${conn.id}`}</TooltipContent>
        </Tooltip>
    );
}

const cell = 'py-3 text-xs';
const rowLink = 'cursor-pointer hover:bg-muted/30 transition-colors';

export default function Show({
    integration,
    section,
    search,
    valuetype,
    data,
    enterprises,
}: {
    integration: any;
    section: string;
    search: string;
    valuetype: 'unique' | 'multiple';
    data: any;
    enterprises: any[];
}) {
    const [query, setQuery] = useState(search ?? '');
    const [valueType, setValueType] = useState(valuetype ?? 'unique');
    // Busca por múltiplos valores só existe em pedidos, igual à tela de pedidos.
    const isMultiple = section === 'pedidos' && valueType === 'multiple';
    const current = sections.find((s) => s.key === section) ?? sections[0];

    const flash = (usePage().props as any).flash || {};
    const [visibleMessage, setVisibleMessage] = useState<string | null>(null);

    useEffect(() => {
        if (!flash.message) return;
        setVisibleMessage(flash.message);
        const t = setTimeout(() => setVisibleMessage(null), 3000);
        return () => clearTimeout(t);
    }, [flash.message]);

    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Integrações', href: '/integracoes' },
        { title: integration.name, href: route('integracoes.show', integration.id) },
    ];

    const visit = (params: Record<string, any>) =>
        router.get(route('integracoes.show', integration.id), params, { preserveState: true, preserveScroll: true, replace: true });

    // Guarda o filtro atual da seção pesquisável para restaurá-lo ao voltar nela pelo menu.
    const page = data?.current_page;
    useEffect(() => {
        if (!current.searchable || current.key !== section) return;
        saveFilters(integration.id, section, {
            search: search || undefined,
            valuetype: valuetype === 'multiple' ? 'multiple' : undefined,
            page: page > 1 ? page : undefined,
        });
    }, [integration.id, section, search, valuetype, page]);

    const goToSection = (key: string) => {
        const saved = readFilters(integration.id)[key] ?? {};
        setQuery(saved.search ?? '');
        setValueType(saved.valuetype ?? 'unique');
        router.get(route('integracoes.show', integration.id), key === 'overview' ? {} : { secao: key, ...saved }, { preserveScroll: true });
    };

    // Recalcula a visão geral ignorando o cache e tira o ?refresh=1 da URL em seguida,
    // para um F5 depois não furar o cache de novo.
    const [refreshing, setRefreshing] = useState(false);
    const refreshOverview = () => {
        const url = route('integracoes.show', integration.id);
        router.get(url, { refresh: 1 }, {
            preserveScroll: true,
            preserveState: true,
            onStart: () => setRefreshing(true),
            onFinish: () => setRefreshing(false),
            onSuccess: () => router.replace({ url, preserveScroll: true, preserveState: true }),
        });
    };

    const goToPage = (page: number) =>
        visit({
            secao: section,
            search: search || undefined,
            valuetype: isMultiple ? 'multiple' : undefined,
            page,
        });

    const submitSearch = (e: React.FormEvent) => {
        e.preventDefault();
        visit({ secao: section, search: query || undefined, valuetype: isMultiple ? 'multiple' : undefined });
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={integration.name} />

            {visibleMessage && (
                <div className="pointer-events-none fixed inset-x-0 top-4 z-50 flex justify-center">
                    <div className="pointer-events-auto flex items-center gap-2 rounded-2xl border border-emerald-200 bg-emerald-50 px-5 py-2.5 text-sm font-medium text-emerald-700 shadow-lg dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-300">
                        {visibleMessage}
                    </div>
                </div>
            )}

            <div className="px-6 py-8">
                <Link
                    href={route('integracoes.index')}
                    className="mb-4 inline-flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"
                >
                    <ArrowLeft size={13} /> Todas as integrações
                </Link>

                <div className="flex flex-wrap items-start justify-between gap-3">
                    <Heading title={integration.name} description={`${integration.client_data?.name ?? 'Empresa'} · ID ${integration.id}`} />
                    <Button asChild size="sm" variant="outline">
                        <Link href={route('integracoes.edit', integration.id)}>
                            <Pencil size={13} /> Editar fluxos
                        </Link>
                    </Button>
                </div>

                <div className="flex flex-col space-y-8 lg:flex-row lg:space-y-0 lg:space-x-12">
                    <aside className="w-full max-w-xl lg:w-48">
                        <nav className="flex flex-col space-y-1 space-x-0">
                            {sections.map((item) => (
                                <Button
                                    key={item.key}
                                    size="sm"
                                    variant="ghost"
                                    onClick={() => goToSection(item.key)}
                                    className={cn('w-full justify-start gap-2', { 'bg-muted': section === item.key })}
                                >
                                    <item.icon size={14} />
                                    {item.title}
                                </Button>
                            ))}
                        </nav>
                    </aside>

                    <Separator className="my-6 md:hidden" />

                    <div className="min-w-0 flex-1">
                        <section className="space-y-6">
                            <div className="flex flex-wrap items-end justify-between gap-3">
                                <div>
                                    <h3 className="text-lg font-medium">{current.title}</h3>
                                    <p className="text-sm text-muted-foreground">{current.description}</p>
                                </div>
                                {section === 'conexoes' && <NewConnWithModal clientsId={integration.clients_id} enterprises={enterprises ?? []} />}
                                {current.searchable && (
                                    <form onSubmit={submitSearch} className="flex flex-wrap items-start gap-2">
                                        {isMultiple ? (
                                            <Textarea
                                                value={query}
                                                onChange={(e) => setQuery(e.target.value)}
                                                placeholder="Um por linha ou separados por vírgula (pedido, destino ou NF)"
                                                className="min-h-[72px] w-72 rounded-lg text-xs"
                                            />
                                        ) : (
                                            <div className="relative w-72">
                                                <Search size={13} className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-muted-foreground" />
                                                <Input
                                                    value={query}
                                                    onChange={(e) => setQuery(e.target.value)}
                                                    placeholder={section === 'pedidos' ? 'Pedido, destino ou NF...' : 'SKU, nome ou EAN...'}
                                                    className="h-9 rounded-lg pl-8 text-xs"
                                                />
                                            </div>
                                        )}
                                        {section === 'pedidos' && (
                                            <select
                                                value={valueType}
                                                onChange={(e) => setValueType(e.target.value as 'unique' | 'multiple')}
                                                className="h-9 rounded-lg border border-input bg-background px-2 text-xs"
                                            >
                                                <option value="unique">Valor único</option>
                                                <option value="multiple">Múltiplos</option>
                                            </select>
                                        )}
                                        {isMultiple && (
                                            <Button type="submit" size="sm" className="h-9">
                                                <Search size={13} /> Buscar
                                            </Button>
                                        )}
                                    </form>
                                )}
                            </div>

                            {section === 'overview' && (
                                <OverviewSection data={data} onNavigate={goToSection} onRefresh={refreshOverview} refreshing={refreshing} />
                            )}

                            {section === 'pedidos' && (
                                <>
                                    <OrdersTable orders={data.data} integrationName={integration.name} />
                                    <Pager page={data} onPage={goToPage} />
                                </>
                            )}

                            {section === 'produtos' && (
                                <>
                                    <DataTable cols={['SKU', 'Nome', 'EAN', 'Estoque', 'Atividade', 'Atualizado']} empty="Nenhum produto encontrado.">
                                        {data.data.map((p: any) => (
                                            <TableRow key={p.id} className={rowLink} onClick={() => router.visit(route('produtos.edit', p.id))}>
                                                <TableCell className={cn(cell, 'font-mono')}>{p.sku}</TableCell>
                                                <TableCell className={cell}>{p.name}</TableCell>
                                                <TableCell className={cn(cell, 'font-mono')}>{p.ean ?? '—'}</TableCell>
                                                <TableCell className={cell}>{p.stock ?? '—'}</TableCell>
                                                <TableCell className={cell}>{p.activity_name ?? '—'}</TableCell>
                                                <TableCell className={cn(cell, 'whitespace-nowrap')}>{fmtDate(p.updated_at)}</TableCell>
                                            </TableRow>
                                        ))}
                                    </DataTable>
                                    <Pager page={data} onPage={goToPage} />
                                </>
                            )}

                            {section === 'webhooks' && (
                                <>
                                    <DataTable cols={['#', 'Atividade', 'Status', 'Recebido', 'Atualizado']} empty="Nenhum webhook recebido.">
                                        {data.data.map((w: any) => (
                                            <TableRow key={w.id} className={rowLink} onClick={() => router.visit(route('webhooks.edit', w.id))}>
                                                <TableCell className={cn(cell, 'font-mono text-muted-foreground')}>{w.id}</TableCell>
                                                <TableCell className={cell}>{w.activity_name ?? '—'}</TableCell>
                                                <TableCell className={cell}>
                                                    <Pill ok={!!w.processed} yes="Processado" no="Pendente" />
                                                </TableCell>
                                                <TableCell className={cn(cell, 'whitespace-nowrap')}>{fmtDate(w.created_at)}</TableCell>
                                                <TableCell className={cn(cell, 'whitespace-nowrap')}>{fmtDate(w.updated_at)}</TableCell>
                                            </TableRow>
                                        ))}
                                    </DataTable>
                                    <Pager page={data} onPage={goToPage} />
                                </>
                            )}

                            {section === 'conexoes' && (
                                <DataTable cols={['', 'Conexão', 'Sistema', 'Atividades', 'Status', '']} empty="Nenhuma conexão vinculada aos fluxos.">
                                    {data.map((c: any) => (
                                        <TableRow key={c.id}>
                                            <TableCell className="w-12 py-2">
                                                <div className="h-8 w-8 overflow-hidden rounded-md border border-border bg-white">
                                                    <EnterpriseLogo src={c.logo} alt={c.enterprise_name ?? c.name} />
                                                </div>
                                            </TableCell>
                                            <TableCell className={cell}>
                                                <span className="font-medium">{c.name ?? c.enterprise_name ?? 'Sem nome'}</span>
                                                <span className="ml-2 font-mono text-[10px] text-muted-foreground">#{c.id}</span>
                                            </TableCell>
                                            <TableCell className={cell}>
                                                {c.enterprise_name ?? '—'}
                                                {c.functionality && <span className="ml-2 text-[10px] uppercase text-muted-foreground">{c.functionality}</span>}
                                            </TableCell>
                                            <TableCell className={cell}>{c.activities_count}</TableCell>
                                            <TableCell className={cell}>
                                                {Number(c.activities_count) > 0 ? (
                                                    <Pill ok={!!Number(c.enabled)} yes="Ativa" no="Inativa" />
                                                ) : (
                                                    <span className="text-[10px] text-muted-foreground">Sem uso</span>
                                                )}
                                            </TableCell>
                                            <TableCell className="w-12 py-2 text-right">
                                                <ConnectionEditButton integrationId={integration.id} conn={c} />
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </DataTable>
                            )}

                            {section === 'fluxos' && <FlowsSection flows={data.flows} connections={data.connections} />}

                            {section === 'notificacoes' && (
                                <>
                                    <NotificationsSection items={data.data} />
                                    <Pager page={data} onPage={goToPage} />
                                </>
                            )}
                        </section>
                    </div>
                </div>
            </div>
        </AppLayout>
    );
}
