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 Report({ reports, pagination }) {
    const { flash } = usePage().props;
    const processedMessages = useRef(new Set());
    
    const [reportData, setReportData] = useState([]);
    const [deleteModal, setDeleteModal] = useState({ show: false, report: 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(() => {
        setReportData(reports || []);
    }, [reports]);

    const columns = [
        { key: 'sn', header: 'SN' },
        { key: 'reporter_name', header: 'Reporter' },
        { key: 'reason', header: 'Reason' },
        { key: 'description', header: 'Description' },
        { key: 'status', header: 'Status' },
        { key: 'created_at', header: 'Date' }
    ];

    const getStatusName = (status) => {
        const statusMap = { 1: 'pending', 2: 'reviewed', 3: 'resolved' };
        return statusMap[status] || 'N/A';
    };

    const transformedData = reportData.map(report => ({
        ...report,
        description: report.description?.length > 50 ? `${report.description.substring(0, 50)}...` : report.description || 'N/A',
        status: getStatusName(report.status),
        created_at: new Date(report.created_at).toLocaleDateString(),
    }));

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

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

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

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