import { Head, router, usePage } from '@inertiajs/react';
import { useState, useEffect } from 'react';
import AdminLayout from '@/components/Layouts/AdminLayout';
import Card from '@/components/Card/Card';
import Button from '@/components/Button/Button';
import Table, { TableBody, TableCell, TableHeader, TableHeaderCell, TableRow } from '@/components/Table/Table';
import Modal from '@/components/Modal/Modal';
import Input from '@/components/Input/Input';
import Select from '@/components/Select/Select';
import SearchInput from '@/components/SearchInput/SearchInput';
import RefreshButton from '@/components/RefreshButton/RefreshButton';
import AssignShowModal from '@/components/AssignShowModal/AssignShowModal';
import { Form } from '@inertiajs/react';
import { User, Show } from '@/types';

interface UsersPageProps {
    users: User[];
    pagination?: {
        data: User[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
        links: Array<{ url: string | null; label: string; active: boolean }>;
    };
    availableShows?: Show[];
    availableFeatures?: Record<string, string>;
    filters?: {
        role?: string;
        search?: string;
    };
}

export default function Index({ users = [], pagination, availableShows = [], availableFeatures = {}, filters = {} }: UsersPageProps) {
    const [search, setSearch] = useState(filters.search || '');
    const [roleFilter, setRoleFilter] = useState(filters.role || 'user');
    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
    const [isAssignShowModalOpen, setIsAssignShowModalOpen] = useState(false);
    const [isFeaturesModalOpen, setIsFeaturesModalOpen] = useState(false);
    const [isCoinBalanceModalOpen, setIsCoinBalanceModalOpen] = useState(false);
    const [selectedUser, setSelectedUser] = useState<User | null>(null);
    const [selectedFeatures, setSelectedFeatures] = useState<string[]>([]);
    const [coinAction, setCoinAction] = useState<'set' | 'add' | 'subtract'>('set');
    const [coinAmount, setCoinAmount] = useState<string>('');
    const [coinReason, setCoinReason] = useState<string>('');

    const handleEdit = (user: User) => {
        setSelectedUser(user);
        setIsEditModalOpen(true);
    };

    const handleDelete = (user: User) => {
        setSelectedUser(user);
        setIsDeleteModalOpen(true);
    };

    const handleAssignShow = (user: User) => {
        setSelectedUser(user);
        setIsAssignShowModalOpen(true);
    };

    const handleManageFeatures = (user: User) => {
        setSelectedUser(user);
        setSelectedFeatures(user.features || []);
        setIsFeaturesModalOpen(true);
    };

    const handleManageCoinBalance = (user: User) => {
        setSelectedUser(user);
        setCoinAction('set');
        setCoinAmount((user.coin_balance || 0).toString());
        setCoinReason('');
        setIsCoinBalanceModalOpen(true);
    };

    const handleUpdateCoinBalance = () => {
        if (!selectedUser || !coinAmount) {
            return;
        }

        router.post(
            `/admin/users/${selectedUser.id}/coin-balance`,
            {
                action: coinAction,
                coin_balance: parseInt(coinAmount) || 0,
                reason: coinReason || 'Admin adjustment',
            },
            {
                preserveState: true,
                preserveScroll: true,
                onSuccess: () => {
                    setIsCoinBalanceModalOpen(false);
                    setSelectedUser(null);
                    setCoinAmount('');
                    setCoinReason('');
                },
            }
        );
    };

    const handleFeatureToggle = (feature: string) => {
        setSelectedFeatures((prev) => {
            if (prev.includes(feature)) {
                return prev.filter((f) => f !== feature);
            }
            return [...prev, feature];
        });
    };

    const handleSaveFeatures = () => {
        if (!selectedUser) {
            return;
        }

        router.put(
            `/admin/users/${selectedUser.id}`,
            {
                features: selectedFeatures,
                name: selectedUser.name,
                email: selectedUser.email,
                role: selectedUser.role,
            },
            {
                preserveState: true,
                preserveScroll: true,
                onSuccess: () => {
                    setIsFeaturesModalOpen(false);
                    setSelectedUser(null);
                    setSelectedFeatures([]);
                },
            }
        );
    };

    const handleDeleteConfirm = () => {
        if (selectedUser) {
            router.delete(`/admin/users/${selectedUser.id}`, {
                onSuccess: () => {
                    setIsDeleteModalOpen(false);
                    setSelectedUser(null);
                },
            });
        }
    };

    // Handle search dengan debounce
    useEffect(() => {
        // Skip initial load jika filter masih default
        const isInitialLoad = search === (filters.search || '') && roleFilter === (filters.role || 'user');
        if (isInitialLoad) {
            return;
        }

        const timer = setTimeout(() => {
            router.get(
                '/admin/users',
                {
                    role: roleFilter,
                    search: search || undefined,
                },
                {
                    preserveState: true,
                    preserveScroll: true,
                    replace: true,
                }
            );
        }, 300);

        return () => clearTimeout(timer);
    }, [search, roleFilter]);

    const handleRoleFilterChange = (newRole: string) => {
        setRoleFilter(newRole);
        router.get(
            '/admin/users',
            {
                role: newRole,
                search: search || undefined,
            },
            {
                preserveState: true,
                preserveScroll: true,
                replace: true,
            }
        );
    };

    const handleSearchClear = () => {
        setSearch('');
    };

    const getRoleBadge = (role: string) => {
        const roleClasses = {
            admin: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
            partner: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
            user: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300',
        };

        return (
            <span
                className={`inline-flex rounded-full px-2 py-1 text-xs font-semibold ${
                    roleClasses[role as keyof typeof roleClasses] || roleClasses.user
                }`}
            >
                {role.charAt(0).toUpperCase() + role.slice(1)}
            </span>
        );
    };

    const getMembershipStatus = (user: User) => {
        if (!user.is_member) {
            return (
                <span className="inline-flex rounded-full bg-gray-100 px-2 py-1 text-xs font-semibold text-gray-800 dark:bg-gray-700 dark:text-gray-300">
                    Non-Member
                </span>
            );
        }

        if (!user.membership_expires_at) {
            return (
                <span className="inline-flex rounded-full bg-yellow-100 px-2 py-1 text-xs font-semibold text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400">
                    Member (No Expiry)
                </span>
            );
        }

        const expiresAt = new Date(user.membership_expires_at);
        const now = new Date();
        const daysRemaining = Math.ceil((expiresAt.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));

        if (daysRemaining < 0) {
            return (
                <span className="inline-flex rounded-full bg-red-100 px-2 py-1 text-xs font-semibold text-red-800 dark:bg-red-900/30 dark:text-red-400">
                    Expired
                </span>
            );
        }

        if (daysRemaining <= 7) {
            return (
                <span className="inline-flex rounded-full bg-orange-100 px-2 py-1 text-xs font-semibold text-orange-800 dark:bg-orange-900/30 dark:text-orange-400">
                    Expires in {daysRemaining} day{daysRemaining !== 1 ? 's' : ''}
                </span>
            );
        }

        return (
            <span className="inline-flex rounded-full bg-green-100 px-2 py-1 text-xs font-semibold text-green-800 dark:bg-green-900/30 dark:text-green-400">
                Active ({daysRemaining} days)
            </span>
        );
    };

    const formatMembershipDate = (dateString?: string) => {
        if (!dateString) return '-';
        return new Date(dateString).toLocaleDateString('id-ID', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
        });
    };

