import StyledTable from "@/Components/Admin/ui/StyledTable";
import { useEffect, useState, useRef } from "react";
import { router, usePage } from '@inertiajs/react';
import { toast, Toaster } from "react-hot-toast";
import DeleteConfirmationModal from "@/Components/Admin/ui/DeleteConfirmationModal";

export default function Review({ reviews, pagination }) {
    const { flash } = usePage().props;
    const processedMessages = useRef(new Set());
    
    const [reviewData, setReviewData] = useState([]);
    const [deleteModal, setDeleteModal] = useState({ show: false, review: null });

    useEffect(() => {
        if (flash?.success) {
            const message = typeof flash.success === 'object' ? flash.success.message : flash.success;
            if (message && !processedMessages.current.has(`success-${message}`)) {
                toast.success(message);
                processedMessages.current.add(`success-${message}`);
            }
        }
        if (flash?.error) {
            const message = typeof flash.error === 'object' ? flash.error.message : flash.error;
            if (message && !processedMessages.current.has(`error-${message}`)) {
                toast.error(message);
                processedMessages.current.add(`error-${message}`);
            }
        }
    }, [flash]);

    useEffect(() => {
        setReviewData(reviews || []);
    }, [reviews]);

    const columns = [
        { key: 'sn', header: 'SN' },
        { key: 'property_title', header: 'Property' },
        { key: 'reviewer_name', header: 'Reviewer' },
        { key: 'rating', header: 'Rating' },
        { key: 'comment', header: 'Comment' },
        { key: 'created_at', header: 'Date' }
    ];

    const transformedData = reviewData.map(review => ({
        ...review,
        comment: review.comment?.length > 50 ? `${review.comment.substring(0, 50)}...` : review.comment || 'N/A',
        rating: `${review.rating}/5 ⭐`,
        created_at: new Date(review.created_at).toLocaleDateString(),
    }));

    const handlePageChange = (page) => {
        router.get('/admin/reviews', { page }, { preserveState: true, preserveScroll: true });
    };

    const handleDelete = (row) => {
        setDeleteModal({ show: true, review: row });
    };

    return (
        <>
            <Toaster />
            <div className="row">
                <StyledTable
                    data={transformedData}
                    columns={columns}
                    title="Review Management"
                    onDelete={handleDelete}
                    noDataText="No reviews found in the system"
                    disablePagination={true}
                    serverPagination={pagination}
                    onPageChange={handlePageChange}
                    itemType="reviews"
                    showEdit={false}
                />
            </div>

            <DeleteConfirmationModal
                isOpen={deleteModal.show}
                onClose={() => setDeleteModal({ show: false, review: null })}
                onConfirmDelete={() => {}}
                itemName={`Review #${deleteModal.review?.id}` || 'this review'}
                itemType="review"
                deleteEndpoint={`/admin/reviews/${deleteModal?.review?.id}`}
            />
        </>
    );
}
