import React, { useState } from 'react';
import { useForm, router } from '@inertiajs/react';
import { AdminLayout } from '../AdminLayout';
import { SEOHead } from '@/Components/SEOHead';
import { Pagination } from '@/Components/Pagination';
import { ConfirmDeleteModal } from '@/Components/ConfirmDeleteModal';
import { UserPlus, SquarePen, Trash2, X, Search, Plus, Eye, EyeOff } from 'lucide-react';

interface UsersIndexProps {
    users: any;
    filters?: {
        search?: string;
        role?: string;
    };
}

export default function Index({ users, filters = {} }: UsersIndexProps) {
    const [search, setSearch] = useState(filters.search || '');
    const [roleFilter, setRoleFilter] = useState(filters.role || 'all');
    const [editingUser, setEditingUser] = useState<any | null>(null);
    const [formOpen, setFormOpen] = useState(false);
    const [deleteId, setDeleteId] = useState<number | null>(null);
    const [showPassword, setShowPassword] = useState(false);


    const { data, setData, post, put, processing, reset } = useForm({
        name: '',
        email: '',
        password: '',
        role: 'admin',
    });

    const usersList = users.data ? users.data : users;

    const handleSearch = (e?: React.FormEvent) => {
        if (e) e.preventDefault();
        router.get('/admin/users', {
            search: search || undefined,
            role: roleFilter !== 'all' ? roleFilter : undefined,
        }, {
            preserveState: true,
            preserveScroll: true,
        });
    };

    const handleClearFilters = () => {
        setSearch('');
        setRoleFilter('all');
        router.get('/admin/users');
    };

    const startEdit = (u: any) => {
        setEditingUser(u);
        setFormOpen(true);
        setData({
            name: u.name,
            email: u.email,
            password: '',
            role: u.role || 'admin',
        });
    };

    const cancelEdit = () => {
        setEditingUser(null);
        setFormOpen(false);
        reset();
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (editingUser) {
            put(`/admin/users/${editingUser.id}`, {
                preserveScroll: true,
                onSuccess: () => cancelEdit(),
            });
        } else {
            post('/admin/users', {
                preserveScroll: true,
                onSuccess: () => {
                    reset();
                    setFormOpen(false);
                },
            });
        }
    };

    const handleDeleteUser = () => {
        if (deleteId) {
            router.delete(`/admin/users/${deleteId}`);
        }
    };

    return (
        <AdminLayout title="Users & Role-Based Access Control (RBAC)">
            <SEOHead title="Users & RBAC | Tech in Soul Admin" description="Manage user accounts, roles, permissions, and administrative access." />

            <div className="space-y-6">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    <div>
                        <h2 className="text-xl font-bold text-white">Admin Accounts & Team Access</h2>
                        <p className="text-xs text-slate-400">Manage administrator roles, editorial permissions, and staff login credentials.</p>
                    </div>
                    <button
                        type="button"
                        onClick={() => {
                            if (formOpen && !editingUser) {
                                setFormOpen(false);
                            } else {
                                setEditingUser(null);
                                reset();
                                setFormOpen(true);
                            }
                        }}
                        className="btn-aqua px-4 py-2 rounded-xl text-xs font-bold flex items-center gap-1.5 self-start sm:self-auto"
                    >
                        <Plus className="w-4 h-4" /> {formOpen && !editingUser ? 'Close Form' : 'Add New User'}
                    </button>
                </div>

                {/* Form to Create or Edit User */}
                {formOpen && (
                    <form onSubmit={handleSubmit} className="glass-card rounded-2xl p-6 sm:p-8 space-y-6 border border-slate-800 animate-in fade-in">
                        <div className="flex items-center justify-between pb-3 border-b border-slate-800">
                            <h3 className="text-sm font-bold text-white flex items-center gap-2">
                                {editingUser ? <SquarePen className="w-4 h-4 text-[#00F2FE]" /> : <UserPlus className="w-4 h-4 text-[#00F2FE]" />}
                                {editingUser ? `Edit Account: ${editingUser.name}` : 'Create Admin Account'}
                            </h3>
                            <button type="button" onClick={cancelEdit} className="text-xs text-rose-400 hover:underline flex items-center gap-1">
                                <X className="w-3.5 h-3.5" /> Cancel
                            </button>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
                            <div>
                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Full Name *</label>
                                <input
                                    type="text"
                                    value={data.name}
                                    onChange={(e) => setData('name', e.target.value)}
                                    required
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                />
                            </div>

                            <div>
                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Email *</label>
                                <input
                                    type="email"
                                    value={data.email}
                                    onChange={(e) => setData('email', e.target.value)}
                                    required
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                />
                            </div>

                            <div>
                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">
                                    {editingUser ? 'New Password (Optional)' : 'Password *'}
                                </label>
                                <div className="relative">
                                    <input
                                        type={showPassword ? 'text' : 'password'}
                                        value={data.password}
                                        onChange={(e) => setData('password', e.target.value)}
                                        required={!editingUser}
                                        placeholder={editingUser ? 'Leave blank to keep current' : 'Enter account password'}
                                        className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 pr-10 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPassword(!showPassword)}
                                        className="absolute right-3 top-2 text-slate-400 hover:text-white transition-colors focus:outline-none"
                                        tabIndex={-1}
                                        aria-label={showPassword ? 'Hide password' : 'Show password'}
                                    >
                                        {showPassword ? <EyeOff className="w-3.5 h-3.5 text-[#00F2FE]" /> : <Eye className="w-3.5 h-3.5" />}
                                    </button>
                                </div>
                            </div>


                            <div>
                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Role *</label>
                                <select
                                    value={data.role}
                                    onChange={(e) => setData('role', e.target.value)}
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                >
                                    <option value="super_admin">Super Admin</option>
                                    <option value="admin">Admin</option>
                                    <option value="editor">Editor</option>
                                    <option value="author">Author</option>
                                    <option value="support">Support</option>
                                </select>
                            </div>
                        </div>

                        <div className="flex items-center gap-3">
                            <button
                                type="submit"
                                disabled={processing}
                                className="btn-aqua px-5 py-2.5 rounded-xl font-bold text-xs flex items-center gap-1.5"
                            >
                                {editingUser ? <SquarePen className="w-4 h-4" /> : <UserPlus className="w-4 h-4" />}
                                {editingUser ? 'Update User Account' : 'Create User Account'}
                            </button>
                            <button
                                type="button"
                                onClick={cancelEdit}
                                className="px-4 py-2.5 rounded-xl text-xs font-bold bg-slate-800/80 hover:bg-slate-800 text-slate-300"
                            >
                                Cancel
                            </button>
                        </div>
                    </form>
                )}

                {/* Search & Role Filter Bar */}
                <div className="glass-card rounded-2xl p-4 border border-slate-800">
                    <form onSubmit={handleSearch} className="flex flex-col sm:flex-row items-center gap-3">
                        <div className="relative flex-grow w-full">
                            <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                            <input
                                type="text"
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                placeholder="Search users by name or email address..."
                                className="w-full bg-[#060B18] border border-slate-800 rounded-xl pl-10 pr-4 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-[#00F2FE]"
                            />
                        </div>

                        <div className="flex items-center gap-2 w-full sm:w-auto">
                            <select
                                value={roleFilter}
                                onChange={(e) => setRoleFilter(e.target.value)}
                                className="bg-[#060B18] border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-300 focus:outline-none focus:border-[#00F2FE]"
                            >
                                <option value="all">All Roles</option>
                                <option value="super_admin">Super Admin</option>
                                <option value="admin">Admin</option>
                                <option value="editor">Editor</option>
                                <option value="author">Author</option>
                                <option value="support">Support</option>
                            </select>

                            <button type="submit" className="btn-aqua px-4 py-2 rounded-xl text-xs font-bold shrink-0">
                                Filter
                            </button>

                            {(search || roleFilter !== 'all') && (
                                <button
                                    type="button"
                                    onClick={handleClearFilters}
                                    className="p-2 rounded-xl bg-slate-800/60 hover:bg-slate-800 text-slate-400 hover:text-white text-xs font-semibold shrink-0 transition-colors"
                                    title="Clear filters"
                                >
                                    <X className="w-4 h-4" />
                                </button>
                            )}
                        </div>
                    </form>
                </div>

                {/* Table */}
                <div className="glass-card rounded-2xl overflow-hidden border border-slate-800">
                    <table className="w-full text-left text-sm text-slate-300">
                        <thead className="bg-[#060B18] text-xs font-bold text-slate-400 uppercase border-b border-slate-800">
                            <tr>
                                <th className="px-6 py-4">Name</th>
                                <th className="px-6 py-4">Email</th>
                                <th className="px-6 py-4">Role</th>
                                <th className="px-6 py-4 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-800/80">
                            {usersList.length === 0 ? (
                                <tr>
                                    <td colSpan={4} className="px-6 py-12 text-center text-slate-500">
                                        <div className="flex flex-col items-center gap-2">
                                            <p className="text-sm font-semibold text-slate-400">No user accounts found</p>
                                            <p className="text-xs text-slate-500">Use the form above to add a new admin or staff account.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                usersList.map((u: any) => (
                                    <tr key={u.id} className="hover:bg-[#060B18]/40 transition-colors">
                                        <td className="px-6 py-4 font-bold text-white">{u.name}</td>
                                        <td className="px-6 py-4 text-xs font-mono text-[#00F2FE]">{u.email}</td>
                                        <td className="px-6 py-4">
                                            <span className="text-[10px] font-semibold px-2.5 py-0.5 rounded-full bg-[#00F2FE]/10 text-[#00F2FE] border border-[#00F2FE]/20 capitalize">
                                                {u.role}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4 text-right">
                                            <div className="flex items-center justify-end gap-2">
                                                <button
                                                    onClick={() => startEdit(u)}
                                                    className="inline-flex items-center justify-center p-1.5 rounded-lg text-slate-400 hover:text-[#00F2FE] hover:bg-[#00F2FE]/10 transition-colors"
                                                    title="Edit User"
                                                >
                                                    <SquarePen className="w-4 h-4" />
                                                </button>
                                                <button
                                                    onClick={() => setDeleteId(u.id)}
                                                    className="inline-flex items-center justify-center p-1.5 rounded-lg text-rose-400 hover:text-rose-300 hover:bg-rose-500/10 transition-colors"
                                                    title="Delete User"
                                                >
                                                    <Trash2 className="w-4 h-4" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>

                    {users.links && (
                        <Pagination links={users.links} from={users.from} to={users.to} total={users.total} />
                    )}
                </div>
            </div>

            <ConfirmDeleteModal
                isOpen={deleteId !== null}
                title="Delete User Account?"
                message="Are you sure you want to delete this user account? Access to the admin panel will be revoked immediately."
                onConfirm={handleDeleteUser}
                onClose={() => setDeleteId(null)}
            />
        </AdminLayout>
    );
}
