import { Head, Link, router } from '@inertiajs/react';
import { useState } from 'react';

import { ConfigurableTable } from '@/components/ui/configurable-table';
import { PaginationLinks } from '@/components/ui/pagination-links';
import { AdminLayout } from '@/layouts/admin-layout';
import type { PaginatedData } from '@/types';

type WebhookEndpointRow = {
    id: number;
    name: string;
    url: string;
    is_active: boolean;
    subscribed_events: string[];
    deliveries_count: number;
    max_attempts: number;
    timeout_seconds: number;
    last_success_at: string | null;
    last_failure_at: string | null;
    updated_at: string | null;
};

type WebhookEndpointIndexProps = {
    endpoints: PaginatedData<WebhookEndpointRow>;
    filters: {
        search: string;
    };
    eventLabels: Record<string, string>;
};

export default function WebhookEndpointIndex({
    endpoints,
    filters,
    eventLabels,
}: WebhookEndpointIndexProps) {
    const [search, setSearch] = useState(filters.search || '');

    const submitSearch = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();

        router.get('/admin/webhook-endpoints', search ? { search } : {}, {
            preserveState: true,
            replace: true,
            preserveScroll: true,
        });
    };

    const deleteEndpoint = (id: number) => {
        if (
            !window.confirm(
                'Delete this webhook endpoint and its delivery logs?',
            )
        ) {
            return;
        }

        router.delete(`/admin/webhook-endpoints/${id}`);
    };

    return (
        <AdminLayout>
            <Head title="Webhook Endpoints" />

            <div className="space-y-5">
                <div className="flex flex-wrap items-center justify-between gap-3">
                    <div>
                        <h1 className="text-2xl font-semibold text-main">
                            Webhook Endpoints
                        </h1>
                        <p className="mt-1 text-sm text-muted">
                            Subscribe external systems to signed platform
                            events.
                        </p>
                    </div>
                    <Link
                        href="/admin/webhook-endpoints/create"
                        className="rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-white hover:bg-primary-hover"
                    >
                        Add Endpoint
                    </Link>
                </div>

                <form
                    onSubmit={submitSearch}
                    className="flex max-w-md flex-col gap-2 sm:flex-row"
                >
                    <input
                        value={search}
                        onChange={(event) => setSearch(event.target.value)}
                        placeholder="Search by name or URL"
                        className="w-full rounded-lg border border-border bg-control px-3 py-2 text-sm text-main outline-none focus:border-primary"
                    />
                    <button
                        type="submit"
                        className="rounded-lg border border-border px-3 py-2 text-sm font-medium text-muted hover:bg-surface hover:text-main"
                    >
                        Search
                    </button>
                </form>

                <div className="space-y-3 md:hidden">
                    {endpoints.data.map((endpoint) => (
                        <article
                            key={endpoint.id}
                            className="rounded-xl border border-border bg-card p-4"
                        >
                            <p className="font-semibold text-main">
                                {endpoint.name}
                            </p>
                            <p className="text-xs break-all text-muted">
                                {endpoint.url}
                            </p>
                            <div className="mt-3 grid grid-cols-2 gap-2 text-xs text-muted">
                                <p>
                                    Active: {endpoint.is_active ? 'Yes' : 'No'}
                                </p>
                                <p>Deliveries: {endpoint.deliveries_count}</p>
                                <p>Attempts: {endpoint.max_attempts}</p>
                                <p>Timeout: {endpoint.timeout_seconds}s</p>
                            </div>
                            <EventList
                                events={endpoint.subscribed_events}
                                labels={eventLabels}
                            />
                            <Actions
                                id={endpoint.id}
                                onDelete={deleteEndpoint}
                            />
                        </article>
                    ))}
                </div>

                <ConfigurableTable
                    tableId="admin-webhook-endpoints"
                    className="hidden overflow-x-auto rounded-xl border border-border md:block"
                >
                    <table className="min-w-full divide-y divide-border text-sm">
                        <thead className="bg-surface">
                            <tr>
                                <th className="px-4 py-3 text-left font-medium text-muted">
                                    Endpoint
                                </th>
                                <th className="px-4 py-3 text-left font-medium text-muted">
                                    Events
                                </th>
                                <th className="px-4 py-3 text-left font-medium text-muted">
                                    Status
                                </th>
                                <th className="px-4 py-3 text-left font-medium text-muted">
                                    Delivery
                                </th>
                                <th className="px-4 py-3 text-left font-medium text-muted">
                                    Actions
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border bg-card">
                            {endpoints.data.map((endpoint) => (
                                <tr key={endpoint.id}>
                                    <td className="px-4 py-3">
                                        <p className="font-medium text-main">
                                            {endpoint.name}
                                        </p>
                                        <p className="max-w-md truncate text-xs text-muted">
                                            {endpoint.url}
                                        </p>
                                    </td>
                                    <td className="px-4 py-3">
                                        <EventList
                                            events={endpoint.subscribed_events}
                                            labels={eventLabels}
                                        />
                                    </td>
                                    <td className="px-4 py-3 text-muted">
                                        <p>
                                            {endpoint.is_active
                                                ? 'Active'
                                                : 'Inactive'}
                                        </p>
                                        <p className="text-xs text-muted">
                                            Updated {endpoint.updated_at || '-'}
                                        </p>
                                    </td>
                                    <td className="px-4 py-3 text-muted">
                                        <p>{endpoint.deliveries_count} logs</p>
                                        <p className="text-xs text-muted">
                                            Last success:{' '}
                                            {endpoint.last_success_at || '-'}
                                        </p>
                                        <p className="text-xs text-muted">
                                            Last failure:{' '}
                                            {endpoint.last_failure_at || '-'}
                                        </p>
                                    </td>
                                    <td className="px-4 py-3">
                                        <Actions
                                            id={endpoint.id}
                                            onDelete={deleteEndpoint}
                                        />
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </ConfigurableTable>

                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <p className="text-sm text-muted">
                        Showing {endpoints.from || 0} to {endpoints.to || 0} of{' '}
                        {endpoints.total} endpoints
                    </p>
                    <PaginationLinks links={endpoints.links} />
                </div>
            </div>
        </AdminLayout>
    );
}

function EventList({
    events,
    labels,
}: {
    events: string[];
    labels: Record<string, string>;
}) {
    return (
        <div className="flex max-w-lg flex-wrap gap-1.5">
            {events.map((event) => (
                <span
                    key={event}
                    className="rounded-full border border-primary/30 bg-primary/10 px-2 py-1 text-xs font-medium text-primary"
                >
                    {labels[event] || event}
                </span>
            ))}
        </div>
    );
}

function Actions({
    id,
    onDelete,
}: {
    id: number;
    onDelete: (id: number) => void;
}) {
    return (
        <div className="mt-4 flex gap-2 md:mt-0">
            <Link
                href={`/admin/webhook-endpoints/${id}/edit`}
                className="rounded-md border border-border px-2.5 py-1 text-xs font-medium text-muted hover:bg-surface hover:text-main"
            >
                Edit
            </Link>
            <button
                type="button"
                onClick={() => onDelete(id)}
                className="rounded-md border border-danger/30 px-2.5 py-1 text-xs font-medium text-danger hover:bg-danger/10"
            >
                Delete
            </button>
        </div>
    );
}
