'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as Dialog from '@radix-ui/react-dialog';
import { Pencil, Plus, Trash2, Search, ArrowUpDown, ArrowUp, ArrowDown, ArrowRightLeft, Loader2, AlertTriangle, } from 'lucide-react';
import { useState, useMemo } from 'react';
import { toast } from 'sonner';
import { sortByRelevance, toggleSort } from '../lib/search.js';
import { useApiData } from '../lib/useApiData.js';
import { cmsApi } from '../lib/api.js';
export function Redirects({ onNavigate }) {
    const { data, loading, error, refetch } = useApiData('/redirects');
    const [showAddDialog, setShowAddDialog] = useState(false);
    const [newRedirect, setNewRedirect] = useState({
        source: '',
        destination: '',
        type: '301',
    });
    const [searchQuery, setSearchQuery] = useState('');
    const [filterType, setFilterType] = useState('all');
    const [sortConfig, setSortConfig] = useState(null);
    const redirects = data ?? [];
    const filteredAndSorted = useMemo(() => {
        let results = redirects.filter((r) => {
            const matchesSearch = (r.from ?? '').toLowerCase().includes(searchQuery.toLowerCase()) ||
                (r.to ?? '').toLowerCase().includes(searchQuery.toLowerCase());
            const matchesType = filterType === 'all' || r.type === filterType;
            return matchesSearch && matchesType;
        });
        if (searchQuery.trim()) {
            results = sortByRelevance(results, searchQuery, (r) => [r.from, r.to]);
        }
        else if (sortConfig) {
            results = [...results].sort((a, b) => {
                let cmp;
                if (sortConfig.key === 'hits') {
                    cmp = a.hits - b.hits;
                }
                else if (sortConfig.key === 'active') {
                    cmp = Number(a.active) - Number(b.active);
                }
                else {
                    cmp = String(a[sortConfig.key]).localeCompare(String(b[sortConfig.key]));
                }
                return sortConfig.direction === 'asc' ? cmp : -cmp;
            });
        }
        return results;
    }, [redirects, searchQuery, filterType, sortConfig]);
    const handleSubmit = async (e) => {
        e.preventDefault();
        const res = await cmsApi('/redirects', {
            method: 'POST',
            body: JSON.stringify({
                from: newRedirect.source,
                to: newRedirect.destination,
                type: newRedirect.type,
            }),
        });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Redirect added');
            refetch();
        }
        setShowAddDialog(false);
    };
    const handleDelete = async (id) => {
        const res = await cmsApi(`/redirects/${id}`, { method: 'DELETE' });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Redirect deleted');
            refetch();
        }
    };
    function SortHeader({ label, sortKey }) {
        const active = sortConfig?.key === sortKey;
        return (_jsxs("button", { type: "button", onClick: () => setSortConfig(toggleSort(sortConfig, sortKey)), className: "flex items-center gap-1 text-xs font-medium text-gray-700 transition-colors hover:text-gray-900", children: [label, active ? (sortConfig.direction === 'asc' ? (_jsx(ArrowUp, { className: "h-3 w-3" })) : (_jsx(ArrowDown, { className: "h-3 w-3" }))) : (_jsx(ArrowUpDown, { className: "h-3 w-3 text-gray-400" }))] }));
    }
    if (loading) {
        return (_jsx("div", { className: "flex h-64 items-center justify-center p-3 pr-6 sm:p-4 sm:pr-8", children: _jsx(Loader2, { className: "h-6 w-6 animate-spin text-blue-600" }) }));
    }
    return (_jsxs("div", { className: "p-3 pr-6 sm:p-4 sm:pr-8", children: [error && (_jsxs("div", { className: "mb-4 flex items-center gap-3 rounded-lg border border-red-200 bg-red-50 p-3", children: [_jsx(AlertTriangle, { className: "h-5 w-5 shrink-0 text-red-600" }), _jsx("span", { className: "flex-1 text-sm text-red-800", children: error }), _jsx("button", { onClick: refetch, className: "rounded-lg border border-red-300 px-3 py-1 text-sm text-red-700 transition-colors hover:bg-red-100", children: "Retry" })] })), _jsxs("div", { className: "mb-4 flex items-center justify-between", children: [_jsxs("div", { children: [_jsx("h1", { className: "mb-1 text-xl font-semibold text-gray-900 sm:text-2xl", children: "Redirects" }), _jsxs("p", { className: "text-sm text-gray-600", children: [filteredAndSorted.length, " total redirects"] })] }), _jsxs("button", { type: "button", onClick: () => setShowAddDialog(true), className: "flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-700", children: [_jsx(Plus, { className: "h-4 w-4" }), "Add Redirect"] })] }), _jsx("div", { className: "mb-4 rounded-lg border border-gray-200 bg-white", children: _jsxs("div", { className: "flex flex-col gap-3 p-3 sm:flex-row", children: [_jsxs("div", { className: "relative flex-1", children: [_jsx(Search, { className: "absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-400" }), _jsx("input", { type: "text", placeholder: "Search by source or destination URL...", value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), className: "w-full rounded-lg border border-gray-300 py-2 pr-3 pl-9 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none" })] }), _jsxs("select", { value: filterType, onChange: (e) => setFilterType(e.target.value), className: "rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none", children: [_jsx("option", { value: "all", children: "All Types" }), _jsx("option", { value: "301", children: "301 (Permanent)" }), _jsx("option", { value: "302", children: "302 (Temporary)" })] })] }) }), filteredAndSorted.length === 0 && !loading ? (_jsxs("div", { className: "flex flex-col items-center justify-center py-16 text-center", children: [_jsx("div", { className: "mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-gray-100", children: _jsx(ArrowRightLeft, { className: "h-6 w-6 text-gray-400" }) }), _jsx("h3", { className: "mb-1 text-sm font-medium text-gray-900", children: "No redirects yet" }), _jsx("p", { className: "text-sm text-gray-500", children: "Add your first redirect to get started." })] })) : (_jsx("div", { className: "rounded-lg border border-gray-200 bg-white", children: _jsx("div", { className: "overflow-x-auto", children: _jsxs("table", { className: "w-full", children: [_jsx("thead", { className: "border-b border-gray-200 bg-gray-50", children: _jsxs("tr", { children: [_jsx("th", { className: "px-4 py-2 text-left", children: _jsx(SortHeader, { label: "Source URL", sortKey: "from" }) }), _jsx("th", { className: "px-4 py-2 text-left", children: _jsx(SortHeader, { label: "Destination URL", sortKey: "to" }) }), _jsx("th", { className: "px-4 py-2 text-left", children: _jsx(SortHeader, { label: "Type", sortKey: "type" }) }), _jsx("th", { className: "px-4 py-2 text-left", children: _jsx(SortHeader, { label: "Hits", sortKey: "hits" }) }), _jsx("th", { className: "px-4 py-2 text-left", children: _jsx(SortHeader, { label: "Status", sortKey: "active" }) }), _jsx("th", { className: "px-4 py-2 text-left text-xs font-medium text-gray-700", children: "Actions" })] }) }), _jsx("tbody", { className: "divide-y divide-gray-200", children: filteredAndSorted.map((redirect) => (_jsxs("tr", { className: "transition-colors hover:bg-gray-50", children: [_jsx("td", { className: "px-4 py-3", children: _jsx("code", { className: "rounded bg-gray-100 px-2 py-1 text-xs text-gray-900", children: redirect.from }) }), _jsx("td", { className: "px-4 py-3", children: _jsx("code", { className: "rounded bg-gray-100 px-2 py-1 text-xs text-gray-900", children: redirect.to }) }), _jsx("td", { className: "px-4 py-3", children: _jsx("span", { className: `inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${redirect.type === '301'
                                                    ? 'bg-blue-100 text-blue-800'
                                                    : 'bg-purple-100 text-purple-800'}`, children: redirect.type }) }), _jsx("td", { className: "px-4 py-3 text-sm text-gray-600", children: redirect.hits.toLocaleString() }), _jsx("td", { className: "px-4 py-3", children: _jsx("span", { className: `inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${redirect.active
                                                    ? 'bg-green-100 text-green-800'
                                                    : 'bg-gray-100 text-gray-800'}`, children: redirect.active ? 'Active' : 'Inactive' }) }), _jsx("td", { className: "px-4 py-3", children: _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { type: "button", onClick: () => onNavigate?.(`/redirects/${redirect.id}/edit`), className: "rounded p-1.5 transition-colors hover:bg-gray-100", "aria-label": "Edit redirect", children: _jsx(Pencil, { className: "h-4 w-4 text-gray-600" }) }), _jsx("button", { type: "button", onClick: () => handleDelete(redirect.id), className: "rounded p-1.5 transition-colors hover:bg-gray-100", "aria-label": "Delete redirect", children: _jsx(Trash2, { className: "h-4 w-4 text-red-600" }) })] }) })] }, redirect.id))) })] }) }) })), _jsx(Dialog.Root, { open: showAddDialog, onOpenChange: setShowAddDialog, children: _jsxs(Dialog.Portal, { children: [_jsx(Dialog.Overlay, { className: "fixed inset-0 z-50 bg-black/50" }), _jsxs(Dialog.Content, { className: "fixed top-1/2 left-1/2 z-50 w-full max-w-md -translate-x-1/2 -translate-y-1/2 rounded-lg bg-white p-6 shadow-lg", children: [_jsx(Dialog.Title, { className: "mb-4 text-lg font-semibold text-gray-900", children: "Add Redirect" }), _jsxs("form", { onSubmit: handleSubmit, className: "space-y-4", children: [_jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Source URL" }), _jsx("input", { type: "text", value: newRedirect.source, onChange: (e) => setNewRedirect({ ...newRedirect, source: e.target.value }), placeholder: "/old-page", className: "w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none", required: true })] }), _jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Destination URL" }), _jsx("input", { type: "text", value: newRedirect.destination, onChange: (e) => setNewRedirect({ ...newRedirect, destination: e.target.value }), placeholder: "/new-page", className: "w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none", required: true })] }), _jsxs("div", { children: [_jsx("label", { className: "mb-1 block text-sm font-medium text-gray-700", children: "Redirect Type" }), _jsxs("select", { value: newRedirect.type, onChange: (e) => setNewRedirect({ ...newRedirect, type: e.target.value }), className: "w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none", children: [_jsx("option", { value: "301", children: "301 (Permanent)" }), _jsx("option", { value: "302", children: "302 (Temporary)" })] })] }), _jsxs("div", { className: "flex items-center justify-end gap-3 pt-4", children: [_jsx(Dialog.Close, { asChild: true, children: _jsx("button", { type: "button", className: "rounded-lg border border-gray-300 px-4 py-2 text-sm transition-colors hover:bg-gray-50", children: "Cancel" }) }), _jsx("button", { type: "submit", className: "rounded-lg bg-blue-600 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-700", children: "Add Redirect" })] })] })] })] }) })] }));
}
//# sourceMappingURL=Redirects.js.map