import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    Plug,
    Trash2,
    ShieldCheck,
    AlertTriangle,
    Loader2,
    ArrowLeft,
    KeyRound,
    Sparkles,
} from 'lucide-react';
import { getErrorMessage } from '@nexuscrm/host-sdk';
import { Button } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { ConfirmationModal } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { useSuccessToast, useErrorToast } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import {
    connectionsAPI,
    type Connection,
} from '../infrastructure/api/connections';

function formatDate(value: string | null): string {
    if (!value) return '—';
    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) return '—';
    return parsed.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
}

function scopeList(scopes: string | undefined | null): string[] {
    return (scopes ?? '').split(/\s+/).map(s => s.trim()).filter(Boolean);
}

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

export const ConnectionsPage: React.FC = () => {
    const navigate = useNavigate();
    const successToast = useSuccessToast();
    const errorToast = useErrorToast();

    const [connections, setConnections] = useState<Connection[]>([]);
    const [loading, setLoading] = useState(true);
    const [loadError, setLoadError] = useState<string | null>(null);
    const [disconnectTarget, setDisconnectTarget] = useState<Connection | null>(null);
    const [disconnecting, setDisconnecting] = useState(false);

    const loadConnections = useCallback(async () => {
        setLoading(true);
        setLoadError(null);
        try {
            const result = await connectionsAPI.list();
            setConnections(result);
        } catch (error) {
            setLoadError(getErrorMessage(error, 'Failed to load connected apps.'));
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => {
        void loadConnections();
    }, [loadConnections]);

    const handleDisconnect = useCallback(async () => {
        if (!disconnectTarget) return;
        setDisconnecting(true);
        try {
            await connectionsAPI.disconnect(disconnectTarget.id);
            successToast('App disconnected');
            setDisconnectTarget(null);
            await loadConnections();
        } catch (error) {
            errorToast(getErrorMessage(error, 'Failed to disconnect app.'));
        } finally {
            setDisconnecting(false);
        }
    }, [disconnectTarget, loadConnections, successToast, errorToast]);

    const orderedConnections = useMemo(
        () => [...connections].sort((a, b) => {
            const at = a.last_used_at ? Date.parse(a.last_used_at) : 0;
            const bt = b.last_used_at ? Date.parse(b.last_used_at) : 0;
            return bt - at;
        }),
        [connections],
    );

    return (
        <div className="h-full overflow-y-auto bg-slate-50">
            <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                {/* Header */}
                <div className="mb-6">
                    <button
                        type="button"
                        onClick={() => navigate('/help/ai-integration')}
                        className="inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-700 mb-3"
                    >
                        <ArrowLeft size={15} />
                        <span>Back to AI &amp; integration help</span>
                    </button>
                    <div className="flex items-center gap-3">
                        <div className="w-11 h-11 rounded-xl bg-blue-50 flex items-center justify-center">
                            <Plug size={22} className="text-blue-600" />
                        </div>
                        <div>
                            <h1 className="text-2xl font-bold text-slate-900 tracking-tight">Connected apps</h1>
                            <p className="text-sm text-slate-500 mt-0.5">
                                AI clients you have connected to your account over OAuth. Each acts as you and sees only what your permissions allow.
                            </p>
                        </div>
                    </div>
                </div>

                {/* Connected apps */}
                <div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
                    <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
                        <h2 className="text-base font-semibold text-slate-900">Your connected apps</h2>
                        {!loading && !loadError && (
                            <span className="text-xs text-slate-500">
                                {orderedConnections.length} {orderedConnections.length === 1 ? 'app' : 'apps'}
                            </span>
                        )}
                    </div>

                    {loading ? (
                        <div className="flex items-center justify-center gap-2 py-16 text-slate-500">
                            <Loader2 size={18} className="animate-spin" />
                            <span className="text-sm">Loading connected apps…</span>
                        </div>
                    ) : loadError ? (
                        <div className="px-6 py-12 text-center">
                            <AlertTriangle size={22} className="text-red-500 mx-auto mb-2" />
                            <p className="text-sm text-slate-700">{loadError}</p>
                            <div className="mt-4">
                                <Button variant="secondary" size="sm" onClick={() => void loadConnections()}>Try again</Button>
                            </div>
                        </div>
                    ) : orderedConnections.length === 0 ? (
                        <div className="px-6 py-16 text-center">
                            <Sparkles size={26} className="text-slate-300 mx-auto mb-3" />
                            <p className="text-sm font-medium text-slate-700">No connected apps yet</p>
                            <p className="text-sm text-slate-500 mt-1">
                                Follow the client-specific setup in the integration help page. Do not reuse another client's
                                Client ID or callback; use a scoped personal access token if your client cannot complete OAuth.
                            </p>
                            <div className="mt-4">
                                <Button
                                    variant="secondary"
                                    size="sm"
                                    onClick={() => navigate('/help/ai-integration')}
                                    icon={<Plug size={15} />}
                                >
                                    How to connect an app
                                </Button>
                            </div>
                        </div>
                    ) : (
                        <div className="overflow-x-auto">
                            <table className="w-full text-sm">
                                <thead>
                                    <tr className="text-left text-xs font-semibold text-slate-500 uppercase tracking-wide bg-slate-50">
                                        <th className="px-6 py-3">App</th>
                                        <th className="px-6 py-3">Scopes</th>
                                        <th className="px-6 py-3">Active grants</th>
                                        <th className="px-6 py-3">Last used</th>
                                        <th className="px-6 py-3">First connected</th>
                                        <th className="px-6 py-3 text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-slate-100">
                                    {orderedConnections.map(connection => (
                                        <tr key={connection.id}>
                                            <td className="px-6 py-4">
                                                <span className="font-medium text-slate-900">{connection.name}</span>
                                                <span className="text-xs text-slate-400">
                                                    Provisioned by an administrator
                                                </span>
                                            </td>
                                            <td className="px-6 py-4">
                                                <div className="flex flex-wrap gap-1">
                                                    {scopeList(connection.scope).length === 0 ? (
                                                        <span className="text-xs text-slate-400">—</span>
                                                    ) : (
                                                        scopeList(connection.scope).map(scope => (
                                                            <span
                                                                key={scope}
                                                                className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-mono bg-slate-100 text-slate-600"
                                                            >
                                                                {scope}
                                                            </span>
                                                        ))
                                                    )}
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 text-slate-600">{connection.active_grants}</td>
                                            <td className="px-6 py-4 text-slate-600">{formatDate(connection.last_used_at)}</td>
                                            <td className="px-6 py-4 text-slate-600">{formatDate(connection.first_connected_at)}</td>
                                            <td className="px-6 py-4 text-right">
                                                <button
                                                    type="button"
                                                    onClick={() => setDisconnectTarget(connection)}
                                                    className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-lg text-red-600 hover:bg-red-50 transition-colors"
                                                >
                                                    <Trash2 size={15} />
                                                    <span>Disconnect</span>
                                                </button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>

                {/* Cross-link to personal access tokens, so both surfaces are discoverable together. */}
                <div className="mt-6 rounded-xl border border-slate-200 bg-white p-5">
                    <div className="flex items-start gap-4">
                        <div className="w-11 h-11 rounded-xl bg-blue-50 flex items-center justify-center shrink-0">
                            <KeyRound size={22} className="text-blue-600" />
                        </div>
                        <div className="min-w-0">
                            <h3 className="text-sm font-semibold text-slate-900">Looking for personal access tokens?</h3>
                            <p className="mt-1 text-sm text-slate-600">
                                CLIs, scripts, and MCP clients that cannot use OAuth authenticate with a personal
                                access token instead. Manage those separately.
                            </p>
                            <button
                                type="button"
                                onClick={() => navigate('/settings/api-tokens')}
                                className="mt-3 inline-flex items-center gap-1.5 text-sm font-medium text-blue-600 hover:text-blue-700"
                            >
                                <KeyRound size={15} />
                                <span>Manage API tokens</span>
                            </button>
                        </div>
                    </div>
                </div>

                <div className="mt-6 flex items-start gap-3 rounded-xl border border-emerald-200 bg-emerald-50 p-4">
                    <ShieldCheck size={18} className="text-emerald-600 shrink-0 mt-0.5" />
                    <p className="text-sm text-emerald-900">
                        Disconnecting an app revokes its access immediately. Access is also revoked automatically
                        when your NexusCRM account is deactivated at offboarding.
                    </p>
                </div>
            </div>

            <ConfirmationModal
                isOpen={!!disconnectTarget}
                title="Disconnect app"
                message={`Disconnect "${disconnectTarget?.name ?? ''}"? It will immediately lose access to your NexusCRM data. You can reconnect it later by signing in again.`}
                confirmLabel="Disconnect"
                variant="danger"
                loading={disconnecting}
                onConfirm={() => void handleDisconnect()}
                onClose={() => (disconnecting ? undefined : setDisconnectTarget(null))}
            />
        </div>
    );
};

export default ConnectionsPage;