    return (
        <AdminLayout title="Users Management">
            <Head title="Users Management" />
            <div className="space-y-6">
                {/* Header dengan tombol Create dan Refresh */}
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-bold text-gray-900 dark:text-white">Users Management</h2>
                        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                            Kelola semua user yang terdaftar di sistem
                        </p>
                    </div>
                    <div className="flex items-center gap-2">
                        <RefreshButton />
                        <Button onClick={() => setIsCreateModalOpen(true)}>Tambah User</Button>
                    </div>
                </div>

                {/* Search and Filter */}
                <Card padding="md">
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Cari User
                            </label>
                            <SearchInput
                                placeholder="Cari berdasarkan nama atau email..."
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                onClear={handleSearchClear}
                            />
                        </div>
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Filter Role
                            </label>
                            <Select
                                value={roleFilter}
                                onChange={(e) => handleRoleFilterChange(e.target.value)}
                                options={[
                                    { value: 'all', label: 'Semua Role' },
                                    { value: 'user', label: 'User' },
                                    { value: 'partner', label: 'Partner' },
                                    { value: 'admin', label: 'Admin' },
                                ]}
                            />
                        </div>
                    </div>
                </Card>

                {/* Table */}
                <Card padding="none">
                    <div className="overflow-x-auto">
                        <Table pagination={pagination}>
                            <TableHeader>
                                <TableHeaderCell>Nama</TableHeaderCell>
                                <TableHeaderCell>Email</TableHeaderCell>
                                <TableHeaderCell>Role</TableHeaderCell>
                                {(roleFilter === 'user' || roleFilter === 'all') && (
                                    <>
                                        <TableHeaderCell>Coin Balance</TableHeaderCell>
                                        <TableHeaderCell>Membership</TableHeaderCell>
                                        <TableHeaderCell>Show</TableHeaderCell>
                                    </>
                                )}
                                {(roleFilter === 'partner' || roleFilter === 'all') && (
                                    <TableHeaderCell>Features</TableHeaderCell>
                                )}
                                <TableHeaderCell className="text-right">Actions</TableHeaderCell>
                            </TableHeader>
                            <TableBody>
                                {!users || users.length === 0 ? (
                                    <TableRow>
                                        <TableCell 
                                            colSpan={
                                                (roleFilter === 'user' || roleFilter === 'all' ? 7 : 4) +
                                                ((roleFilter === 'partner' || roleFilter === 'all') ? 1 : 0)
                                            } 
                                            className="text-center py-8 text-gray-500 dark:text-gray-400"
                                        >
                                            Tidak ada data user
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    (users || []).map((user) => {
                                        const isUser = user.role === 'user';
                                        const isPartner = user.role === 'partner';
                                        const showMembershipColumns = roleFilter === 'user' || roleFilter === 'all';
                                        const showFeaturesColumn = roleFilter === 'partner' || roleFilter === 'all';
                                        
                                        return (
                                            <TableRow key={user.id}>
                                                <TableCell className="font-medium">{user.name}</TableCell>
                                                <TableCell className="text-sm text-gray-600 dark:text-gray-400">
                                                    {user.email}
                                                </TableCell>
                                                <TableCell>{getRoleBadge(user.role)}</TableCell>
                                                {showMembershipColumns && (
                                                    <>
                                                        <TableCell>
                                                            {isUser ? (
                                                                <div className="flex items-center gap-2">
                                                                    <span className="inline-flex items-center gap-1 rounded-full bg-[#d4af37]/10 px-2.5 py-1 text-xs font-semibold text-[#d4af37] dark:bg-[#b8941f]/20 dark:text-[#b8941f]">
                                                                        <CoinIcon className="h-3.5 w-3.5" />
                                                                        {(user.coin_balance || 0).toLocaleString('id-ID')} NGD
                                                                    </span>
                                                                </div>
                                                            ) : (
                                                                '-'
                                                            )}
                                                        </TableCell>
                                                        <TableCell>
                                                            {isUser ? getMembershipStatus(user) : '-'}
                                                        </TableCell>
                                                        <TableCell>
                                                            {isUser ? (
                                                                <span className="inline-flex items-center gap-1 rounded-full bg-[#d4af37]/10 px-2 py-1 text-xs font-semibold text-[#d4af37] dark:bg-[#b8941f]/20 dark:text-[#b8941f]">
                                                                    <i className="fas fa-film text-xs"></i>
                                                                    {(user as any).shows?.length || 0}
                                                                </span>
                                                            ) : (
                                                                '-'
                                                            )}
                                                        </TableCell>
                                                    </>
                                                )}
                                                {showFeaturesColumn && (
                                                    <TableCell>
                                                        {isPartner ? (
                                                            user.features && user.features.length > 0 ? (
                                                                <div className="flex flex-wrap gap-1">
                                                                    {user.features.slice(0, 2).map((feature) => (
                                                                        <span
                                                                            key={feature}
                                                                            className="inline-flex items-center gap-1 rounded-full bg-purple-100 px-2 py-0.5 text-xs font-semibold text-purple-800 dark:bg-purple-900/30 dark:text-purple-400"
                                                                            title={availableFeatures[feature] || feature}
                                                                        >
                                                                            <i className="fas fa-star text-xs"></i>
                                                                            {availableFeatures[feature] || feature}
                                                                        </span>
                                                                    ))}
                                                                    {user.features.length > 2 && (
                                                                        <span className="inline-flex items-center rounded-full bg-gray-100 px-2 py-0.5 text-xs font-semibold text-gray-800 dark:bg-gray-700 dark:text-gray-300">
                                                                            +{user.features.length - 2}
                                                                        </span>
                                                                    )}
                                                                </div>
                                                            ) : (
                                                                <span className="text-xs text-gray-400 dark:text-gray-500">No features</span>
                                                            )
                                                        ) : (
                                                            '-'
                                                        )}
                                                    </TableCell>
                                                )}
                                                <TableCell>
                                                    <div className="flex items-center justify-end gap-1">
                                                        {isUser && (
                                                            <>
                                                                <button
                                                                    onClick={() => handleManageCoinBalance(user)}
                                                                    className="rounded-md p-2 text-[#d4af37] hover:bg-[#d4af37]/10 dark:text-[#b8941f] dark:hover:bg-[#b8941f]/20 transition-colors"
                                                                    title="Manage Coin Balance"
                                                                >
                                                                    <CoinIcon className="h-4 w-4" />
                                                                </button>
                                                                <button
                                                                    onClick={() => handleAssignShow(user)}
                                                                    className="rounded-md p-2 text-[#d4af37] hover:bg-[#d4af37]/10 dark:text-[#b8941f] dark:hover:bg-[#b8941f]/20 transition-colors"
                                                                    title="Assign Show"
                                                                >
                                                                    <i className="fas fa-ticket-alt"></i>
                                                                </button>
                                                            </>
                                                        )}
                                                        {user.role === 'partner' && (
                                                            <button
                                                                onClick={() => handleManageFeatures(user)}
                                                                className="rounded-md p-2 text-purple-600 hover:bg-purple-50 dark:text-purple-400 dark:hover:bg-purple-900/20 transition-colors"
                                                                title="Manage Features"
                                                            >
                                                                <i className="fas fa-star"></i>
                                                            </button>
                                                        )}
                                                        <button
                                                            onClick={() => handleEdit(user)}
                                                            className="rounded-md p-2 text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20 transition-colors"
                                                            title="Edit"
                                                        >
                                                            <i className="fas fa-edit"></i>
                                                        </button>
                                                        <button
                                                            onClick={() => handleDelete(user)}
                                                            className="rounded-md p-2 text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20 transition-colors"
                                                            title="Hapus"
                                                        >
                                                            <i className="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        );
                                    })
                                )}
                            </TableBody>
                        </Table>
                    </div>
                </Card>

                {/* Create Modal */}
                <Modal
                    isOpen={isCreateModalOpen}
                    onClose={() => setIsCreateModalOpen(false)}
                    title="Tambah User Baru"
                    size="md"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button variant="secondary" onClick={() => setIsCreateModalOpen(false)}>
                                Batal
                            </Button>
                            <Form action="/admin/users" method="post" id="create-user-form">
                                <Button type="submit" form="create-user-form">
                                    Simpan
                                </Button>
                            </Form>
                        </div>
                    }
                >
                    <Form action="/admin/users" method="post" id="create-user-form" className="space-y-4">
                        <Input
                            name="name"
                            label="Nama"
                            required
                            placeholder="Masukkan nama user"
                        />
                        <Input
                            name="email"
                            type="email"
                            label="Email"
                            required
                            placeholder="Masukkan email user"
                        />
                        <Input
                            name="password"
                            type="password"
                            label="Password"
                            required
                            placeholder="Masukkan password"
                        />
                        <Select
                            name="role"
                            label="Role"
                            required
                            options={[
                                { value: 'user', label: 'User' },
                                { value: 'partner', label: 'Partner' },
                                { value: 'admin', label: 'Admin' },
                            ]}
                        />
                    </Form>
                </Modal>

                {/* Edit Modal */}
                <Modal
                    isOpen={isEditModalOpen}
                    onClose={() => {
                        setIsEditModalOpen(false);
                        setSelectedUser(null);
                    }}
                    title="Edit User"
                    size="md"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                variant="secondary"
                                onClick={() => {
                                    setIsEditModalOpen(false);
                                    setSelectedUser(null);
                                }}
                            >
                                Batal
                            </Button>
                            {selectedUser && (
                                <Form
                                    action={`/admin/users/${selectedUser.id}`}
                                    method="post"
                                    id="edit-user-form"
                                >
                                    <input type="hidden" name="_method" value="put" />
                                    <Button type="submit" form="edit-user-form">
                                        Update
                                    </Button>
                                </Form>
                            )}
                        </div>
                    }
                >
                    {selectedUser && (
                        <Form
                            action={`/admin/users/${selectedUser.id}`}
                            method="post"
                            id="edit-user-form"
                            className="space-y-4"
                        >
                            <input type="hidden" name="_method" value="put" />
                            <Input
                                name="name"
                                label="Nama"
                                required
                                defaultValue={selectedUser.name}
                                placeholder="Masukkan nama user"
                            />
                            <Input
                                name="email"
                                type="email"
                                label="Email"
                                required
                                defaultValue={selectedUser.email}
                                placeholder="Masukkan email user"
                            />
                            <Input
                                name="password"
                                type="password"
                                label="Password (kosongkan jika tidak ingin mengubah)"
                                placeholder="Masukkan password baru"
                            />
                            <Select
                                name="role"
                                label="Role"
                                required
                                defaultValue={selectedUser.role}
                                options={[
                                    { value: 'user', label: 'User' },
                                    { value: 'partner', label: 'Partner' },
                                    { value: 'admin', label: 'Admin' },
                                ]}
                            />
                            
                            {/* Coin Balance Section - Hanya untuk user biasa */}
                            {selectedUser.role === 'user' && (
                                <div className="space-y-4 border-t border-gray-200 pt-4 dark:border-gray-700">
                                    <h3 className="text-base font-semibold text-gray-900 dark:text-white">
                                        Coin Balance
                                    </h3>
                                    <Input
                                        name="coin_balance"
                                        label="Saldo Coin (NGD)"
                                        type="number"
                                        min="0"
                                        defaultValue={selectedUser.coin_balance || 0}
                                        placeholder="0"
                                    />
                                    <p className="text-xs text-gray-500 dark:text-gray-400">
                                        Gunakan tombol "Manage Coin Balance" untuk menambah/mengurangi coin dengan alasan.
                                    </p>
                                </div>
                            )}
                            
                            {/* Membership Section - Hanya untuk user biasa */}
                            {selectedUser.role === 'user' && (
                                <div className="space-y-4 border-t border-gray-200 pt-4 dark:border-gray-700">
                                    <h3 className="text-base font-semibold text-gray-900 dark:text-white">
                                        Membership
                                    </h3>
                                    <div className="flex items-center gap-2">
                                        <input type="hidden" name="is_member" value="0" />
                                        <input
                                            type="checkbox"
                                            name="is_member"
                                            id="edit_is_member"
                                            value="1"
                                            defaultChecked={selectedUser.is_member}
                                            className="h-4 w-4 rounded border-gray-300 text-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600"
                                        />
                                        <label htmlFor="edit_is_member" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Aktifkan Membership
                                        </label>
                                    </div>
                                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                        <Input
                                            name="membership_started_at"
                                            label="Tanggal Mulai Membership"
                                            type="datetime-local"
                                            defaultValue={
                                                selectedUser.membership_started_at
                                                    ? new Date(selectedUser.membership_started_at).toISOString().slice(0, 16)
                                                    : ''
                                            }
                                        />
                                        <Input
                                            name="membership_expires_at"
                                            label="Tanggal Berakhir Membership"
                                            type="datetime-local"
                                            defaultValue={
                                                selectedUser.membership_expires_at
                                                    ? new Date(selectedUser.membership_expires_at).toISOString().slice(0, 16)
                                                    : ''
                                            }
                                        />
                                    </div>
                                </div>
                            )}
                        </Form>
                    )}
                </Modal>

