import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { Button } from "../../components/ui/button";
import { MultiSwitchButton } from "../../components/ui/multi-switch-button";
import { Select } from "../../components/ui/select";
import { SearchInput } from "../../components/SearchInput";
import { Loader2, Plus } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { deleteReview } from "../services/reviewsService";
import { CreateReviewDialog } from "./CreateReviewDialog";
import { ReviewCard } from "./ReviewCard";
import { filterReviewList, getReviewerDisplayName, getReviewerKey, normalizeReviewIdentity, } from "./reviewListPresentation";
const statusOptions = [
    { value: "all", label: "All status" },
    { value: "in-progress", label: "In progress" },
    { value: "approved", label: "Approved" },
    { value: "rejected", label: "Rejected" },
    { value: "expired", label: "Expired" },
];
export function ReviewsList({ reviews, loading, error, onSelectReview, onCreateReview, onRefresh, }) {
    const editContext = useEditContext();
    const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
    const [view, setView] = useState("open");
    const [statusFilter, setStatusFilter] = useState("all");
    const [reviewerFilter, setReviewerFilter] = useState("all");
    const [searchTerm, setSearchTerm] = useState("");
    const reviewerOptions = useMemo(() => {
        const reviewersByKey = new Map();
        reviews.forEach((review) => {
            review.reviewers?.forEach((reviewer) => {
                const key = getReviewerKey(reviewer);
                if (key && !reviewersByKey.has(key)) {
                    reviewersByKey.set(key, getReviewerDisplayName(reviewer));
                }
            });
        });
        return [
            { value: "all", label: "All reviewers" },
            ...Array.from(reviewersByKey, ([value, label]) => ({
                value,
                label,
            })).sort((first, second) => first.label.localeCompare(second.label)),
        ];
    }, [reviews]);
    useEffect(() => {
        if (!reviewerOptions.some((option) => option.value === reviewerFilter)) {
            setReviewerFilter("all");
        }
    }, [reviewerFilter, reviewerOptions]);
    const filteredReviews = useMemo(() => filterReviewList(reviews, {
        view,
        status: statusFilter,
        reviewer: reviewerFilter,
        searchTerm,
    }), [reviews, view, statusFilter, reviewerFilter, searchTerm]);
    const canDeleteReview = (review) => {
        const user = editContext?.user;
        if (user?.isLimitedPreviewUser)
            return false;
        return (user?.isAdministrator === true ||
            normalizeReviewIdentity(review.createdBy) ===
                normalizeReviewIdentity(user?.name));
    };
    const handleViewChange = (nextView) => {
        setView(nextView);
        if (nextView === "open" &&
            statusFilter !== "all" &&
            statusFilter !== "in-progress") {
            setStatusFilter("all");
        }
    };
    const handleDeleteClick = (reviewId, event) => {
        event.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);
                    await onRefresh?.();
                }
                catch (deleteError) {
                    console.error("Failed to delete review:", deleteError);
                }
            },
        });
    };
    const handleCreateReview = () => {
        onCreateReview();
        setIsCreateDialogOpen(true);
    };
    const isInitialLoading = loading && reviews.length === 0;
    const canCreateReview = !editContext?.user?.isLimitedPreviewUser;
    const hasActiveFilters = !!searchTerm || statusFilter !== "all" || reviewerFilter !== "all";
    return (_jsxs("div", { className: "flex h-full flex-col bg-white", children: [_jsxs("div", { className: "space-y-3 p-3", children: [canCreateReview && (_jsxs(Button, { variant: "outline", size: "lg", onClick: handleCreateReview, "data-testid": "create-review-button", className: "h-11 w-full rounded-[4px] text-sm font-medium", children: ["Request a review", _jsx(Plus, { className: "h-5 w-5", strokeWidth: 1 })] })), _jsx(SearchInput, { placeholder: "Search ...", value: searchTerm, onChange: setSearchTerm, className: "w-full", inputClassName: "bg-neutral-grey-5 h-10 rounded-lg border-transparent px-3 pl-10 text-sm", searchIconClassName: "left-3.5 h-5 w-5", size: "lg", testId: "reviews-search-input" }), _jsx(MultiSwitchButton, { value: view, onValueChange: handleViewChange, options: [
                            { value: "open", label: "Open reviews" },
                            { value: "all", label: "All reviews" },
                        ], className: "w-full", optionClassName: "h-8 text-xs", "aria-label": "Review list", testId: "reviews-list-view-switch" }), _jsxs("div", { className: "grid grid-cols-2 gap-2", children: [_jsx(Select, { value: statusFilter, onValueChange: (value) => setStatusFilter(value), options: statusOptions, className: "h-9 rounded-lg px-3", "data-testid": "reviews-status-filter" }), _jsx(Select, { value: reviewerFilter, onValueChange: setReviewerFilter, options: reviewerOptions, className: "h-9 rounded-lg px-3", maxWidth: 280, "data-testid": "reviews-reviewer-filter" })] })] }), _jsx("div", { className: "relative min-h-0 flex-1", children: _jsxs("div", { className: "absolute inset-0 overflow-auto px-3 pb-3", children: [error && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red mb-3 rounded-lg border p-3 text-xs", children: error })), isInitialLoading ? (_jsx("div", { className: "flex h-full items-center justify-center", children: _jsx(Loader2, { strokeWidth: 1, className: "text-neutral-grey-50 h-7 w-7 animate-spin" }) })) : filteredReviews.length === 0 ? (_jsx("div", { className: "text-neutral-grey-50 flex h-full items-center justify-center px-6 text-center text-xs", children: hasActiveFilters
                                ? "No reviews match these filters"
                                : view === "open"
                                    ? "No open reviews"
                                    : "No reviews found" })) : (_jsx("div", { className: "flex flex-col gap-2.5", children: filteredReviews.map((review) => (_jsx(ReviewCard, { review: review, currentUser: editContext?.user, onClick: onSelectReview, onDelete: handleDeleteClick, canDelete: canDeleteReview(review) }, review.reviewId))) }))] }) }), canCreateReview && isCreateDialogOpen && (_jsx(CreateReviewDialog, { open: isCreateDialogOpen, onOpenChange: setIsCreateDialogOpen, onCreated: async (reviewId) => {
                    setIsCreateDialogOpen(false);
                    await onRefresh?.();
                    if (reviewId)
                        onSelectReview(reviewId);
                } }))] }));
}
//# sourceMappingURL=ReviewsList.js.map