import { useEffect, useMemo, useRef, useState } from 'react';
import { FolderPlus, Layers, Plus, Search, ChevronRight, X, Check } from 'lucide-react';
import { Modal } from '@/Components/Proto/UI/Modal';

/**
 * To Project picker — ONE component, THREE modes, one look.
 * Crisp white theme with light grey selection highlights instead of purple.
 *
 * | `mode`            | shows                                   | emits                        |
 * |-------------------|-----------------------------------------|------------------------------|
 * | `'both'` DEFAULT  | project cards + their detail tables      | `{id, detailId, title}`      |
 * | `'project'`       | project cards ONLY (no detail table)     | `{id, detailId: null, title}`|
 * | `'detail'`        | the detail table of ONE project + New    | `{id, detailId, title}`      |
 *
 * Every mode can also emit `null` — the footer's "Clear Selection", shown once there is
 * something to clear. A caller that treats `null` as "nothing happened" will look broken.
 *
 * `'both'` is the ORIGINAL behaviour and the default — Quotation
 * (`MenuQuotations/Quotations/QuotationProductModal` + its Proto copy) picks a project and a
 * detail in one go and must keep rendering exactly as before. Do not make another mode the
 * default.
 *
 * Sample Order splits the same picking into two steps (user decision 2026-08-10): the ORDER
 * INFORMATION header picks the project (`'project'` — legacy `selectProject(id)`,
 * createsampleorder.php:2162) and each PRODUCT ROW then picks its detail under that project
 * (`'detail'` — legacy `selToProjectDetail[]`, :1312). The detail table is the same markup in
 * both modes; only what the modal is scoped to and what it emits differ.
 *
 * `lineApplicationId` narrows the pickable details to the ones whose Application matches the
 * line — legacy did this by rebuilding the detail <select> from
 * itemtoprojectdetails[project][application] (createquotation.php:2904). Non-matching details
 * are DISABLED rather than hidden: hiding them leaves a card that advertises "3 details" above
 * an empty table, which reads as a bug instead of a rule.
 *
 * Pass `undefined` to switch the narrowing off entirely (the Proto copy of the product modal
 * does not know about applications). `''` means "no Application chosen yet" — then only
 * unclassified details remain pickable, mirroring the legacy `el2.value != "0"` gate. In
 * `'project'` mode the narrowing is off by construction: there is no single line to narrow
 * against, so every project stays pickable.
 *
 * `'detail'` mode needs `projectId` (which project's details to list) and optionally
 * `selectedDetailId` (`'new'` | number) to mark the current pick. `selected` stays the PROJECT
 * id in the other two modes.
 */
