import React, { useEffect, useState } from 'react';

type ChannelRow = {
    id: string;
    type: string;
    displayName: string;
    status: string;
    lastSyncAt: string | null;
    externalAccountId: string | null;
    externalBusinessId?: string | null;
    metadata?: Record<string, unknown>;
};

type ChannelsBootstrap = {
    channelsEndpoint: string;
    connectWhatsAppEndpoint: string;
    connectInstagramEndpoint: string;
    webhookEventBase: string;
    help: {
        whatsapp: string[];
        instagram: string[];
    };
    csrfToken: string;
};

export function ChannelsSettingsWorkspace({ bootstrap }: { bootstrap: ChannelsBootstrap }) {
    const [channels, setChannels] = useState<ChannelRow[]>([]);
    const [selectedChannelId, setSelectedChannelId] = useState<string | null>(null);
    const [webhookLogs, setWebhookLogs] = useState<Array<{ id: string; source: string; eventType: string; status: string; createdAt: string | null; retriesCount: number; errorMessage: string | null }>>([]);
    const [selectedEvent, setSelectedEvent] = useState<{ id: string; payload: unknown; status: string; errorMessage: string | null } | null>(null);
    const [waForm, setWaForm] = useState({
        display_name: 'WhatsApp Business',
        external_account_id: '',
        external_business_id: '',
        phone_number: '',
    });
    const [igForm, setIgForm] = useState({
        display_name: 'Instagram Business',
        external_account_id: '',
        external_business_id: '',
        handle: '',
    });

    async function loadChannels() {
        const response = await fetch(bootstrap.channelsEndpoint, {
            credentials: 'same-origin',
            headers: { Accept: 'application/json' },
        });
        const json = await response.json();
        setChannels(json.data ?? []);
    }

    useEffect(() => {
        void loadChannels();
    }, [bootstrap.channelsEndpoint]);

    useEffect(() => {
        async function loadLogs() {
            if (!selectedChannelId) {
                setWebhookLogs([]);
                return;
            }

            const response = await fetch(`${bootstrap.channelsEndpoint}/${selectedChannelId}/webhook-logs`, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json' },
            });
            const json = await response.json();
            setWebhookLogs(json.data ?? []);
            setSelectedEvent(null);
        }

        void loadLogs();
    }, [selectedChannelId, bootstrap.channelsEndpoint]);

    async function connect(endpoint: string, payload: Record<string, string>) {
        await fetch(endpoint, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': bootstrap.csrfToken,
            },
            body: JSON.stringify(payload),
        });

        await loadChannels();
    }

    async function loadEvent(eventId: string) {
        const response = await fetch(`${bootstrap.webhookEventBase}/${eventId}`, {
            credentials: 'same-origin',
            headers: { Accept: 'application/json' },
        });
        const json = await response.json();
        setSelectedEvent({
            id: json.data.id,
            payload: json.data.payload,
            status: json.data.status,
            errorMessage: json.data.errorMessage,
        });
    }

    async function retryEvent(eventId: string) {
        await fetch(`${bootstrap.webhookEventBase}/${eventId}/retry`, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': bootstrap.csrfToken,
            },
        });

        if (selectedChannelId) {
            const response = await fetch(`${bootstrap.channelsEndpoint}/${selectedChannelId}/webhook-logs`, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json' },
            });
            const json = await response.json();
            setWebhookLogs(json.data ?? []);
        }
    }

    return (
        <div className="space-y-6">
            <section className="rounded-[30px] border border-slate-200/80 bg-white p-8 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">Channels</p>
                <h2 className="mt-2 text-3xl font-semibold tracking-tight text-slate-950">WhatsApp and Instagram foundation</h2>
                <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-600">
                    Official messaging integration foundation with connection status, sync timestamps, and webhook-ready records for future real provider credentials.
                </p>
            </section>

            <div className="grid gap-6 xl:grid-cols-2">
                <div className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <div className="flex items-center justify-between gap-4">
                        <div>
                            <h3 className="text-xl font-semibold text-slate-950">WhatsApp Business Platform</h3>
                            <p className="mt-1 text-sm text-slate-500">Connect your business number so customer conversations can enter the shared inbox.</p>
                        </div>
                    </div>

                    <div className="mt-5 space-y-3">
                        {bootstrap.help.whatsapp.map((item) => (
                            <div key={item} className="rounded-2xl bg-slate-50 px-4 py-3 text-sm text-slate-600">
                                {item}
                            </div>
                        ))}
                    </div>

                    <div className="mt-5 grid gap-3">
                        <input value={waForm.display_name} onChange={(e) => setWaForm({ ...waForm, display_name: e.target.value })} placeholder="Display name" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                        <input value={waForm.phone_number} onChange={(e) => setWaForm({ ...waForm, phone_number: e.target.value })} placeholder="Business phone number" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                        <input value={waForm.external_account_id} onChange={(e) => setWaForm({ ...waForm, external_account_id: e.target.value })} placeholder="WhatsApp account ID (optional)" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                        <input value={waForm.external_business_id} onChange={(e) => setWaForm({ ...waForm, external_business_id: e.target.value })} placeholder="Meta business ID (optional)" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                        <button
                            type="button"
                            onClick={() => connect(bootstrap.connectWhatsAppEndpoint, waForm)}
                            className="rounded-2xl bg-emerald-500 px-4 py-3 text-sm font-semibold text-slate-950 hover:bg-emerald-400"
                        >
                            Connect WhatsApp
                        </button>
                    </div>
                </div>

                <div className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <div className="flex items-center justify-between gap-4">
                        <div>
                            <h3 className="text-xl font-semibold text-slate-950">Instagram Business</h3>
                            <p className="mt-1 text-sm text-slate-500">Connect your Instagram business account so DMs can become conversations in the system.</p>
                        </div>
                    </div>

                    <div className="mt-5 space-y-3">
                        {bootstrap.help.instagram.map((item) => (
                            <div key={item} className="rounded-2xl bg-slate-50 px-4 py-3 text-sm text-slate-600">
                                {item}
                            </div>
                        ))}
                    </div>

                    <div className="mt-5 grid gap-3">
                        <input value={igForm.display_name} onChange={(e) => setIgForm({ ...igForm, display_name: e.target.value })} placeholder="Display name" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                        <input value={igForm.handle} onChange={(e) => setIgForm({ ...igForm, handle: e.target.value })} placeholder="Instagram handle" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                        <input value={igForm.external_account_id} onChange={(e) => setIgForm({ ...igForm, external_account_id: e.target.value })} placeholder="Instagram account ID (optional)" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                        <input value={igForm.external_business_id} onChange={(e) => setIgForm({ ...igForm, external_business_id: e.target.value })} placeholder="Meta business ID (optional)" className="rounded-2xl border border-slate-300 px-4 py-3 text-sm" />
                        <button
                            type="button"
                            onClick={() => connect(bootstrap.connectInstagramEndpoint, igForm)}
                            className="rounded-2xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white hover:bg-slate-800"
                        >
                            Connect Instagram
                        </button>
                    </div>
                </div>
            </div>

            <section className="overflow-hidden rounded-[30px] border border-slate-200/80 bg-white shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <div className="border-b border-slate-200 px-6 py-5">
                    <h3 className="text-xl font-semibold text-slate-950">Connected channel records</h3>
                </div>
                <div className="overflow-x-auto">
                    <table className="min-w-full divide-y divide-slate-200 text-sm">
                        <thead className="bg-slate-50 text-left text-slate-500">
                            <tr>
                                <th className="px-6 py-4 font-semibold">Type</th>
                                <th className="px-6 py-4 font-semibold">Display Name</th>
                                <th className="px-6 py-4 font-semibold">Status</th>
                                <th className="px-6 py-4 font-semibold">External Account</th>
                                <th className="px-6 py-4 font-semibold">Last Sync</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-200">
                            {channels.map((channel) => (
                                <tr key={channel.id} onClick={() => setSelectedChannelId(channel.id)} className="cursor-pointer">
                                    <td className="px-6 py-5 font-semibold text-slate-950">{channel.type}</td>
                                    <td className="px-6 py-5 text-slate-600">{channel.displayName}</td>
                                    <td className="px-6 py-5">
                                        <span className={`rounded-full px-3 py-1 text-xs font-semibold ${channel.status === 'connected' ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'}`}>
                                            {channel.status}
                                        </span>
                                    </td>
                                    <td className="px-6 py-5 text-slate-600">{channel.externalAccountId ?? 'Pending'}</td>
                                    <td className="px-6 py-5 text-slate-600">{channel.lastSyncAt ?? 'Never'}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </section>

            {selectedChannelId ? (
                <section className="overflow-hidden rounded-[30px] border border-slate-200/80 bg-white shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <div className="border-b border-slate-200 px-6 py-5">
                        <h3 className="text-xl font-semibold text-slate-950">Webhook logs</h3>
                    </div>
                    <div className="overflow-x-auto">
                        <table className="min-w-full divide-y divide-slate-200 text-sm">
                            <thead className="bg-slate-50 text-left text-slate-500">
                                <tr>
                                    <th className="px-6 py-4 font-semibold">Source</th>
                                    <th className="px-6 py-4 font-semibold">Event</th>
                                    <th className="px-6 py-4 font-semibold">Status</th>
                                    <th className="px-6 py-4 font-semibold">Retries</th>
                                    <th className="px-6 py-4 font-semibold">Created</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-200">
                                {webhookLogs.map((log) => (
                                    <tr key={log.id} className="cursor-pointer" onClick={() => loadEvent(log.id)}>
                                        <td className="px-6 py-5 text-slate-600">{log.source}</td>
                                        <td className="px-6 py-5 text-slate-600">{log.eventType}</td>
                                        <td className="px-6 py-5 text-slate-600">{log.status}</td>
                                        <td className="px-6 py-5 text-slate-600">{log.retriesCount}</td>
                                        <td className="px-6 py-5 text-slate-600">{log.createdAt ?? 'N/A'}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </section>
            ) : null}

            {selectedEvent ? (
                <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                    <div className="flex items-center justify-between gap-4">
                        <div>
                            <h3 className="text-xl font-semibold text-slate-950">Webhook payload</h3>
                            <p className="mt-1 text-sm text-slate-500">Inspect payload content and retry processing for failed or stuck events.</p>
                        </div>
                        <button
                            type="button"
                            onClick={() => retryEvent(selectedEvent.id)}
                            className="rounded-2xl border border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                        >
                            Retry processing
                        </button>
                    </div>

                    {selectedEvent.errorMessage ? (
                        <div className="mt-4 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
                            {selectedEvent.errorMessage}
                        </div>
                    ) : null}

                    <pre className="mt-4 overflow-x-auto rounded-2xl bg-slate-950 p-5 text-sm text-slate-100">
                        {JSON.stringify(selectedEvent.payload, null, 2)}
                    </pre>
                </section>
            ) : null}

            <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <h3 className="text-xl font-semibold text-slate-950">Easy setup guidance</h3>
                <div className="mt-4 grid gap-3 md:grid-cols-3">
                    <div className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-600">
                        <p className="font-semibold text-slate-900">1. Prepare account</p>
                        <p className="mt-2">Use a real business phone number for WhatsApp and a professional Instagram account connected to Meta.</p>
                    </div>
                    <div className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-600">
                        <p className="font-semibold text-slate-900">2. Connect here</p>
                        <p className="mt-2">Enter the display name and any account identifiers you already have. The system stores the channel record immediately.</p>
                    </div>
                    <div className="rounded-2xl bg-slate-50 p-4 text-sm text-slate-600">
                        <p className="font-semibold text-slate-900">3. Start working</p>
                        <p className="mt-2">Once connected and synced, your customer messages can start appearing in Inbox for reply, notes, AI assist, and order handling.</p>
                    </div>
                </div>
            </section>
        </div>
    );
}

export type { ChannelsBootstrap };