                {/* Delete Confirmation Modal */}
                <Modal
                    isOpen={isDeleteModalOpen}
                    onClose={() => {
                        setIsDeleteModalOpen(false);
                        setSelectedUser(null);
                    }}
                    title="Hapus User"
                    size="sm"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                variant="secondary"
                                onClick={() => {
                                    setIsDeleteModalOpen(false);
                                    setSelectedUser(null);
                                }}
                            >
                                Batal
                            </Button>
                            <Button variant="danger" onClick={handleDeleteConfirm}>
                                Hapus
                            </Button>
                        </div>
                    }
                >
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                        Apakah Anda yakin ingin menghapus user{' '}
                        <span className="font-semibold text-gray-900 dark:text-white">
                            {selectedUser?.name}
                        </span>
                        ? Tindakan ini tidak dapat dibatalkan.
                    </p>
                </Modal>

                {/* Assign Show Modal */}
                {selectedUser && (
                    <AssignShowModal
                        isOpen={isAssignShowModalOpen}
                        onClose={() => {
                            setIsAssignShowModalOpen(false);
                            setSelectedUser(null);
                        }}
                        user={selectedUser}
                        availableShows={availableShows}
                        userShows={(selectedUser as any).shows || []}
                    />
                )}

                {/* Manage Features Modal */}
                <Modal
                    isOpen={isFeaturesModalOpen}
                    onClose={() => {
                        setIsFeaturesModalOpen(false);
                        setSelectedUser(null);
                        setSelectedFeatures([]);
                    }}
                    title={`Manage Features - ${selectedUser?.name}`}
                    size="lg"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                variant="secondary"
                                onClick={() => {
                                    setIsFeaturesModalOpen(false);
                                    setSelectedUser(null);
                                    setSelectedFeatures([]);
                                }}
                            >
                                Batal
                            </Button>
                            <Button onClick={handleSaveFeatures}>
                                Simpan Features
                            </Button>
                        </div>
                    }
                >
                    <div className="space-y-4">
                        <p className="text-sm text-gray-600 dark:text-gray-400">
                            Pilih fitur yang akan diaktifkan untuk partner ini. Fitur yang dipilih akan tersedia di dashboard partner.
                        </p>
                        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                            {Object.entries(availableFeatures).map(([key, label]) => (
                                <label
                                    key={key}
                                    className={`flex items-center gap-3 rounded-lg border p-4 cursor-pointer transition-colors ${
                                        selectedFeatures.includes(key)
                                            ? 'border-[#d4af37] bg-[#d4af37]/5 dark:border-[#b8941f] dark:bg-[#b8941f]/10'
                                            : 'border-gray-200 hover:border-gray-300 dark:border-gray-700 dark:hover:border-gray-600'
                                    }`}
                                >
                                    <input
                                        type="checkbox"
                                        checked={selectedFeatures.includes(key)}
                                        onChange={() => handleFeatureToggle(key)}
                                        className="h-4 w-4 rounded border-gray-300 text-[#d4af37] focus:ring-[#d4af37] dark:border-gray-600"
                                    />
                                    <div className="flex-1">
                                        <div className="text-sm font-medium text-gray-900 dark:text-white">
                                            {label}
                                        </div>
                                        <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                            {key}
                                        </div>
                                    </div>
                                    {selectedFeatures.includes(key) && (
                                        <i className="fas fa-check-circle text-[#d4af37] dark:text-[#b8941f]"></i>
                                    )}
                                </label>
                            ))}
                        </div>
                        {selectedFeatures.length > 0 && (
                            <div className="mt-4 rounded-lg border border-[#d4af37]/20 bg-[#d4af37]/5 p-3 dark:border-[#b8941f]/20 dark:bg-[#b8941f]/10">
                                <div className="text-sm font-medium text-gray-900 dark:text-white mb-2">
                                    Features yang dipilih ({selectedFeatures.length}):
                                </div>
                                <div className="flex flex-wrap gap-2">
                                    {selectedFeatures.map((feature) => (
                                        <span
                                            key={feature}
                                            className="inline-flex items-center gap-1 rounded-full bg-[#d4af37]/10 px-2 py-1 text-xs font-semibold text-[#d4af37] dark:bg-[#b8941f]/20 dark:text-[#b8941f]"
                                        >
                                            {availableFeatures[feature] || feature}
                                            <button
                                                onClick={() => handleFeatureToggle(feature)}
                                                className="ml-1 hover:text-red-600 dark:hover:text-red-400"
                                            >
                                                <i className="fas fa-times text-xs"></i>
                                            </button>
                                        </span>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                </Modal>

                {/* Manage Coin Balance Modal */}
                <Modal
                    isOpen={isCoinBalanceModalOpen}
                    onClose={() => {
                        setIsCoinBalanceModalOpen(false);
                        setSelectedUser(null);
                        setCoinAmount('');
                        setCoinReason('');
                    }}
                    title={`Manage Coin Balance - ${selectedUser?.name}`}
                    size="md"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                variant="secondary"
                                onClick={() => {
                                    setIsCoinBalanceModalOpen(false);
                                    setSelectedUser(null);
                                    setCoinAmount('');
                                    setCoinReason('');
                                }}
                            >
                                Batal
                            </Button>
                            <Button onClick={handleUpdateCoinBalance} disabled={!coinAmount || parseInt(coinAmount) < 0}>
                                Update Coin Balance
                            </Button>
                        </div>
                    }
                >
                    {selectedUser && (
                        <div className="space-y-4">
                            {/* Current Balance Display */}
                            <div className="rounded-lg border-2 border-[#d4af37]/20 bg-[#d4af37]/5 p-4 dark:border-[#b8941f]/20 dark:bg-[#b8941f]/10">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm font-medium text-gray-600 dark:text-gray-400">Saldo Saat Ini</p>
                                        <p className="mt-1 text-2xl font-bold text-[#d4af37] dark:text-[#b8941f]">
                                            {(selectedUser.coin_balance || 0).toLocaleString('id-ID')} NGD
                                        </p>
                                    </div>
                                    <CoinIcon className="h-10 w-10 text-[#d4af37] dark:text-[#b8941f]" />
                                </div>
                            </div>

                            {/* Action Selection */}
                            <div>
                                <label className="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    Tindakan
                                </label>
                                <div className="grid grid-cols-3 gap-2">
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setCoinAction('set');
                                            setCoinAmount((selectedUser.coin_balance || 0).toString());
                                        }}
                                        className={`rounded-lg border-2 px-3 py-2 text-sm font-medium transition-all ${
                                            coinAction === 'set'
                                                ? 'border-[#d4af37] bg-[#d4af37]/10 text-[#d4af37] dark:border-[#b8941f] dark:bg-[#b8941f]/20 dark:text-[#b8941f]'
                                                : 'border-gray-300 bg-white text-gray-700 hover:border-gray-400 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-300'
                                        }`}
                                    >
                                        Set
                                    </button>
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setCoinAction('add');
                                            setCoinAmount('');
                                        }}
                                        className={`rounded-lg border-2 px-3 py-2 text-sm font-medium transition-all ${
                                            coinAction === 'add'
                                                ? 'border-green-500 bg-green-50 text-green-700 dark:border-green-400 dark:bg-green-900/20 dark:text-green-400'
                                                : 'border-gray-300 bg-white text-gray-700 hover:border-gray-400 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-300'
                                        }`}
                                    >
                                        Tambah
                                    </button>
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setCoinAction('subtract');
                                            setCoinAmount('');
                                        }}
                                        className={`rounded-lg border-2 px-3 py-2 text-sm font-medium transition-all ${
                                            coinAction === 'subtract'
                                                ? 'border-red-500 bg-red-50 text-red-700 dark:border-red-400 dark:bg-red-900/20 dark:text-red-400'
                                                : 'border-gray-300 bg-white text-gray-700 hover:border-gray-400 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-300'
                                        }`}
                                    >
                                        Kurangi
                                    </button>
                                </div>
                            </div>

                            {/* Amount Input */}
                            <div>
                                <label htmlFor="coin_amount" className="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    {coinAction === 'set' ? 'Jumlah Coin Baru' : coinAction === 'add' ? 'Jumlah Coin yang Ditambahkan' : 'Jumlah Coin yang Dikurangi'}
                                </label>
                                <div className="relative">
                                    <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                        <CoinIcon className="h-5 w-5 text-gray-400 dark:text-gray-500" />
                                    </div>
                                    <input
                                        type="number"
                                        id="coin_amount"
                                        value={coinAmount}
                                        onChange={(e) => setCoinAmount(e.target.value)}
                                        min="0"
                                        placeholder={coinAction === 'set' ? 'Masukkan jumlah coin baru' : 'Masukkan jumlah coin'}
                                        className="block w-full pl-10 pr-3 py-2.5 rounded-lg border-2 border-gray-300 bg-white text-gray-900 placeholder-gray-400 shadow-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-[#d4af37]/20 focus:border-[#d4af37] dark:border-gray-600 dark:bg-gray-800 dark:text-white dark:placeholder-gray-500 dark:focus:ring-[#b8941f]/20 dark:focus:border-[#b8941f] sm:text-sm font-medium"
                                    />
                                </div>
                                {coinAction !== 'set' && coinAmount && (
                                    <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
                                        Saldo setelah {coinAction === 'add' ? 'penambahan' : 'pengurangan'}:{' '}
                                        <span className="font-semibold text-[#d4af37] dark:text-[#b8941f]">
                                            {(
                                                coinAction === 'add'
                                                    ? (selectedUser.coin_balance || 0) + parseInt(coinAmount)
                                                    : Math.max(0, (selectedUser.coin_balance || 0) - parseInt(coinAmount))
                                            ).toLocaleString('id-ID')}{' '}
                                            NGD
                                        </span>
                                    </p>
                                )}
                            </div>

                            {/* Reason Input */}
                            <div>
                                <label htmlFor="coin_reason" className="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    Alasan (Opsional)
                                </label>
                                <textarea
                                    id="coin_reason"
                                    value={coinReason}
                                    onChange={(e) => setCoinReason(e.target.value)}
                                    placeholder="Masukkan alasan perubahan coin balance..."
                                    rows={3}
                                    className="block w-full px-3 py-2.5 rounded-lg border-2 border-gray-300 bg-white text-gray-900 placeholder-gray-400 shadow-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-[#d4af37]/20 focus:border-[#d4af37] dark:border-gray-600 dark:bg-gray-800 dark:text-white dark:placeholder-gray-500 dark:focus:ring-[#b8941f]/20 dark:focus:border-[#b8941f] sm:text-sm resize-none"
                                />
                            </div>
                        </div>
                    )}
                </Modal>
            </div>
        </AdminLayout>
    );
}

// Icons
function CoinIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 6v12m-3-2.818l.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
        </svg>
    );
}

