'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as Dialog from '@radix-ui/react-dialog';
import { adminPortalContainer } from '../lib/portal-container.js';
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: "text-foreground hover:text-foreground flex items-center gap-1 text-xs font-medium transition-colors", children: [label, active ? (sortConfig.direction === 'asc' ? (_jsx(ArrowUp, { className: "h-3 w-3" })) : (_jsx(ArrowDown, { className: "h-3 w-3" }))) : (_jsx(ArrowUpDown, { className: "text-muted-foreground h-3 w-3" }))] }));
    }
    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: "text-primary h-6 w-6 animate-spin" }) }));
    }
    return (_jsxs("div", { className: "p-3 pr-6 sm:p-4 sm:pr-8", children: [error && (_jsxs("div", { className: "border-destructive/30 bg-destructive/10 mb-4 flex items-center gap-3 rounded-lg border p-3", children: [_jsx(AlertTriangle, { className: "text-destructive h-5 w-5 shrink-0" }), _jsx("span", { className: "text-destructive flex-1 text-sm", children: error }), _jsx("button", { onClick: refetch, className: "border-destructive/40 text-destructive hover:bg-destructive/15 rounded-lg border px-3 py-1 text-sm transition-colors", children: "Retry" })] })), _jsxs("div", { className: "mb-4 flex items-center justify-between", children: [_jsxs("div", { children: [_jsx("h1", { className: "text-foreground mb-1 text-xl font-medium sm:text-2xl", children: "Redirects" }), _jsxs("p", { className: "text-muted-foreground text-sm", children: [filteredAndSorted.length, " total redirects"] })] }), _jsxs("button", { type: "button", onClick: () => setShowAddDialog(true), className: "bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm transition-colors", children: [_jsx(Plus, { className: "h-4 w-4" }), "Add Redirect"] })] }), _jsx("div", { className: "border-border bg-card mb-4 rounded-lg border", 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: "text-muted-foreground absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2" }), _jsx("input", { type: "text", placeholder: "Search by source or destination URL...", value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), className: "border-input focus:ring-ring w-full rounded-lg border py-2 pr-3 pl-9 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("select", { value: filterType, onChange: (e) => setFilterType(e.target.value), className: "border-input focus:ring-ring rounded-lg border px-3 py-2 text-sm focus:ring-2 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: "bg-muted mb-4 flex h-12 w-12 items-center justify-center rounded-full", children: _jsx(ArrowRightLeft, { className: "text-muted-foreground h-6 w-6" }) }), _jsx("h3", { className: "text-foreground mb-1 text-sm font-medium", children: "No redirects yet" }), _jsx("p", { className: "text-muted-foreground text-sm", children: "Add your first redirect to get started." })] })) : (_jsx("div", { className: "border-border bg-card rounded-lg border", children: _jsx("div", { className: "overflow-x-auto", children: _jsxs("table", { className: "w-full", children: [_jsx("thead", { className: "border-border bg-muted border-b", 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: "text-foreground px-4 py-2 text-left text-xs font-medium", children: "Actions" })] }) }), _jsx("tbody", { className: "divide-border divide-y", children: filteredAndSorted.map((redirect) => (_jsxs("tr", { className: "hover:bg-muted transition-colors", children: [_jsx("td", { className: "px-4 py-3", children: _jsx("code", { className: "bg-muted text-foreground rounded px-2 py-1 text-xs", children: redirect.from }) }), _jsx("td", { className: "px-4 py-3", children: _jsx("code", { className: "bg-muted text-foreground rounded px-2 py-1 text-xs", 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-primary/15 text-primary'
                                                    : 'bg-accent text-accent-foreground'}`, children: redirect.type }) }), _jsx("td", { className: "text-muted-foreground px-4 py-3 text-sm", 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-success/15 text-success'
                                                    : 'bg-muted text-foreground'}`, 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: "hover:bg-muted rounded p-1.5 transition-colors", "aria-label": "Edit redirect", children: _jsx(Pencil, { className: "text-muted-foreground h-4 w-4" }) }), _jsx("button", { type: "button", onClick: () => handleDelete(redirect.id), className: "hover:bg-muted rounded p-1.5 transition-colors", "aria-label": "Delete redirect", children: _jsx(Trash2, { className: "text-destructive h-4 w-4" }) })] }) })] }, redirect.id))) })] }) }) })), _jsx(Dialog.Root, { open: showAddDialog, onOpenChange: setShowAddDialog, children: _jsxs(Dialog.Portal, { container: adminPortalContainer(), children: [_jsx(Dialog.Overlay, { className: "fixed inset-0 z-50 bg-black/50" }), _jsxs(Dialog.Content, { className: "bg-card fixed top-1/2 left-1/2 z-50 w-full max-w-md -translate-x-1/2 -translate-y-1/2 rounded-lg p-6 shadow-lg", children: [_jsx(Dialog.Title, { className: "text-foreground mb-4 text-lg font-medium", children: "Add Redirect" }), _jsxs("form", { onSubmit: handleSubmit, className: "space-y-4", children: [_jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Source URL" }), _jsx("input", { type: "text", value: newRedirect.source, onChange: (e) => setNewRedirect({ ...newRedirect, source: e.target.value }), placeholder: "/old-page", className: "border-input focus:ring-ring w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none", required: true })] }), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Destination URL" }), _jsx("input", { type: "text", value: newRedirect.destination, onChange: (e) => setNewRedirect({ ...newRedirect, destination: e.target.value }), placeholder: "/new-page", className: "border-input focus:ring-ring w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none", required: true })] }), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "Redirect Type" }), _jsxs("select", { value: newRedirect.type, onChange: (e) => setNewRedirect({ ...newRedirect, type: e.target.value }), className: "border-input focus:ring-ring w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 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: "border-input hover:bg-muted rounded-lg border px-4 py-2 text-sm transition-colors", children: "Cancel" }) }), _jsx("button", { type: "submit", className: "bg-primary text-primary-foreground hover:bg-primary/90 rounded-lg px-4 py-2 text-sm transition-colors", children: "Add Redirect" })] })] })] })] }) })] }));
}
//# sourceMappingURL=Redirects.js.map