import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, router } from '@inertiajs/react';
import { Shield, Plus, Pencil, Trash2, Users } from 'lucide-react';
import { Button } from '@/Components/ui/button';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/Components/ui/table";
import { format } from 'date-fns';
import { toast } from 'sonner';

interface Role {
    id: number;
    name: string;
    users_count: number;
    permissions_count: number;
    created_at: string;
}

interface Props {
    roles: Role[];
}

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

    const translateRoleName = (name: string) => {
        const map: Record<string, string> = {
            'super-admin': '超級管理員',
            'admin': '管理員',
            'warehouse-manager': '倉庫主管',
            'purchaser': '採購人員',
            'viewer': '檢視者',
        };
        return map[name] || name;
    }

    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-[#01ab83]" />
                            角色與權限
                        </h1>
                        <p className="text-gray-500 mt-1">
                            設定系統角色與功能存取權限
                        </p>
                    </div>
                    <Link href={route('roles.create')}>
                        <Button className="button-filled-primary">
                            <Plus className="h-4 w-4 mr-2" />
                            新增角色
                        </Button>
                    </Link>
                </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">
                                            {translateRoleName(role.name)}
                                        </div>
                                    </TableCell>
                                    <TableCell className="text-gray-500 font-mono text-xs">
                                        {role.name}
                                    </TableCell>
                                    <TableCell className="text-center">
                                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                            {role.permissions_count} 項權限
                                        </span>
                                    </TableCell>
                                    <TableCell className="text-center">
                                        <div className="flex items-center justify-center gap-1 text-gray-600">
                                            <Users className="h-3 w-3" />
                                            {role.users_count}
                                        </div>
                                    </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">
                                                <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>
                                                <Button
                                                    variant="outline"
                                                    size="sm"
                                                    className="button-outlined-error"
                                                    title="刪除"
                                                    disabled={role.users_count > 0}
                                                    onClick={() => handleDelete(role.id, translateRoleName(role.name))}
                                                >
                                                    <Trash2 className="h-4 w-4" />
                                                </Button>
                                            </div>
                                        )}
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
