import Col from "@admin/ui/Col";
import Row from "@admin/ui/Row";
import StyledTable from "@admin/ui/StyledTable";
import { Link } from "@inertiajs/react";
import DeleteConfirmationModal from "@admin/ui/DeleteConfirmationModal";

import { toast,Toaster } from "react-hot-toast";
import { useState } from "react";
import EditUser from "./EditUser";

export default function User({users}){
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [initialData, setInitialData] = useState(null);
    const [deleteModal, setDeleteModal] = useState({ show: false, user: null });

    const columns = [
        { header: '', key: 'checkbox' },
        { header: 'Name', key: 'name' },
        { header: 'Photo', key: 'photo' },
        { header: 'Role', key: 'role' },
        { header: 'Status', key: 'status' },
      ];

      const handleEdit = (row) => {
        fetch(`/admin/edit_user/${row.id}`)
        .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);
        });
    };

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

    return(
        <>
        <Row md="12" >
            <Col lg="12">
            <Toaster />
            <h2 className="page-title">Users</h2>
            <p className="text-muted">Manage system users</p>
            <Link className="btn mb-4 btn-primary" href="/admin/user/create">
            Create new User
            </Link>
            <Row>
            <Col lg="12">
                <StyledTable 
                data={users} 
                columns={columns} 
                itemsPerPage={5} 
                title="Available Users"
                onEdit={handleEdit}
                onDelete={handleDelete}
                noDataText="No Users found"
                />
            </Col>
            </Row>
            </Col>
        </Row>
        <EditUser isOpen={isEditModalOpen} onClose={() => setIsEditModalOpen(false)} initialData={initialData}
        />

        <DeleteConfirmationModal isOpen={deleteModal.show} onClose={() => setDeleteModal({ show: false, user: null })}
            onConfirmDelete={() => {
                toast.success("User Deleted Successfuly")
            }}
            itemName={deleteModal.user?.name || 'this user'}
            itemType="user"
            deleteEndpoint={`/admin/api/delete_user/${deleteModal?.user?.id}`}
        />
        </>
    );
}