import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
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 { ArrowLeft, ChevronRight, Edit, Trash } from 'lucide-react';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { router } from '@inertiajs/react';

declare const route: (...args: any[]) => string;

interface Permission {
    id: number;
    name: string;
    slug: string;
    group_name: string;
}

interface Role {
    id: number;
    uid: string;
    name: string;
    slug: string;
    status: string;
    permissions: Permission[];
    created_at: string;
    updated_at: string;
}

export default function View() {
    // @ts-ignore
    const { role } = usePage<PageProps>().props as { role: Role };

    const handleDelete = () => {
        router.delete(route('admin.roles.destroy', role.uid));
    };

    // Group permissions by group_name
    const groupedPermissions = role.permissions.reduce(
        (acc, perm) => {
            if (!acc[perm.group_name]) {
                acc[perm.group_name] = [];
            }
            acc[perm.group_name].push(perm);
            return acc;
        },
        {} as Record<string, Permission[]>
    );

    const statusColorMap: Record<string, string> = {
        active: 'bg-green-100 text-green-800',
        inactive: 'bg-gray-100 text-gray-800',
        deleted: 'bg-red-100 text-red-800',
    };

    return (
        <>
            <Head title={role.name} />
            <div className="mx-auto flex w-full flex-1 flex-col gap-4 p-3 sm:gap-6 sm:p-2">
                {/* Header */}
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <div className="flex items-start gap-3 sm:gap-4">
                        <Button
                            variant="outline"
                            size="icon"
                            onClick={() => history.back()}
                            className="shrink-0 border-none bg-muted hover:bg-muted/80"
                        >
                            <ArrowLeft className="h-4 w-4" color="black" />
                        </Button>
                        <div>
                            <h1 className="text-xl font-bold tracking-tight sm:text-2xl">{role.name}</h1>
                            <p className="text-sm text-gray-600">@{role.slug}</p>
                        </div>
                    </div>
                    <div className="flex items-center gap-2">
                        <Link href={route('admin.roles.edit', role.uid)}>
                            <Button variant="default" size="sm" className="gap-2">
                                <Edit className="h-4 w-4" />
                                Edit
                            </Button>
                        </Link>
                        <AlertDialog>
                            <AlertDialogTrigger asChild>
                                <Button variant="destructive" size="sm" className="gap-2">
                                    <Trash className="h-4 w-4" />
                                    Delete
                                </Button>
                            </AlertDialogTrigger>
                            <AlertDialogContent>
                                <AlertDialogHeader>
                                    <AlertDialogTitle>Delete Role</AlertDialogTitle>
                                    <AlertDialogDescription>
                                        Are you sure you want to delete this role? This action cannot be undone.
                                    </AlertDialogDescription>
                                </AlertDialogHeader>
                                <AlertDialogFooter>
                                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                                    <AlertDialogAction onClick={handleDelete}>Delete</AlertDialogAction>
                                </AlertDialogFooter>
                            </AlertDialogContent>
                        </AlertDialog>
                    </div>
                </div>

                {/* Role Details */}
                <div className="grid gap-4 sm:grid-cols-2">
                    <Card>
                        <CardHeader>
                            <CardTitle>Status</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <Badge className={statusColorMap[role.status] || 'bg-blue-100 text-blue-800'}>
                                {role.status}
                            </Badge>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader>
                            <CardTitle>Permissions</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <p className="text-2xl font-bold">{role.permissions.length}</p>
                            <p className="text-sm text-muted-foreground">Total permissions assigned</p>
                        </CardContent>
                    </Card>
                </div>

                {/* Permissions by Group */}
                <Card>
                    <CardHeader>
                        <CardTitle>Permissions</CardTitle>
                        <CardDescription>Permissions grouped by category</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        {Object.entries(groupedPermissions).map(([groupName, permissions]) => (
                            <div key={groupName}>
                                <h3 className="mb-3 font-semibold capitalize">{groupName}</h3>
                                <div className="grid gap-2 sm:grid-cols-2">
                                    {permissions.map((perm) => (
                                        <div key={perm.id} className="flex items-start gap-2 rounded-lg border p-2">
                                            <div className="flex-1">
                                                <p className="font-medium text-sm">{perm.name}</p>
                                                <p className="text-xs text-muted-foreground">{perm.slug}</p>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        ))}
                        {role.permissions.length === 0 && (
                            <p className="text-sm text-muted-foreground">No permissions assigned to this role</p>
                        )}
                    </CardContent>
                </Card>

                {/* Timestamps */}
                <Card>
                    <CardHeader>
                        <CardTitle>Information</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-2 text-sm">
                        <div>
                            <p className="text-muted-foreground">Created</p>
                            <p>{role.created_at}</p>
                        </div>
                        <div>
                            <p className="text-muted-foreground">Last Updated</p>
                            <p>{role.updated_at}</p>
                        </div>
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

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