import { useState } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { ArrowLeft, Save, Users } from 'lucide-react';

interface UsuarioRolesProps {
    entity: {
        id: number;
        name: string;
        email: string;
        roles: Array<{
            id: number;
            name: string;
        }>;
    };
    roles: Array<{
        id: number;
        name: string;
    }>;
}

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Usuarios',
        href: '/users',
    },
    {
        title: 'Gestionar Roles',
        href: '#',
    },
];

export default function UsuarioRoles({ entity, roles }: UsuarioRolesProps) {
    const [selectedRoles, setSelectedRoles] = useState<number[]>(
        entity.roles.map(role => role.id)
    );
    const [processing, setProcessing] = useState(false);

    const handleRoleToggle = (roleId: number) => {
        setSelectedRoles(prev =>
            prev.includes(roleId)
                ? prev.filter(id => id !== roleId)
                : [...prev, roleId]
        );
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        setProcessing(true);

        router.post(`/usuarios/${entity.id}/roles`, {
            roles: selectedRoles
        }, {
            onSuccess: () => {
                toast.success('Roles actualizados exitosamente');
                setProcessing(false);
            },
            onError: () => {
                toast.error('Error al actualizar los roles');
                setProcessing(false);
            },
        });
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Gestionar Roles" />

            <div className="flex h-full flex-1 flex-col gap-6 p-6">
                <Card className="max-w-2xl mx-auto w-full">
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Users className="h-6 w-6" />
                            Gestionar Roles
                        </CardTitle>
                        <CardDescription>
                            Asignar roles al usuario: {entity.name}
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                        <form onSubmit={handleSubmit} className="space-y-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {roles.map((role) => (
                                    <div key={role.id} className="flex items-center space-x-2">
                                        <Checkbox
                                            id={`role-${role.id}`}
                                            checked={selectedRoles.includes(role.id)}
                                            onCheckedChange={() => handleRoleToggle(role.id)}
                                        />
                                        <label
                                            htmlFor={`role-${role.id}`}
                                            className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                                        >
                                            {role.name}
                                        </label>
                                    </div>
                                ))}
                            </div>

                            <div className="flex gap-3 pt-4">
                                <Link href="/users" className="flex-1">
                                    <Button type="button" variant="outline" className="w-full">
                                        <ArrowLeft className="mr-2 h-4 w-4" />
                                        Cancelar
                                    </Button>
                                </Link>
                                <Button type="submit" disabled={processing} className="flex-1">
                                    <Save className="mr-2 h-4 w-4" />
                                    {processing ? 'Guardando...' : 'Guardar Roles'}
                                </Button>
                            </div>
                        </form>
                    </CardContent>
                </Card>
            </div>

            <ToastContainer
                position="top-right"
                autoClose={3000}
                hideProgressBar={false}
                newestOnTop
                closeOnClick
                rtl={false}
                pauseOnFocusLoss
                draggable
                pauseOnHover
                theme="light"
            />
        </AppLayout>
    );
}
