import { useState } from "react";
import Alert from "react-bootstrap/Alert";
import { LoadingPage } from "src/components";
import { useAuditLogs } from "src/hooks";
import { T } from "src/locale";
import { showEventDetailsModal } from "src/modals";
import Table from "./Table";

export default function TableWrapper() {
	const { isFetching, isLoading, isError, error, data } = useAuditLogs(["user"]);
	const [search, setSearch] = useState("");

	if (isLoading) {
		return <LoadingPage />;
	}

	if (isError) {
		return <Alert variant="danger">{error?.message || "Unknown error"}</Alert>;
	}

	return (
		<div className="card mt-4">
			<div className="card-status-top bg-purple" />
			<div className="card-table">
				<div className="card-header">
					<div className="row w-full align-items-center">
						<div className="col">
							<h2 className="mt-1 mb-0">
								<T id="auditlogs" />
							</h2>
						</div>
						{/* Search box */}
						<div className="col-auto">
							<div className="input-group input-group-sm">
								<span className="input-group-text">
									<svg
										xmlns="http://www.w3.org/2000/svg"
										width="14"
										height="14"
										viewBox="0 0 24 24"
										fill="none"
										stroke="currentColor"
										strokeWidth="2"
										strokeLinecap="round"
										strokeLinejoin="round"
									>
										<circle cx="11" cy="11" r="8" />
										<line x1="21" y1="21" x2="16.65" y2="16.65" />
									</svg>
								</span>
								<input
									type="text"
									className="form-control"
									placeholder="Tìm kiếm..."
									value={search}
									onChange={(e) => setSearch(e.target.value)}
									style={{ minWidth: "180px" }}
								/>
								{search && (
									<button
										type="button"
										className="btn btn-outline-secondary btn-sm"
										onClick={() => setSearch("")}
										title="Xoá tìm kiếm"
									>
										✕
									</button>
								)}
							</div>
						</div>
					</div>
				</div>
				<Table
					data={data ?? []}
					isFetching={isFetching}
					onSelectItem={showEventDetailsModal}
					globalFilter={search}
				/>
			</div>
		</div>
	);
}
