import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, router } from '@inertiajs/react';
import { cn } from "@/lib/utils";
import { Shield, Plus, Pencil, Trash2, Users } from 'lucide-react';
import { Button } from '@/Components/ui/button';
import { Badge } from '@/Components/ui/badge';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/Components/ui/table";
import { format } from 'date-fns';
import { toast } from 'sonner';
import { Can } from '@/Components/Permission/Can';
import { useState } from 'react';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from "@/Components/ui/dialog";

interface User {
    id: number;
    name: string;
    username: string;
}

interface Role {
    id: number;
    name: string;
    display_name: string;
    users_count: number;
    permissions_count: number;
    created_at: string;
    users?: User[];
}

interface Props {
    roles: Role[];
}

export default function RoleIndex({ roles }: Props) {
    const [selectedRole, setSelectedRole] = useState<Role | null>(null);

    const handleDelete = (id: number, name: string) => {
        if (confirm(`確定要刪除角色「${name}」嗎？此操作無法復原。`)) {
            router.delete(route('roles.destroy', id), {
                onSuccess: () => toast.success('角色已刪除'),
            });
        }
    };

    return (
        <AuthenticatedLayout
            breadcrumbs={[
                { label: '系統管理', href: '#' },
                { label: '角色與權限', href: route('roles.index'), isPage: true },
            ]}
        >
            <Head title="角色管理" />

            <div className="container mx-auto p-6 max-w-7xl">
                <div className="flex items-center justify-between mb-6">
                    <div>
                        <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
                            <Shield className="h-6 w-6 text-primary-main" />
                            角色與權限
                        </h1>
                        <p className="text-gray-500 mt-1">
                            設定系統角色與功能存取權限
                        </p>
                    </div>
                    <Can permission="roles.create">
                        <Link href={route('roles.create')}>
                            <Button className="button-filled-primary">
                                <Plus className="h-4 w-4 mr-2" />
                                新增角色
                            </Button>
                        </Link>
                    </Can>
                </div>

                <div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
                    <Table>
                        <TableHeader className="bg-gray-50">
                            <TableRow>
                                <TableHead className="w-[50px] text-center">#</TableHead>
                                <TableHead>名稱</TableHead>
                                <TableHead>代號</TableHead>
                                <TableHead className="text-center">權限數量</TableHead>
                                <TableHead className="text-center">使用者人數</TableHead>
                                <TableHead className="text-left">建立時間</TableHead>
                                <TableHead className="text-center">操作</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {roles.map((role, index) => (
                                <TableRow key={role.id}>
                                    <TableCell className="text-gray-500 font-medium text-center">
                                        {index + 1}
                                    </TableCell>
                                    <TableCell className="font-medium">
                                        <div className="flex items-center gap-2">
                                            {role.display_name}
                                        </div>
                                    </TableCell>
                                    <TableCell className="text-gray-500 font-mono text-xs">
                                        {role.name}
                                    </TableCell>
                                    <TableCell className="text-center">
                                        <Badge variant="default" className="bg-blue-100 text-blue-800 border-blue-200">
                                            {role.permissions_count} 項權限
                                        </Badge>
                                    </TableCell>
                                    <TableCell className="text-center">
                                        <button
                                            onClick={() => role.users_count > 0 && setSelectedRole(role)}
                                            className={cn(
                                                "flex items-center justify-center gap-1 w-full h-full py-2 rounded-md transition-colors",
                                                role.users_count > 0
                                                    ? "text-primary-main hover:bg-primary-main/10 font-bold"
                                                    : "text-gray-400 cursor-default"
                                            )}
                                            title={role.users_count > 0 ? "點擊查看成員名單" : ""}
                                        >
                                            <Users className="h-3.5 w-3.5" />
                                            {role.users_count}
                                        </button>
                                    </TableCell>
                                    <TableCell className="text-left text-gray-500 text-sm">
                                        {format(new Date(role.created_at), 'yyyy/MM/dd')}
                                    </TableCell>
                                    <TableCell className="text-center">
                                        {role.name !== 'super-admin' && (
                                            <div className="flex items-center justify-center gap-2">
                                                <Can permission="roles.edit">
                                                    <Link href={route('roles.edit', role.id)}>
                                                        <Button
                                                            variant="outline"
                                                            size="sm"
                                                            className="button-outlined-primary"
                                                            title="編輯"
                                                        >
                                                            <Pencil className="h-4 w-4" />
                                                        </Button>
                                                    </Link>
                                                </Can>
                                                <Can permission="roles.delete">
                                                    <Button
                                                        variant="outline"
                                                        size="sm"
                                                        className="button-outlined-error"
                                                        title="刪除"
                                                        disabled={role.users_count > 0}
                                                        onClick={() => handleDelete(role.id, role.display_name)}
                                                    >
                                                        <Trash2 className="h-4 w-4" />
                                                    </Button>
                                                </Can>
                                            </div>
                                        )}
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </div>
            </div>

            {/* 成員名單對話框 */}
            <Dialog open={!!selectedRole} onOpenChange={(open) => !open && setSelectedRole(null)}>
                <DialogContent className="sm:max-w-md">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2">
                            <Users className="h-5 w-5 text-primary-main" />
                            {selectedRole?.display_name} - 成員名單
                        </DialogTitle>
                        <DialogDescription>
                            目前共有 {selectedRole?.users_count} 位使用者具備此角色權限
                        </DialogDescription>
                    </DialogHeader>

                    <div className="max-h-[60vh] overflow-y-auto pr-2">
                        {selectedRole?.users && selectedRole.users.length > 0 ? (
                            <div className="space-y-3">
                                {selectedRole.users.map((user) => (
                                    <div
                                        key={user.id}
                                        className="flex items-center justify-between p-3 rounded-lg border border-gray-100 bg-gray-50/50"
                                    >
                                        <div className="flex items-center gap-3">
                                            <div className="h-8 w-8 rounded-full bg-white border border-gray-200 flex items-center justify-center text-xs font-bold text-gray-500 shadow-sm">
                                                {user.name.charAt(0)}
                                            </div>
                                            <div>
                                                <p className="text-sm font-semibold text-gray-900">{user.name}</p>
                                                <p className="text-xs text-gray-500 font-mono italic">@{user.username}</p>
                                            </div>
                                        </div>
                                        <Link
                                            href={route('users.edit', user.id)}
                                            className="text-xs text-primary-main hover:underline font-medium"
                                        >
                                            查看帳號
                                        </Link>
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <div className="text-center py-8 text-gray-500 italic">
                                暫無成員
                            </div>
                        )}
                    </div>
                </DialogContent>
            </Dialog>
        </AuthenticatedLayout>
    );
}
