import RoleForm from '@/components/all-forms/RoleForm';
import HeaderWithBackIcon from '@/components/header-with-backicon';
import { Button } from '@/components/ui/button';
import AppLayout from '@/layouts/app-layout';
import { PageProps } from '@/types/global';
import { Head, Link, usePage } from '@inertiajs/react';
import { Edit } from 'lucide-react';

interface Permission {
    id: number;
    name: string;
    description?: string;
}

interface Role {
    id: number;
    name: string;
    description?: string;
    permissions: Permission[];
    users_count?: number;
    created_at?: string;
}

interface RolePageProps extends PageProps {
    role: Role;
    [key: string]: any;
}

export default function RolePermissionsView() {
    // @ts-ignore
    const { roleModuleScopes, role, modulePermissions } = usePage<PageProps>().props;

    const normalizeSlug = (slug: string) => slug.replace(/_/g, '_');

    // Prepare initial data for the form
    const initialData = {
        name: (role as any)?.name || '',
        slug: (role as any)?.slug || '',
        permissions: (role as any)?.permissions?.map((p: any) => normalizeSlug(p.slug)) || [],
        moduleScopes: (roleModuleScopes as any) || {},
    };

    const handleSubmit = (formData: any) => {};

    return (
        <>
            <Head title={`View Role: ${(role as any)?.name}`} />
            <div className="mx-auto flex w-full flex-1 flex-col gap-4 p-3 sm:gap-6 sm:p-2">
                {/* Simple header */}
                <div className="flex items-center justify-between">
                    <HeaderWithBackIcon title="View Role" description={`View role details and permissions for ${(role as any)?.name}`} />
                    <div className="hidden items-center space-x-2 text-sm text-gray-500 sm:flex">
                        <Link href={route('roles.edit', role?.uid)}>
                            <Button className="" size={'sm'}>
                                <Edit className="mr-2 h-4 w-4" />
                                Edit Role
                            </Button>
                        </Link>
                    </div>
                </div>
                {/* Main content */}
                <RoleForm
                    modulePermissions={modulePermissions as any}
                    initialData={initialData}
                    onSubmit={handleSubmit}
                    submitButtonText="View Role"
                    isEdit={true}
                    isView={true}
                />
            </div>
        </>
    );
}

RolePermissionsView.layout = (page: React.ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Dashboard', href: route('dashboard') },
            { title: 'Roles', href: route('roles.index') },
            { title: 'View Role', href: '#' },
        ]}
        title="Role Details"
    >
        {page}
    </AppLayout>
);
