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

export default function User({ users, pagination, filters }) {
    const { flash } = usePage().props;
    const processedMessages = useRef(new Set());
    
    const [userData, setUserData] = useState([]);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [initialData, setInitialData] = useState(null);
    const [deleteModal, setDeleteModal] = useState({ show: false, user: null });

    // Handle flash messages from trait (simple format) - prevent duplicates
    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]);

    // Define columns for user data
    const columns = [
        { key: 'sn', header: 'SN' },
        { key: 'name', header: 'Name' },
        { key: 'email', header: 'Email' },
        { key: 'phone', header: 'Phone' },
        { key: 'role', header: 'Role' },
        { key: 'status', header: 'Status' }
    ];

    useEffect(() => {
        // Set user data directly from users prop
        setUserData(users);
    }, [users]);

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

    const handleEdit = (row) => {
        fetch(`/admin/users/${row.id}/edit`)
            .then((response) => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then((userData) => {
                const formattedData = userData;
                setInitialData(formattedData);
                setIsEditModalOpen(true);
            })
            .catch((error) => {
                console.error('Error fetching user details:', error);
                toast.error('Failed to load user details');
            });
    };

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

    return (
        <>
            <Toaster />
            <div className="row">
                <div className="col-lg-2 mt-4">
                    <Link href="/admin/users/create" className="btn btn-primary mb-3">
                        Add New User
                    </Link>
                </div>
                <StyledTable
                    data={userData}
                    columns={columns}
                    title="User Management"
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                    noDataText="No users found in the system"
                    disablePagination={true}
                    serverPagination={pagination}
                    onPageChange={handlePageChange}
                    itemType="users"
                />
            </div>

            <DeleteConfirmationModal
                isOpen={deleteModal.show}
                onClose={() => setDeleteModal({ show: false, user: null })}
                onConfirmDelete={() => {
                    // Let Inertia handle the response and page refresh
                    // The trait will redirect back with success/error messages
                }}
                itemName={deleteModal.user?.name || 'this user'}
                itemType="user"
                deleteEndpoint={`/admin/users/${deleteModal?.user?.id}`}
            />
            <EditUser
                isOpen={isEditModalOpen}
                onClose={() => setIsEditModalOpen(false)}
                initialData={initialData}
            />
        </>
    );
}
