'use client';

import React, { useState, useEffect, useCallback } from 'react';
import {
    Code2, Copy, Check, ChevronDown, Terminal,
    Smartphone, Key, Plus, Trash2, Power,
    MessageSquare, Send, Wifi, List, Eye, EyeOff,
    Loader2, RefreshCw,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import { useAuth } from '@/context/AuthContext';
import { instanceApi, apiKeyApi, type ApiKeyRecord } from '@/services/chatApiService';
import { PageHeader, Button, Badge, Toast } from '@/components/ui';

// ─── Constants ────────────────────────────────────────────────────────────────

const BASE_URL = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:8008'

// ─── Endpoint definitions ─────────────────────────────────────────────────────

type EndpointDef = {
    id: string
    title: string
    method: 'GET' | 'POST' | 'PATCH' | 'DELETE'
    path: string
    icon: any
    color: string
    bg: string
    border: string
    description: string
    params: { name: string; in: 'path' | 'query' | 'body' | 'header'; required: boolean; desc: string }[]
    buildCurl: (opts: { baseUrl: string; token: string; instanceId: string; jid: string; msg: string }) => string
}

const ENDPOINTS: EndpointDef[] = [
    {
        id: 'send-text',
        title: 'Enviar Texto',
        method: 'POST',
        path: '/api/instances/:instanceId/send',
        icon: MessageSquare,
        color: 'text-blue-400',
        bg: 'bg-blue-500/10',
        border: 'border-blue-500/20',
        description: 'Envia uma mensagem de texto para qualquer JID do WhatsApp. O chat é criado automaticamente se não existir.',
        params: [
            { name: 'instanceId', in: 'path',   required: true,  desc: 'ID da instância conectada.' },
            { name: 'jid',        in: 'body',   required: true,  desc: 'Destinatário — número com DDI ou @g.us para grupos.' },
            { name: 'text',       in: 'body',   required: true,  desc: 'Conteúdo textual da mensagem.' },
            { name: 'replyToMessageId', in: 'body', required: false, desc: 'messageId original para citar.' },
        ],
        buildCurl: ({ baseUrl, token, instanceId, jid, msg }) =>
`curl -s -X POST '${baseUrl}/api/instances/${instanceId}/send' \\
  -H 'Authorization: Bearer ${token}' \\
  -H 'Content-Type: application/json' \\
  -d '{"jid":"${jid}","text":"${msg}"}'`,
    },
    {
        id: 'broadcast',
        title: 'Disparo em Massa',
        method: 'POST',
        path: '/api/instances/:instanceId/broadcast',
        icon: Send,
        color: 'text-brand-400',
        bg: 'bg-brand-500/10',
        border: 'border-brand-500/20',
        description: 'Inicia um disparo assíncrono para até 500 números com delay configurável. Retorna 202 e um jobId para rastreamento.',
        params: [
            { name: 'instanceId', in: 'path',  required: true,  desc: 'ID da instância conectada.' },
            { name: 'numbers',    in: 'body',  required: true,  desc: 'Array de strings com os números (apenas dígitos, DDI incluído).' },
            { name: 'message',    in: 'body',  required: true,  desc: 'Texto a ser enviado para todos.' },
            { name: 'delayMs',    in: 'body',  required: false, desc: 'Intervalo entre envios em ms (padrão: 2000, máx: 60000).' },
        ],
        buildCurl: ({ baseUrl, token, instanceId, jid, msg }) =>
`curl -s -X POST '${baseUrl}/api/instances/${instanceId}/broadcast' \\
  -H 'Authorization: Bearer ${token}' \\
  -H 'Content-Type: application/json' \\
  -d '{"numbers":["${jid}"],"message":"${msg}","delayMs":3000}'`,
    },
    {
        id: 'list-chats',
        title: 'Listar Chats',
        method: 'GET',
        path: '/api/chats',
        icon: List,
        color: 'text-emerald-400',
        bg: 'bg-emerald-500/10',
        border: 'border-emerald-500/20',
        description: 'Retorna a lista de chats do tenant com snapshot da última mensagem e protocolo ativo.',
        params: [
            { name: 'instanceId', in: 'query', required: true,  desc: 'Filtrar por instância.' },
            { name: 'search',     in: 'query', required: false, desc: 'Filtro textual por nome/JID.' },
            { name: 'archived',   in: 'query', required: false, desc: 'true para listar apenas arquivados.' },
            { name: 'limit',      in: 'query', required: false, desc: 'Máximo de resultados (padrão: 50).' },
        ],
        buildCurl: ({ baseUrl, token, instanceId }) =>
`curl -s '${baseUrl}/api/chats?instanceId=${instanceId}&limit=20' \\
  -H 'Authorization: Bearer ${token}'`,
    },
    {
        id: 'instance-status',
        title: 'Status da Instância',
        method: 'GET',
        path: '/api/instances',
        icon: Wifi,
        color: 'text-amber-400',
        bg: 'bg-amber-500/10',
        border: 'border-amber-500/20',
        description: 'Lista todas as instâncias do tenant com status (CONNECTED, DISCONNECTED, QR_PENDING…) e telefone vinculado.',
        params: [
            { name: 'Authorization', in: 'header', required: true, desc: 'Bearer token de acesso.' },
        ],
        buildCurl: ({ baseUrl, token }) =>
`curl -s '${baseUrl}/api/instances' \\
  -H 'Authorization: Bearer ${token}'`,
    },
]

// ─── Helpers ──────────────────────────────────────────────────────────────────

function useCopy() {
    const [copiedId, setCopiedId] = useState('')
    const copy = useCallback((text: string, id: string) => {
        navigator.clipboard.writeText(text)
        setCopiedId(id)
        setTimeout(() => setCopiedId(''), 2000)
    }, [])
    return { copiedId, copy }
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function ApiAccessPage() {
    const { token } = useAuth()
    const { copiedId, copy } = useCopy()

    // ── Instances ────────────────────────────────────────────────────────────
    const [instances, setInstances] = useState<{ id: string; name: string; status: string }[]>([])
    const [selectedInstanceId, setSelectedInstanceId] = useState('')
    const [loadingInstances, setLoadingInstances] = useState(true)

    useEffect(() => {
        instanceApi.list()
            .then((data) => {
                const list = Array.isArray(data) ? data : (data as any).instances ?? []
                setInstances(list)
                const connected = list.find((i: any) => i.status === 'CONNECTED')
                setSelectedInstanceId(connected?.id ?? list[0]?.id ?? '')
            })
            .catch(() => {})
            .finally(() => setLoadingInstances(false))
    }, [])

    // ── API Keys ─────────────────────────────────────────────────────────────
    const [apiKeys, setApiKeys] = useState<ApiKeyRecord[]>([])
    const [keysLoading, setKeysLoading] = useState(true)
    const [newKeyName, setNewKeyName] = useState('')
    const [creating, setCreating] = useState(false)
    const [revealedKey, setRevealedKey] = useState<{ id: string; key: string } | null>(null)
    const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' } | null>(null)

    const showToast = (message: string, type: 'success' | 'error') => {
        setToast({ message, type })
        setTimeout(() => setToast(null), 3000)
    }

    const loadKeys = useCallback(async () => {
        setKeysLoading(true)
        try {
            setApiKeys(await apiKeyApi.list())
        } catch {
            showToast('Erro ao carregar chaves.', 'error')
        } finally {
            setKeysLoading(false)
        }
    }, [])

    useEffect(() => { loadKeys() }, [])

    const createKey = async () => {
        if (!newKeyName.trim()) return
        setCreating(true)
        try {
            const result = await apiKeyApi.create(newKeyName.trim())
            setRevealedKey({ id: result.id, key: result.key })
            setNewKeyName('')
            await loadKeys()
            showToast('Chave criada. Copie agora — não será exibida novamente.', 'success')
        } catch (err: any) {
            showToast(err?.response?.data?.error ?? 'Erro ao criar chave.', 'error')
        } finally {
            setCreating(false)
        }
    }

    const toggleKey = async (id: string, isActive: boolean) => {
        await apiKeyApi.toggle(id, !isActive)
        setApiKeys((prev) => prev.map((k) => k.id === id ? { ...k, isActive: !isActive } : k))
    }

    const deleteKey = async (id: string) => {
        await apiKeyApi.delete(id)
        setApiKeys((prev) => prev.filter((k) => k.id !== id))
        showToast('Chave revogada.', 'success')
    }

    // ── Curl playground ──────────────────────────────────────────────────────
    const [activeEndpoint, setActiveEndpoint] = useState('send-text')
    const [testJid, setTestJid] = useState('5511999999999')
    const [testMsg, setTestMsg] = useState('Olá! Mensagem de teste.')
    const [showToken, setShowToken] = useState(false)

    const activeToken = token ?? 'SEU_TOKEN_JWT'
    const displayToken = showToken ? activeToken : `${activeToken.slice(0, 20)}…`

    return (
        <div className="flex-1 overflow-y-auto p-6 md:p-10">
            <PageHeader
                icon={Code2}
                title="API"
                titleAccent=" Access"
                subtitle="Integre o NewWhats em qualquer sistema externo"
            />

            <div className="grid grid-cols-1 xl:grid-cols-3 gap-8">

                {/* ── Left: API Keys + Token ──────────────────────────────── */}
                <div className="xl:col-span-1 space-y-6">

                    {/* Bearer Token */}
                    <div className="glass rounded-2xl border border-white/5 p-5 space-y-3">
                        <p className="text-xs text-slate-400 uppercase tracking-widest font-bold flex items-center gap-1.5">
                            <Key className="w-3.5 h-3.5" /> Token de Sessão (JWT)
                        </p>
                        <div className="flex items-center gap-2">
                            <code className="flex-1 text-xs text-brand-300 bg-black/30 border border-white/5 rounded-lg px-3 py-2 font-mono truncate">
                                {displayToken}
                            </code>
                            <button onClick={() => setShowToken(!showToken)} className="p-2 text-slate-400 hover:text-white transition-colors">
                                {showToken ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                            </button>
                            <button onClick={() => copy(activeToken, 'jwt')} className="p-2 text-slate-400 hover:text-brand-400 transition-colors">
                                {copiedId === 'jwt' ? <Check className="w-4 h-4 text-emerald-400" /> : <Copy className="w-4 h-4" />}
                            </button>
                        </div>
                        <p className="text-xs text-slate-600">Expira com a sessão. Use uma API Key para integração permanente.</p>
                    </div>

                    {/* API Keys */}
                    <div className="glass rounded-2xl border border-white/5 p-5 space-y-4">
                        <div className="flex items-center justify-between">
                            <p className="text-xs text-slate-400 uppercase tracking-widest font-bold flex items-center gap-1.5">
                                <Key className="w-3.5 h-3.5" /> API Keys
                            </p>
                            <button onClick={loadKeys} className="p-1 text-slate-500 hover:text-white transition-colors">
                                <RefreshCw className={`w-3.5 h-3.5 ${keysLoading ? 'animate-spin' : ''}`} />
                            </button>
                        </div>

                        {/* Revealed key banner */}
                        <AnimatePresence>
                            {revealedKey && (
                                <motion.div
                                    initial={{ opacity: 0, height: 0 }}
                                    animate={{ opacity: 1, height: 'auto' }}
                                    exit={{ opacity: 0, height: 0 }}
                                    className="overflow-hidden"
                                >
                                    <div className="bg-emerald-500/10 border border-emerald-500/30 rounded-xl p-3 space-y-2">
                                        <p className="text-xs font-bold text-emerald-400">Copie agora — não será exibida novamente</p>
                                        <div className="flex items-center gap-2">
                                            <code className="flex-1 text-xs text-emerald-300 font-mono break-all">{revealedKey.key}</code>
                                            <button onClick={() => { copy(revealedKey.key, 'revealed'); setRevealedKey(null) }} className="shrink-0 p-1.5 bg-emerald-500/20 hover:bg-emerald-500/30 rounded-lg text-emerald-400 transition-colors">
                                                {copiedId === 'revealed' ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
                                            </button>
                                        </div>
                                    </div>
                                </motion.div>
                            )}
                        </AnimatePresence>

                        {/* Create form */}
                        <div className="flex gap-2">
                            <input
                                type="text"
                                value={newKeyName}
                                onChange={(e) => setNewKeyName(e.target.value)}
                                placeholder="Nome da chave…"
                                onKeyDown={(e) => { if (e.key === 'Enter') createKey() }}
                                className="flex-1 bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-brand-500/50 transition-colors"
                            />
                            <Button variant="primary" size="sm" loading={creating} onClick={createKey} disabled={!newKeyName.trim()} icon={<Plus className="w-3.5 h-3.5" />}>
                                Criar
                            </Button>
                        </div>

                        {/* Keys list */}
                        {keysLoading ? (
                            <div className="flex justify-center py-4">
                                <Loader2 className="w-4 h-4 text-brand-400 animate-spin" />
                            </div>
                        ) : apiKeys.length === 0 ? (
                            <p className="text-xs text-slate-600 text-center py-3">Nenhuma chave criada.</p>
                        ) : (
                            <div className="space-y-2">
                                {apiKeys.map((k) => (
                                    <div key={k.id} className="flex items-center gap-2 p-2.5 rounded-xl bg-white/[0.03] border border-white/5 group">
                                        <div className="flex-1 min-w-0">
                                            <p className={`text-sm font-medium truncate ${k.isActive ? 'text-white' : 'text-slate-500 line-through'}`}>{k.name}</p>
                                            <p className="text-xs font-mono text-slate-600 truncate">{k.keyPreview}</p>
                                        </div>
                                        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                            <button title={k.isActive ? 'Desativar' : 'Ativar'} onClick={() => toggleKey(k.id, k.isActive)}
                                                className={`p-1 rounded transition-colors ${k.isActive ? 'text-slate-400 hover:text-amber-400' : 'text-emerald-400 hover:text-emerald-300'}`}>
                                                <Power className="w-3.5 h-3.5" />
                                            </button>
                                            <button title="Revogar" onClick={() => deleteKey(k.id)} className="p-1 rounded text-slate-400 hover:text-red-400 transition-colors">
                                                <Trash2 className="w-3.5 h-3.5" />
                                            </button>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* Instance selector */}
                    <div className="glass rounded-2xl border border-white/5 p-5 space-y-3">
                        <p className="text-xs text-slate-400 uppercase tracking-widest font-bold flex items-center gap-1.5">
                            <Smartphone className="w-3.5 h-3.5" /> Instância para exemplos
                        </p>
                        <select
                            value={selectedInstanceId}
                            onChange={(e) => setSelectedInstanceId(e.target.value)}
                            disabled={loadingInstances}
                            className="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-500/50 transition-colors appearance-none"
                        >
                            {loadingInstances
                                ? <option>Carregando…</option>
                                : instances.map((i) => <option key={i.id} value={i.id}>{i.name} ({i.status})</option>)
                            }
                        </select>

                        <div className="grid grid-cols-1 gap-3">
                            <div>
                                <label className="block text-xs text-slate-500 mb-1">JID de teste</label>
                                <input type="text" value={testJid} onChange={(e) => setTestJid(e.target.value)}
                                    className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white font-mono focus:outline-none focus:border-brand-500/50 transition-colors" />
                            </div>
                            <div>
                                <label className="block text-xs text-slate-500 mb-1">Mensagem de teste</label>
                                <input type="text" value={testMsg} onChange={(e) => setTestMsg(e.target.value)}
                                    className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-brand-500/50 transition-colors" />
                            </div>
                        </div>

                        <div className="flex items-center gap-2 p-2.5 rounded-xl bg-white/[0.03] border border-white/5">
                            <div className="w-2 h-2 rounded-full bg-emerald-400 shrink-0" />
                            <p className="text-xs text-slate-400 font-mono truncate">{BASE_URL}</p>
                        </div>
                    </div>
                </div>

                {/* ── Right: Endpoint docs ────────────────────────────────── */}
                <div className="xl:col-span-2 space-y-3">
                    {ENDPOINTS.map((ep) => {
                        const isActive = activeEndpoint === ep.id
                        const curl = ep.buildCurl({
                            baseUrl: BASE_URL,
                            token: activeToken,
                            instanceId: selectedInstanceId || 'INSTANCE_ID',
                            jid: testJid,
                            msg: testMsg,
                        })

                        return (
                            <motion.div
                                key={ep.id}
                                layout
                                className={`rounded-2xl border overflow-hidden transition-colors ${
                                    isActive ? 'border-white/10 bg-white/[0.03]' : 'border-white/5 bg-black/20 hover:border-white/10 hover:bg-white/[0.02]'
                                }`}
                            >
                                {/* Header */}
                                <div
                                    onClick={() => setActiveEndpoint(isActive ? '' : ep.id)}
                                    className="p-5 flex items-center justify-between cursor-pointer select-none group"
                                >
                                    <div className="flex items-center gap-4">
                                        <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${ep.bg} border ${ep.border}`}>
                                            <ep.icon className={`${ep.color} w-5 h-5`} />
                                        </div>
                                        <div>
                                            <div className="flex items-center gap-2">
                                                <span className="text-white font-bold group-hover:text-brand-400 transition-colors">{ep.title}</span>
                                                <span className={`text-[10px] font-black px-2 py-0.5 rounded-full border ${
                                                    ep.method === 'GET' ? 'bg-blue-500/20 text-blue-400 border-blue-500/30' :
                                                    ep.method === 'POST' ? 'bg-brand-500/20 text-brand-400 border-brand-500/30' :
                                                    'bg-amber-500/20 text-amber-400 border-amber-500/30'
                                                }`}>{ep.method}</span>
                                            </div>
                                            <p className="text-xs text-slate-500 font-mono mt-0.5">{ep.path}</p>
                                        </div>
                                    </div>
                                    <ChevronDown className={`w-4 h-4 text-slate-500 transition-transform ${isActive ? 'rotate-180' : ''}`} />
                                </div>

                                {/* Body */}
                                <AnimatePresence>
                                    {isActive && (
                                        <motion.div
                                            initial={{ height: 0, opacity: 0 }}
                                            animate={{ height: 'auto', opacity: 1 }}
                                            exit={{ height: 0, opacity: 0 }}
                                            transition={{ duration: 0.25 }}
                                            className="overflow-hidden"
                                        >
                                            <div className="px-5 pb-5 border-t border-white/5 pt-5 grid lg:grid-cols-2 gap-6">
                                                {/* Params */}
                                                <div>
                                                    <p className="text-sm text-slate-300 mb-4 leading-relaxed">{ep.description}</p>
                                                    <p className="text-xs text-slate-500 uppercase tracking-widest font-bold mb-3">Parâmetros</p>
                                                    <div className="space-y-2">
                                                        {ep.params.map((p) => (
                                                            <div key={p.name} className="p-3 rounded-xl bg-black/20 border border-white/5">
                                                                <div className="flex items-center justify-between mb-1">
                                                                    <div className="flex items-center gap-2">
                                                                        <code className="text-sm text-brand-300 font-mono">{p.name}</code>
                                                                        <span className="text-[10px] bg-white/5 text-slate-500 px-1.5 py-0.5 rounded uppercase">{p.in}</span>
                                                                    </div>
                                                                    {p.required
                                                                        ? <span className="text-[10px] text-red-400 font-bold uppercase">required</span>
                                                                        : <span className="text-[10px] text-slate-600 font-bold uppercase">optional</span>}
                                                                </div>
                                                                <p className="text-xs text-slate-500">{p.desc}</p>
                                                            </div>
                                                        ))}
                                                    </div>
                                                </div>

                                                {/* Curl example */}
                                                <div>
                                                    <div className="flex items-center justify-between mb-3">
                                                        <p className="text-xs text-slate-500 uppercase tracking-widest font-bold flex items-center gap-1.5">
                                                            <Terminal className="w-3.5 h-3.5" /> cURL
                                                        </p>
                                                        <button
                                                            onClick={() => copy(curl, ep.id)}
                                                            className="flex items-center gap-1.5 text-xs text-slate-400 hover:text-white transition-colors"
                                                        >
                                                            {copiedId === ep.id
                                                                ? <><Check className="w-3.5 h-3.5 text-emerald-400" /> Copiado</>
                                                                : <><Copy className="w-3.5 h-3.5" /> Copiar</>}
                                                        </button>
                                                    </div>
                                                    <pre className="bg-black/40 border border-white/5 rounded-xl p-4 text-xs font-mono text-slate-300 whitespace-pre-wrap break-all leading-relaxed overflow-x-auto">
                                                        {curl}
                                                    </pre>
                                                </div>
                                            </div>
                                        </motion.div>
                                    )}
                                </AnimatePresence>
                            </motion.div>
                        )
                    })}
                </div>
            </div>

            <Toast message={toast?.message ?? ''} type={toast?.type ?? 'success'} visible={!!toast} />
        </div>
    )
}