export function ToProjectModal({
    open,
    onClose,
    onSelect,
    selected,
    projects = [],
    lineApplicationId,
    mode = 'both',
    projectId = null,
    selectedDetailId = null,
}) {
    const [search, setSearch] = useState('');
    const [activeRow, setActiveRow] = useState(0);
    // Show only the first few projects; the rest sit behind a "view more" (user 2026-08-05) —
    // a long list used to make this dialog as tall as the screen.
    const [expanded, setExpanded] = useState(false);
    const bodyRef = useRef(null);

    const detailMode = mode === 'detail';
    const projectMode = mode === 'project';

    // Group projects by projectId
    const grouped = useMemo(() => {
        const list = [];
        (projects || []).forEach((r) => {
            let g = list.find((x) => x.id === r.projectId);
            if (!g) {
                g = { id: r.projectId, title: r.projectTitle, details: [] };
                list.push(g);
            }
            let d = g.details.find((x) => x.id === r.detailId);
            if (!d) {
                d = {
                    id: r.detailId,
                    application: r.application,
                    applicationId: r.applicationId ?? null,
                    ccProducts: [],
                    compProduct: r.compProduct,
                };
                g.details.push(d);
            }
            if (r.ccProduct && !d.ccProducts.includes(r.ccProduct)) {
                d.ccProducts.push(r.ccProduct);
            }
        });
        return list;
    }, [projects]);

    // Detail mode picks INSIDE one project, so the card list collapses to that project. A
    // project whose cc lines were all removed still has to offer "New Detail", hence the
    // empty stand-in rather than an empty list.
    const scoped = useMemo(() => {
        if (!detailMode) return grouped;
        const own = grouped.filter((g) => String(g.id) === String(projectId));
        return own.length ? own : [{ id: projectId, title: '', details: [] }];
    }, [grouped, detailMode, projectId]);

    const q = search.toLowerCase().trim();
    const filtered = useMemo(() => {
        const has = (v) => String(v ?? '').toLowerCase().includes(q);
        if (!q) return scoped;
        // With the project already fixed, the query narrows its DETAILS instead of the card
        // list — the card itself stays so "New Detail" never disappears behind a search.
        if (detailMode) {
            return scoped.map((g) => ({
                ...g,
                details: g.details.filter(
                    (d) => has(d.id) || has(d.application) || has(d.compProduct) || d.ccProducts.some(has)
                ),
            }));
        }
        return scoped.filter(
            (g) =>
                has(g.id) ||
                has(g.title) ||
                g.details.some(
                    (d) => has(d.id) || has(d.application) || has(d.compProduct) || d.ccProducts.some(has)
                )
        );
    }, [scoped, q, detailMode]);

    // Project-only picking has no line Application to narrow against — what you pick is the
    // project, so none of its details may be greyed out (they are not even rendered).
    const narrowing = !projectMode && lineApplicationId !== undefined;
    const lineAppId = lineApplicationId === '' || lineApplicationId == null ? null : Number(lineApplicationId);

    // While searching, show every match (the query is already the narrowing); otherwise cap.
    const VISIBLE_LIMIT = 4;
    const visible = q || expanded ? filtered : filtered.slice(0, VISIBLE_LIMIT);
    const hiddenCount = filtered.length - visible.length;

    /**
     * Stamps every row with its keyboard-nav index and builds the flat ↑↓/Enter list in the
     * SAME pass — disabled details take no index, so the arrow keys skip them instead of
     * landing on a row that Enter cannot select.
     *
     * Walks the VISIBLE subset, not `filtered`: rows still hidden behind "view more" must not
     * take a nav index either, or the arrow keys would land on a card that is not on screen.
     *
     * In `'project'` mode a whole CARD is the single selectable row; in the other two modes
     * each detail row is selectable plus one "New Detail" row per card.
     */
    const view = useMemo(() => {
        let idx = 0;
        const items = [];
        const groups = visible.map((g) => {
            if (projectMode) {
                const navIdx = idx++;
                items.push({ type: 'project', id: g.id, detailId: null, title: g.title });
                // Recognition summary for a card that no longer shows its detail table.
                const applications = [...new Set(g.details.map((d) => d.application).filter(Boolean))];

                return { ...g, navIdx, applications };
            }

            const details = g.details.map((d) => {
                // A NULL application is unclassified, never in conflict — always pickable.
                const pickable = !narrowing || d.applicationId == null || d.applicationId === lineAppId;
                const navIdx = pickable ? idx++ : -1;
                if (pickable) items.push({ type: 'detail', id: g.id, detailId: d.id, title: g.title });

                return { ...d, pickable, navIdx };
            });
            const newIdx = idx++;
            items.push({ type: 'new_detail', id: g.id, detailId: 'new', title: g.title });

            return { ...g, details, newIdx };
        });

        return { groups, items };
    }, [visible, narrowing, lineAppId, projectMode]);

    const selectable = view.items;
    // Detail mode has exactly one card; its "New Detail" action is promoted to the footer so
    // the dialog keeps a single, gradient primary the way the project mode does.
    const detailGroup = detailMode ? view.groups[0] : null;

    useEffect(() => {
        setActiveRow((i) => (selectable.length === 0 ? -1 : Math.min(Math.max(i, 0), selectable.length - 1)));
    }, [selectable.length]);

    useEffect(() => {
        if (activeRow < 0) return;
        bodyRef.current?.querySelector(`[data-row-idx="${activeRow}"]`)?.scrollIntoView({ block: 'nearest' });
    }, [activeRow]);

    const handleClose = () => {
        setSearch('');
        setActiveRow(0);
        setExpanded(false);
        onClose();
    };

    const emit = (payload) => {
        onSelect(payload);
        setSearch('');
        setActiveRow(0);
        setExpanded(false);
        onClose();
    };

    const onSearchKeyDown = (e) => {
        const last = selectable.length - 1;
        if (last < 0) return;
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            setActiveRow((i) => Math.min(i + 1, last));
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            setActiveRow((i) => Math.max(i - 1, 0));
        } else if (e.key === 'Home') {
            e.preventDefault();
            setActiveRow(0);
        } else if (e.key === 'End') {
            e.preventDefault();
            setActiveRow(last);
        } else if (e.key === 'Enter') {
            e.preventDefault();
            if (activeRow >= 0 && selectable[activeRow]) {
                const item = selectable[activeRow];
                emit({ id: item.id, detailId: item.detailId, title: item.title });
            }
        }
    };

    const isDetailPicked = (id) => detailMode && selectedDetailId != null && String(selectedDetailId) === String(id);
    // Wording follows the caller: 'both' is Quotation's, and its copy must not drift.
    const mismatchTitle = detailMode
        ? 'Application detail ini berbeda dengan Application baris ini.'
        : 'Application detail ini berbeda dengan Application baris quotation.';

    return (
        <Modal open={open} onClose={handleClose} size="w-[min(720px,100%)] max-w-[720px] max-h-[min(560px,calc(100vh-64px))]" labelledBy="toProjectModalTitle">
            {/* Header */}
            <header className="flex items-center justify-between gap-3 border-b border-border bg-card px-5 py-3">
                <div className="flex items-center gap-2.5">
                    <span className="grid size-7 shrink-0 place-items-center rounded-lg bg-accent text-primary">
                        {detailMode ? <Layers className="size-4" strokeWidth={1.8} /> : <FolderPlus className="size-4" strokeWidth={1.8} />}
                    </span>
                    <h2 id="toProjectModalTitle" className="m-0 text-sm font-bold text-card-foreground">
                        {detailMode ? 'Select Project Detail' : 'Select Project'}
                    </h2>
                </div>
                <button
                    type="button"
                    onClick={handleClose}
                    className="grid size-7 place-items-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
                    aria-label="Close"
                >
                    <X className="size-4.5" />
                </button>
            </header>

            {/* Body */}
            <div className="flex min-h-0 flex-1 flex-col gap-3 bg-card px-5 py-4 overflow-hidden">
                <div className="relative flex items-center">
                    <Search className="pointer-events-none absolute left-3 size-3.5 text-muted-foreground" />
                    <input
                        data-autofocus
                        type="search"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        onKeyDown={onSearchKeyDown}
                        placeholder={detailMode ? 'Cari detail, application, atau product…' : 'Cari project, ID, application, atau product…'}
                        autoComplete="off"
                        className="h-9 w-full rounded-lg border border-input bg-card pl-9 pr-9 text-xs font-medium text-foreground outline-none transition-colors placeholder:text-muted-foreground/70 focus:border-primary focus:ring-1 focus:ring-primary"
                    />
                    {search && (
                        <button
                            type="button"
                            onClick={() => setSearch('')}
                            className="absolute right-3 text-muted-foreground hover:text-foreground"
                        >
                            <X className="size-3.5" />
                        </button>
                    )}
                </div>

                {narrowing && lineAppId === null && (
                    <p className="m-0 rounded-lg border border-dashed border-border bg-secondary/30 px-3 py-2 text-[11px] font-medium text-muted-foreground">
                        Pilih Application dulu untuk memilih detail yang sudah ada. Tanpa Application, hanya
                        detail tanpa Application dan pembuatan project/detail baru yang tersedia.
                    </p>
                )}

                <div ref={bodyRef} className="flex-1 overflow-auto space-y-3 pr-1">
                    {view.groups.length === 0 ? (
                        <div className="rounded-xl border border-dashed border-border p-8 text-center text-xs italic text-muted-foreground bg-card">
                            Tidak ada project yang sesuai dengan pencarian.
                        </div>
                    ) : (
                        view.groups.map((g) => {
                            const isProjectSelected = !detailMode && selected === g.id;

                            /* MODE A — the card IS the control: one project, no detail table.
                               A real <button> so Enter/Space pick it like the ↑↓ list does. */
                            if (projectMode) {
                                const isActive = activeRow === g.navIdx;

                                return (
                                    <article
                                        key={g.id}
                                        className={`overflow-hidden rounded-xl border transition-colors bg-card ${
                                            isProjectSelected ? 'border-neutral-300 dark:border-neutral-700 shadow-2xs' : 'border-border'
                                        }`}
                                    >
                                        <button
                                            type="button"
                                            data-row-idx={g.navIdx}
                                            onClick={() => emit({ id: g.id, detailId: null, title: g.title })}
                                            className={`group flex w-full items-center gap-3 px-4 py-3 text-left transition-colors ${
                                                isActive ? 'bg-secondary/70' : 'bg-card hover:bg-secondary/40'
                                            }`}
                                        >
                                            <span className="min-w-0 flex-1">
                                                <span className="flex min-w-0 items-center gap-2">
                                                    <span className="inline-flex shrink-0 items-center rounded-md border border-border/80 bg-card px-2 py-0.5 text-xs font-bold text-foreground tabular-nums">
                                                        Project #{g.id}
                                                    </span>
                                                    {g.title && (
                                                        <span className="truncate text-xs font-bold text-foreground">{g.title}</span>
                                                    )}
                                                    {isProjectSelected && (
                                                        <span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] font-bold text-emerald-600 dark:text-emerald-400">
                                                            <Check className="size-3" /> Selected
                                                        </span>
                                                    )}
                                                </span>
                                                {/* Enough to recognise the project without its table:
                                                    how many details it holds and what they are for. */}
                                                <span className="mt-1 block truncate text-[11px] font-medium text-muted-foreground">
                                                    {g.details.length} detail{g.details.length === 1 ? '' : 's'}
                                                    {g.applications.length > 0 && (
                                                        <> · {g.applications.slice(0, 3).join(', ')}
                                                        {g.applications.length > 3 ? ` +${g.applications.length - 3}` : ''}</>
                                                    )}
                                                </span>
                                            </span>
                                            <span
                                                className={`inline-flex shrink-0 items-center gap-1 rounded-lg border px-2.5 py-1 text-xs font-semibold transition-colors ${
                                                    isActive
                                                        ? 'border-neutral-400 bg-secondary text-foreground font-bold'
                                                        : 'border-input bg-card text-foreground group-hover:border-neutral-400 group-hover:bg-secondary'
                                                }`}
                                            >
                                                Select <ChevronRight className="size-3" />
                                            </span>
                                        </button>
                                    </article>
                                );
                            }

                            /* MODE B + the original both-at-once mode — same detail table. */
                            const isNewActive = activeRow === g.newIdx;

                            return (
                                <article
                                    key={g.id ?? 'new'}
                                    className={`overflow-hidden rounded-xl border transition-colors bg-card ${
                                        isProjectSelected ? 'border-neutral-300 dark:border-neutral-700 bg-secondary/20 shadow-2xs' : 'border-border'
                                    }`}
                                >
                                    {/* Card Header — Crisp White */}
                                    <div className="flex items-center justify-between gap-3 border-b border-border bg-card px-4 py-3">
                                        <div className="flex items-center gap-2 min-w-0">
                                            {/* `detail` mode under a project that does not exist yet (the caller picked
                                                "Insert New Project" upstream) has no id to print — "Project #" alone
                                                reads as a rendering bug. Dead branch in `both` mode: those cards are
                                                grouped from real rows and always carry an id. */}
                                            <span className="inline-flex items-center rounded-md border border-border/80 bg-card px-2 py-0.5 text-xs font-bold text-foreground tabular-nums">
                                                {g.id == null ? 'New Project' : `Project #${g.id}`}
                                            </span>
                                            {g.title && (
                                                <span className="truncate text-xs font-bold text-foreground">
                                                    {g.title}
                                                </span>
                                            )}
                                            {isProjectSelected && (
                                                <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] font-bold text-emerald-600 dark:text-emerald-400">
                                                    <Check className="size-3" /> Selected
                                                </span>
                                            )}
                                            <span className="text-[11px] font-medium text-muted-foreground">
                                                ({g.details.length} detail{g.details.length === 1 ? '' : 's'})
                                            </span>
                                        </div>

                                        {/* Detail mode promotes New Detail to the footer — the card header
                                            would be the second copy of the same action. */}
                                        {!detailMode && (
                                            <button
                                                type="button"
                                                data-row-idx={g.newIdx}
                                                onClick={() => emit({ id: g.id, detailId: 'new', title: g.title })}
                                                className={`inline-flex items-center gap-1 rounded-lg border px-2.5 py-1 text-xs font-semibold transition-colors ${
                                                    isNewActive
                                                        ? 'border-neutral-400 bg-secondary text-foreground font-bold'
                                                        : 'border-input bg-card text-foreground hover:bg-secondary'
                                                }`}
                                            >
                                                <Plus className="size-3.5" />
                                                <span>New Detail</span>
                                            </button>
                                        )}
                                    </div>

                                    {/* Details Table — Crisp White */}
                                    <div className="overflow-x-auto bg-card">
                                        <table className="w-full text-left text-[12px] bg-card">
                                            <thead>
                                                <tr className="border-b border-border/60 bg-card text-[10px] font-bold uppercase tracking-wide text-muted-foreground">
                                                    <th className="px-4 py-2 w-[90px] bg-card">Detail ID</th>
                                                    <th className="px-4 py-2 bg-card">Application</th>
                                                    <th className="px-4 py-2 bg-card">CC Products</th>
                                                    <th className="px-4 py-2 bg-card">Comp Product</th>
                                                    <th className="px-4 py-2 text-right w-[100px] bg-card">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody className="divide-y divide-border/40 bg-card">
                                                {g.details.length === 0 && (
                                                    <tr>
                                                        <td colSpan={5} className="px-4 py-6 text-center text-[11px] italic text-muted-foreground">
                                                            {q
                                                                ? 'Tidak ada detail yang sesuai dengan pencarian.'
                                                                : 'Project ini belum punya detail — pilih New Detail.'}
                                                        </td>
                                                    </tr>
                                                )}
                                                {g.details.map((d) => {
                                                    const isActive = d.pickable && activeRow === d.navIdx;
                                                    const picked = isDetailPicked(d.id);

                                                    return (
                                                        <tr
                                                            key={d.id}
                                                            data-row-idx={d.pickable ? d.navIdx : undefined}
                                                            aria-disabled={!d.pickable}
                                                            title={d.pickable ? undefined : mismatchTitle}
                                                            onClick={
                                                                d.pickable
                                                                    ? () => emit({ id: g.id, detailId: d.id, title: g.title })
                                                                    : undefined
                                                            }
                                                            className={`group transition-colors ${
                                                                !d.pickable
                                                                    ? 'cursor-not-allowed bg-card opacity-45'
                                                                    : isActive
                                                                      ? 'cursor-pointer bg-secondary/70 font-semibold'
                                                                      : 'cursor-pointer bg-card hover:bg-secondary/40'
                                                            }`}
                                                        >
                                                            <td className="px-4 py-2.5 font-bold tabular-nums text-foreground">
                                                                #{d.id}
                                                            </td>
                                                            <td className="px-4 py-2.5 font-medium text-foreground">
                                                                {d.application || <span className="text-muted-foreground/40">—</span>}
                                                            </td>
                                                            <td className="px-4 py-2.5">
                                                                <div className="flex flex-wrap gap-1">
                                                                    {d.ccProducts?.length ? (
                                                                        d.ccProducts.map((cc, cci) => (
                                                                            <span
                                                                                key={cci}
                                                                                className="inline-flex items-center rounded-md border border-border/70 bg-card px-2 py-0.5 text-[11px] font-medium text-foreground shadow-2xs"
                                                                            >
                                                                                {cc}
                                                                            </span>
                                                                        ))
                                                                    ) : (
                                                                        <span className="text-muted-foreground/40">—</span>
                                                                    )}
                                                                </div>
                                                            </td>
                                                            <td className="px-4 py-2.5 text-muted-foreground">
                                                                {d.compProduct || <span className="text-muted-foreground/40">—</span>}
                                                            </td>
                                                            <td className="px-4 py-2.5 text-right">
                                                                {!d.pickable ? (
                                                                    <span className="text-[11px] font-semibold italic text-muted-foreground">
                                                                        Application lain
                                                                    </span>
                                                                ) : picked ? (
                                                                    <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-1 text-[10px] font-bold text-emerald-600 dark:text-emerald-400">
                                                                        <Check className="size-3" /> Selected
                                                                    </span>
                                                                ) : (
                                                                    <span
                                                                        className={`inline-flex items-center gap-1 rounded-lg border px-2.5 py-1 text-xs font-semibold transition-colors ${
                                                                            isActive
                                                                                ? 'border-neutral-400 bg-secondary text-foreground font-bold'
                                                                                : 'border-input bg-card text-foreground group-hover:border-neutral-400 group-hover:bg-secondary'
                                                                        }`}
                                                                    >
                                                                        Select <ChevronRight className="size-3" />
                                                                    </span>
                                                                )}
                                                            </td>
                                                        </tr>
                                                    );
                                                })}
                                            </tbody>
                                        </table>
                                    </div>
                                </article>
                            );
                        })
                    )}

                    {/* View more — the rest of the list stays collapsed until asked for. */}
                    {hiddenCount > 0 && (
                        <button
                            type="button"
                            onClick={() => setExpanded(true)}
                            className="flex w-full items-center justify-center gap-1.5 rounded-lg border border-dashed border-border py-2 text-xs font-semibold text-muted-foreground transition-colors hover:border-primary hover:text-primary"
                        >
                            Lihat {hiddenCount} project lainnya
                            <ChevronRight className="size-3.5 rotate-90" />
                        </button>
                    )}
                </div>

                <div className="flex items-center justify-between pt-0.5 text-[11px] text-muted-foreground">
                    <span>
                        {detailMode
                            ? `Menampilkan ${detailGroup?.details.length ?? 0} detail`
                            : `Menampilkan ${visible.length} dari ${grouped.length} project`}
                    </span>
                    <span className="italic">↑↓ berpindah · Enter memilih</span>
                </div>
            </div>

            {/* Footer — ONE left-aligned action row, primary first (ui-conventions.md: no
                action row sits on the right anywhere in the app; Cancel joins the same group
                instead of facing it from the far edge). The primary is the "make a new one"
                escape hatch of whichever step this is: a new PROJECT while picking projects,
                a new DETAIL while picking details. */}
            <footer className="flex flex-wrap items-center gap-2.5 border-t border-border bg-card px-5 py-3">
                {detailMode ? (
                    <button
                        type="button"
                        data-row-idx={detailGroup?.newIdx}
                        onClick={() => emit({ id: detailGroup?.id ?? projectId, detailId: 'new', title: detailGroup?.title ?? '' })}
                        className={`inline-flex h-9 items-center justify-center gap-1.5 rounded-lg bg-linear-to-br from-violet-500 to-primary px-4 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105 ${
                            activeRow === detailGroup?.newIdx ? 'ring-2 ring-primary/40' : ''
                        }`}
                    >
                        {isDetailPicked('new') ? <Check className="size-3.5" /> : <Plus className="size-3.5" />} New Detail
                    </button>
                ) : (
                    <button
                        type="button"
                        onClick={() => emit({ id: 'new', detailId: projectMode ? null : 'new', title: 'New Project' })}
                        className="inline-flex h-9 items-center justify-center gap-1.5 rounded-lg bg-linear-to-br from-violet-500 to-primary px-4 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105"
                    >
                        <Plus className="size-3.5" /> Insert New Project
                    </button>
                )}
                {/* Clearing is available at BOTH steps. At the detail step it is NOT the same as
                    New Detail: since the per-row "link this line" checkbox was dropped, having no
                    detail pick IS the way a line opts out of the project, so the picker must be
                    able to reach that state — not only the X on the caller's trigger. `emit(null)`
                    is what every caller reads as "cleared". */}
                {(detailMode ? selectedDetailId != null : Boolean(selected)) ? (
                    <button
                        type="button"
                        onClick={() => emit(null)}
                        className="inline-flex h-9 items-center justify-center rounded-lg border border-input bg-card px-4 text-xs font-semibold text-foreground transition-colors hover:border-primary hover:text-primary"
                    >
                        Clear Selection
                    </button>
                ) : null}
                <button
                    type="button"
                    onClick={handleClose}
                    className="inline-flex h-9 items-center justify-center rounded-lg border border-input bg-card px-4 text-xs font-semibold text-foreground transition-colors hover:bg-muted"
                >
                    Cancel
                </button>
            </footer>
        </Modal>
    );
}
