import AuthenticatedLayout from "@/layouts/authenticated-layout";
import { Head, router,Link } from "@inertiajs/react";
import { useState, useEffect } from "react";
type Permission = {
  id: number;
  name: string;
};

type Role = {
  id: number;
  name: string;
  permissions: Permission[];
};



interface Props {
  roles: Role[];
}

export default function Index({ roles }: Props) {
    const [editableroles, setEditableroles] = useState([]);

    function handleDelete(id){
      if(confirm("Are you sure you want to delete this user?")){
        router.delete(route('roles.destroy', id));

      }
    }



    return (
        <AuthenticatedLayout
            header="roles"
        >
            <Head title="roles" />
<div className="p-3">
<Link href={route('roles.create')}
 className="mr-3 text-sm bg-blue-500 hover:bg-blue-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Create </Link>

</div>
    
<div className="text-gray-900 bg-gray-200">
    <div className="p-4 flex">
        <h1 className="text-3xl">
            roles
        </h1>
    </div>
    <div className="px-3 py-4 flex justify-center">
        <table className="w-full text-md bg-white shadow-md rounded mb-4">
            <tbody>
                <tr className="border-b">
                    <th className="text-left p-3 px-5">ID</th>
                    <th className="text-left p-3 px-5">Name</th>
                    <th className="text-left p-3 px-5">Permissions</th>
                    <th></th>
                </tr>
                {roles.map(({id, name,permissions})=>
                <tr className="border-b hover:bg-orange-100 bg-gray-100">
                    <td className="p-3 px-5">{id}</td>
                    <td className="p-3 px-5">{name}</td>

<td className="p-3 px-5">
  {permissions.map((p: Permission) => p.name).join(', ')}
</td>

                    <td className="p-3 px-5 flex justify-end">
                    <Link 
                        href={route('roles.show',id)}
                    className="mr-3 text-sm bg-blue-500 hover:bg-blue-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Show</Link>
                    <Link 
                        href={route('roles.edit',id)}
                    className="mr-3 text-sm bg-blue-500 hover:bg-blue-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Edit</Link>
                    <button 
                    onClick={()=>handleDelete(id)}
                    type="button" className="text-sm bg-red-500 hover:bg-red-700 text-white py-1 px-2 rounded focus:outline-none focus:shadow-outline">Delete</button></td>
                </tr>
                )}

            </tbody>
        </table>
    </div>
</div>

        </AuthenticatedLayout>
    );
}
