import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from "react";
import { SimpleToolbar } from "../ui/SimpleToolbar";
import { ReviewCard } from "./ReviewCard";
import { SimpleIconButton } from "../ui/SimpleIconButton";
import { Plus, Loader2 } from "lucide-react";
import { DeleteIcon } from "../../components/ui/delete-icon";
import { CreateReviewDialog } from "./CreateReviewDialog";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { Checkbox } from "../../components/ui/checkbox";
import { useEditContext } from "../client/editContext";
import { deleteReview, deleteReviews } from "../services/reviewsService";
export function ReviewsList({ reviews, loading, error, onSelectReview, onCreateReview, onRefresh, }) {
    const editContext = useEditContext();
    const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState("");
    const [selectedReviewIds, setSelectedReviewIds] = useState(new Set());
    const [isDeleting, setIsDeleting] = useState(false);
    const filteredReviews = reviews.filter((review) => {
        if (!searchTerm)
            return true;
        const searchLower = searchTerm.toLowerCase();
        return (review.title?.toLowerCase().includes(searchLower) ||
            review.createdBy.toLowerCase().includes(searchLower));
    });
    const allFilteredSelected = filteredReviews.length > 0 &&
        filteredReviews.every((review) => selectedReviewIds.has(review.reviewId));
    const someFilteredSelected = filteredReviews.some((review) => selectedReviewIds.has(review.reviewId));
    const selectAllChecked = allFilteredSelected
        ? true
        : someFilteredSelected
            ? "indeterminate"
            : false;
    const handleSelectAll = (checked) => {
        if (checked) {
            const newSelected = new Set(selectedReviewIds);
            filteredReviews.forEach((review) => {
                newSelected.add(review.reviewId);
            });
            setSelectedReviewIds(newSelected);
        }
        else {
            const newSelected = new Set(selectedReviewIds);
            filteredReviews.forEach((review) => {
                newSelected.delete(review.reviewId);
            });
            setSelectedReviewIds(newSelected);
        }
    };
    const handleSelectReview = (reviewId, checked) => {
        const newSelected = new Set(selectedReviewIds);
        if (checked) {
            newSelected.add(reviewId);
        }
        else {
            newSelected.delete(reviewId);
        }
        setSelectedReviewIds(newSelected);
    };
    const handleDeleteSelected = () => {
        const selectedCount = selectedReviewIds.size;
        editContext?.confirm({
            header: "Delete Selected Reviews",
            message: `Are you sure you want to delete ${selectedCount} review${selectedCount > 1 ? "s" : ""}?`,
            acceptLabel: "Delete",
            showCancel: true,
            accept: async () => {
                try {
                    setIsDeleting(true);
                    // Delete all selected reviews in a single API request
                    await deleteReviews(Array.from(selectedReviewIds));
                    setSelectedReviewIds(new Set());
                    if (onRefresh) {
                        await onRefresh();
                    }
                }
                catch (err) {
                    console.error("Failed to delete reviews:", err);
                    // You might want to show an error message here
                }
                finally {
                    setIsDeleting(false);
                }
            },
        });
    };
    const handleDeleteClick = (reviewId, e) => {
        e.stopPropagation();
        editContext?.confirm({
            header: "Delete Review",
            message: "Are you sure you want to delete this review?",
            acceptLabel: "Delete",
            showCancel: true,
            accept: async () => {
                try {
                    await deleteReview(reviewId);
                    if (onRefresh) {
                        await onRefresh();
                    }
                }
                catch (err) {
                    console.error("Failed to delete review:", err);
                    // You might want to show an error message here
                }
            },
        });
    };
    const isInitialLoading = loading && reviews.length === 0;
    return (_jsxs("div", { className: "flex h-full flex-col", children: [_jsxs(SimpleToolbar, { children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(SimpleIconButton, { label: "Create Review", icon: _jsx(Plus, { className: "h-4 w-4" }), onClick: () => setIsCreateDialogOpen(true), "data-testid": "create-review-button" }), filteredReviews.length > 0 && (_jsxs("div", { className: "border-border-default ml-1 flex items-center gap-1.5 border-l pl-2", children: [_jsx(Checkbox, { id: "select-all-reviews", checked: selectAllChecked, onCheckedChange: (checked) => handleSelectAll(checked === true), className: "h-3.5 w-3.5" }), _jsx("label", { htmlFor: "select-all-reviews", className: "text-neutral-grey-50 cursor-pointer text-[11px] font-medium whitespace-nowrap", children: "Select All" })] }))] }), selectedReviewIds.size > 0 && (_jsx(Button, { variant: "outline", size: "sm", onClick: handleDeleteSelected, className: "text-neutral-grey-50 hover:bg-neutral-grey-5 h-7 px-2 text-[11px]", disabled: isDeleting, children: isDeleting ? (_jsx(Loader2, { className: "h-3 w-3 animate-spin" })) : (_jsxs(_Fragment, { children: [_jsx(DeleteIcon, { size: "md", className: "mr-1.5" }), _jsxs("span", { children: ["Delete (", selectedReviewIds.size, ")"] })] })) })), _jsx("div", { className: "ml-auto flex max-w-[150px] items-center gap-2 sm:max-w-[200px]", children: _jsx(Input, { placeholder: "Search...", value: searchTerm, onChange: (e) => setSearchTerm(e.target.value), className: "h-7 text-xs" }) })] }), _jsx("div", { className: "relative flex-1", children: _jsxs("div", { className: "absolute inset-0 overflow-auto", children: [error && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red m-3 rounded border p-3 text-xs", children: error })), isInitialLoading ? (_jsx("div", { className: "flex h-full items-center justify-center", children: _jsx(Loader2, { className: "h-8 w-8 animate-spin" }) })) : filteredReviews.length === 0 ? (_jsx("div", { className: "text-neutral-grey-50 flex h-full items-center justify-center text-xs", children: searchTerm ? "No matches found" : "No reviews found" })) : (_jsx("div", { className: "flex flex-col gap-3 p-3", children: filteredReviews.map((review) => {
                                const isCreator = review.createdBy === editContext?.user?.name;
                                const isLimitedPreviewUser = editContext?.user?.isLimitedPreviewUser ?? false;
                                const isAdministrator = editContext?.user?.isAdministrator ?? false;
                                const canDelete = !isLimitedPreviewUser && (isCreator || isAdministrator);
                                return (_jsx(ReviewCard, { review: review, isSelected: selectedReviewIds.has(review.reviewId), onSelect: handleSelectReview, onClick: onSelectReview, onDelete: handleDeleteClick, canDelete: canDelete }, review.reviewId));
                            }) }))] }) }), isCreateDialogOpen && (_jsx(CreateReviewDialog, { open: isCreateDialogOpen, onOpenChange: setIsCreateDialogOpen, onCreated: async (reviewId) => {
                    setIsCreateDialogOpen(false);
                    // Refresh the reviews list
                    if (onRefresh) {
                        await onRefresh();
                    }
                    if (reviewId) {
                        onSelectReview(reviewId);
                    }
                } }))] }));
}
//# sourceMappingURL=ReviewsList.js.map