import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, router } from '@inertiajs/react';
import { Users, Plus, Pencil, Trash2, Mail, Shield } 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;
}

interface User {
    id: number;
    name: string;
    email: string;
    username: string | null;
    created_at: string;
    roles: Role[];
}

interface Pagination {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    from: number;
    links: {
        url: string | null;
        label: string;
        active: boolean;
    }[];
}

interface Props {
    users: {
        data: User[];
        meta?: Pagination; // Standard Laravel Pagination resource structure, but if simple paginate() it's direct properties
    } & Pagination; // paginate() returns object with data and meta properties mixed
}

export default function UserIndex({ users }: Props) {
    const handleDelete = (id: number, name: string) => {
        if (confirm(`確定要刪除使用者「${name}」嗎？此操作無法復原。`)) {
            router.delete(route('users.destroy', id), {
                onSuccess: () => toast.success('使用者已刪除'),
                onError: () => toast.error('刪除失敗，請檢查權限'),
            });
        }
    };

    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('users.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">
                            <Users className="h-6 w-6 text-[#01ab83]" />
                            使用者管理
                        </h1>
                        <p className="text-gray-500 mt-1">
                            管理系統使用者帳號與角色分配
                        </p>
                    </div>
                    <Link href={route('users.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 className="w-[250px]">使用者</TableHead>
                                <TableHead>角色</TableHead>
                                <TableHead className="w-[200px]">加入時間</TableHead>
                                <TableHead className="text-center">操作</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {users.data.map((user, index) => (
                                <TableRow key={user.id}>
                                    <TableCell className="text-gray-500 font-medium text-center">
                                        {users.from + index}
                                    </TableCell>
                                    <TableCell>
                                        <div className="flex items-center gap-3">
                                            <div>
                                                <p className="font-medium text-gray-900">{user.name}</p>
                                                <div className="flex items-center text-xs text-gray-500">
                                                    <Mail className="h-3 w-3 mr-1" />
                                                    {user.email}
                                                </div>
                                            </div>
                                        </div>
                                    </TableCell>
                                    <TableCell>
                                        <div className="flex flex-wrap gap-1">
                                            {user.roles.length > 0 ? (
                                                user.roles.map(role => (
                                                    <span
                                                        key={role.id}
                                                        className={cn(
                                                            "inline-flex items-center px-2 py-1 rounded-md text-xs font-medium border",
                                                            role.name === 'super-admin'
                                                                ? "bg-purple-50 text-purple-700 border-purple-200"
                                                                : "bg-gray-100 text-gray-700 border-gray-200"
                                                        )}
                                                    >
                                                        {role.name === 'super-admin' && <Shield className="h-3 w-3 mr-1" />}
                                                        {translateRoleName(role.name)}
                                                    </span>
                                                ))
                                            ) : (
                                                <span className="text-gray-400 text-sm italic">未分配角色</span>
                                            )}
                                        </div>
                                    </TableCell>
                                    <TableCell className="text-gray-500 text-sm">
                                        {format(new Date(user.created_at), 'yyyy/MM/dd')}
                                    </TableCell>
                                    <TableCell className="text-center">
                                        <div className="flex items-center justify-center gap-2">
                                            <Link href={route('users.edit', user.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="刪除"
                                                onClick={() => handleDelete(user.id, user.name)}
                                            >
                                                <Trash2 className="h-4 w-4" />
                                            </Button>
                                        </div>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>

                    {/* Pagination - Simple implementation */}
                    {users.links && users.links.length > 3 && (
                        <div className="px-4 py-3 border-t border-gray-200 flex items-center justify-between sm:px-6">
                            <div className="flex-1 flex justify-between sm:hidden">
                                {/* Mobile pagination */}
                            </div>
                            <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                                <div>
                                    <p className="text-sm text-gray-700">
                                        顯示第 <span className="font-medium">{users.current_page}</span> 頁
                                    </p>
                                </div>
                                <div>
                                    <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                                        {users.links.map((link, i) => {
                                            if (link.url === null) return null; // Skip null links usually
                                            return (
                                                <Link
                                                    key={i}
                                                    href={link.url}
                                                    className={cn(
                                                        "relative inline-flex items-center px-4 py-2 border text-sm font-medium",
                                                        link.active
                                                            ? "z-10 bg-[#01ab83] border-[#01ab83] text-white"
                                                            : "bg-white border-gray-300 text-gray-500 hover:bg-gray-50",
                                                        i === 0 ? "rounded-l-md" : "",
                                                        i === users.links.length - 1 ? "rounded-r-md" : ""
                                                    )}
                                                    dangerouslySetInnerHTML={{ __html: link.label }}
                                                />
                                            );
                                        })}
                                    </nav>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
// Helper for conditional class names if not imported
function cn(...classes: (string | undefined | null | false)[]) {
    return classes.filter(Boolean).join(' ');
}
