import React, { useState, useEffect } from 'react';
import userService from '../services/userService';
import billingService from '../services/billingService';
import { Users, Plus, Edit2, Shield, Power, CheckCircle, XCircle, Trash2, Key, Search, User as UserIcon, Eye, EyeOff, RefreshCw, Send, Mail, Phone, Lock } from 'lucide-react';
import { clsx } from 'clsx';

const UserList = () => {
    const [users, setUsers] = useState([]);
    const [roles, setRoles] = useState([]);
    const [clients, setClients] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingUser, setEditingUser] = useState(null);
    const [showPassword, setShowPassword] = useState(false);
    const [formData, setFormData] = useState({
        fullName: '',
        email: '',
        password: '',
        roleId: '',
        clientId: '',
        phone: ''
    });

    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = async () => {
        setLoading(true);
        try {
            const [userRes, roleRes, clientRes] = await Promise.all([
                userService.getAll(),
                userService.getRoles(),
                billingService.getClients()
            ]);
            setUsers(userRes.data);
            setRoles(roleRes.data);
            setClients(clientRes.data || []);
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    };

    const handleSave = async (e) => {
        e.preventDefault();
        try {
            if (editingUser) {
                await userService.update(editingUser.id, formData);
            } else {
                await userService.create(formData);
            }
            setIsModalOpen(false);
            fetchData();
            setEditingUser(null);
            setFormData({ fullName: '', email: '', password: '', roleId: '', clientId: '', phone: '' });
        } catch (err) {
            alert(err.response?.data?.error || 'Failed to save user');
        }
    };

    const handleEdit = (user) => {
        setEditingUser(user);
        setFormData({
            fullName: user.fullName,
            email: user.email,
            password: '',
            roleId: user.roleId,
            clientId: user.clientId || '',
            phone: user.phone || ''
        });
        setIsModalOpen(true);
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this user? This action is irreversible.')) {
            try {
                await userService.delete(id);
                fetchData();
            } catch (err) {
                alert('Failed to delete user');
            }
        }
    };

    const toggleStatus = async (id) => {
        if (window.confirm('Change user access status?')) {
            await userService.toggleStatus(id);
            fetchData();
        }
    };

    const handleResetPassword = async (id) => {
        if (window.confirm('Reset this user\'s password? A new password will be created and sent to the user.')) {
            try {
                const newPwd = await userService.resetPassword(id);
                alert(`Password reset successful. New password: ${newPwd.data.newPassword}`);
            } catch (err) {
                alert('Failed to reset password');
            }
        }
    };

    const handleResendCredentials = async (id) => {
        if (window.confirm('Resend login details? This will regenerate their password and email them the new credentials along with the portal link.')) {
            try {
                const res = await userService.resendCredentials(id);
                alert(`Credentials resent! New temporary password: ${res.data.newPassword}`);
                fetchData();
            } catch (err) {
                alert(err.response?.data?.error || 'Failed to resend credentials');
            }
        }
    };

    const selectedRole = roles.find(r => String(r.id) === String(formData.roleId));
    const isClientRole = selectedRole?.constant?.trim().toUpperCase() === 'CLIENT';

    const handleClientSelect = (clientId) => {
        const client = clients.find(c => c.id === clientId);
        if (client) {
            setFormData({
                ...formData,
                clientId: client.id,
                fullName: client.name,
                email: client.email,
                phone: client.phone || client.mobile || ''
            });
        } else {
            setFormData({ ...formData, clientId: '' });
        }
    };

    const StatusBadge = ({ active }) => (
        <div className={clsx(
            "inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-widest border transition-all duration-300",
            active
                ? "bg-emerald-500/10 text-emerald-500 border-emerald-500/20 shadow-sm shadow-emerald-500/5"
                : "bg-rose-500/10 text-rose-500 border-rose-500/20 shadow-sm shadow-rose-500/5"
        )}>
            {active ? <CheckCircle className="w-3.5 h-3.5" /> : <XCircle className="w-3.5 h-3.5" />}
            {active ? 'Active' : 'Inactive'}
        </div>
    );

    return (
        <div className="space-y-10 animate-slide-up">
            {/* Premium Header */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                <div className="flex items-center gap-4 sm:gap-5 min-w-0">
                    <div className="p-3 sm:p-4 bg-primary rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                        <Users className="w-6 h-6 sm:w-8 sm:h-8 shrink-0" />
                    </div>
                    <div className="min-w-0">
                        <h1 className="text-xl sm:text-2xl font-extrabold text-slate-800 dark:text-white tracking-tight leading-none truncate">User Management</h1>
                        <div className="flex items-center gap-2 mt-1">
                            <span className="text-[10px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest whitespace-nowrap">System Access</span>
                            <div className="w-1 h-1 bg-slate-300 dark:bg-slate-700 rounded-full shrink-0"></div>
                            <span className="text-[10px] font-black text-primary uppercase tracking-widest whitespace-nowrap truncate">{users.length} Users</span>
                        </div>
                    </div>
                </div>
                <button
                    onClick={() => {
                        setEditingUser(null);
                        setFormData({ fullName: '', email: '', password: '', roleId: '', clientId: '', phone: '' });
                        setIsModalOpen(true);
                    }}
                    className="btn-primary flex items-center justify-center gap-2 px-8 w-full md:w-auto h-12 lg:h-14"
                >
                    <Plus className="w-4 h-4 shrink-0" />
                    <span className="text-[10px] sm:text-[11px] font-black uppercase tracking-widest whitespace-nowrap">Add User</span>
                </button>
            </div>

            {/* Users Table */}
            <div className="premium-card overflow-hidden">
                <div className="overflow-x-auto">
                    <table className="w-full text-left min-w-[900px]">
                        <thead>
                            <tr className="bg-slate-50/50 dark:bg-slate-900/40 border-b border-slate-100 dark:border-slate-800">
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-center w-20">#</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Full Name</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Role</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest">Status</th>
                                <th className="px-8 py-5 text-[11px] font-black text-slate-400 dark:text-slate-500 uppercase tracking-widest text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100 dark:divide-slate-800/50">
                            {loading ? (
                                <tr>
                                    <td colSpan="5" className="p-24 text-center">
                                        <div className="flex flex-col items-center gap-4">
                                            <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"></div>
                                            <p className="text-[11px] font-black text-slate-400 uppercase tracking-[0.2em]">Loading users...</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : users.length === 0 ? (
                                <tr>
                                    <td colSpan="5" className="p-24 text-center">
                                        <div className="max-w-xs mx-auto space-y-4">
                                            <div className="w-16 h-16 bg-slate-50 dark:bg-slate-900 rounded-3xl flex items-center justify-center mx-auto">
                                                <Users className="w-8 h-8 text-slate-200 dark:text-slate-800" />
                                            </div>
                                            <h3 className="text-sm font-extrabold text-slate-800 dark:text-white uppercase tracking-tight">No Users Found</h3>
                                            <p className="text-[11px] text-slate-500 dark:text-slate-500 leading-relaxed font-bold uppercase tracking-widest">Add your first user to get started.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                users.map((user, idx) => (
                                    <tr key={user.id} className="group hover:bg-slate-50/50 dark:hover:bg-slate-900/30 transition-all duration-300">
                                        <td className="px-8 py-6 text-center text-xs font-black text-slate-300 dark:text-slate-700 group-hover:text-primary transition-colors">{String(idx + 1).padStart(2, '0')}</td>
                                        <td className="px-8 py-6">
                                            <div className="flex items-center gap-4">
                                                <div className="w-11 h-11 bg-gradient-to-br from-primary/10 to-primary/5 text-primary rounded-2xl flex items-center justify-center font-black text-sm shadow-sm border border-primary/10 shrink-0">
                                                    {user.fullName.charAt(0)}
                                                </div>
                                                <div className="min-w-0">
                                                    <p className="text-sm font-black text-slate-800 dark:text-white tracking-tight truncate">{user.fullName}</p>
                                                    <div className="flex flex-wrap items-center gap-3 mt-1">
                                                        <span className="text-[10px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-widest flex items-center gap-1 truncate">
                                                            <Mail className="w-3 h-3" /> {user.email}
                                                        </span>
                                                        {user.credentialsSent ? (
                                                            <div className="flex items-center gap-1.5 px-2 py-0.5 bg-emerald-500/5 text-emerald-500 rounded-md text-[8px] font-black uppercase tracking-tighter shrink-0">
                                                                <CheckCircle className="w-2.5 h-2.5" /> Active
                                                            </div>
                                                        ) : (
                                                            <div className="flex items-center gap-1.5 px-2 py-0.5 bg-amber-500/5 text-amber-500 rounded-md text-[8px] font-black uppercase tracking-tighter shrink-0">
                                                                <Key className="w-2.5 h-2.5" /> Pending
                                                            </div>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-8 py-6">
                                            <div className={clsx(
                                                "inline-flex items-center gap-2 px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-widest border transition-all duration-300",
                                                user.Role?.constant === 'SUPER_ADMIN'
                                                    ? "bg-primary text-white border-primary shadow-lg shadow-primary/20"
                                                    : "bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-slate-400 border-slate-200 dark:border-slate-700"
                                            )}>
                                                <Shield className="w-3.5 h-3.5" /> {user.Role?.name}
                                            </div>
                                        </td>
                                        <td className="px-8 py-6">
                                            <StatusBadge active={user.isActive} />
                                        </td>
                                        <td className="px-8 py-6 text-right">
                                            <div className="flex justify-end items-center gap-1 opacity-100 lg:opacity-0 lg:group-hover:opacity-100 transition-all lg:translate-x-2 lg:group-hover:translate-x-0 duration-300">
                                                <button onClick={() => handleEdit(user)} className="p-2.5 text-slate-400 hover:text-primary hover:bg-primary/5 dark:hover:bg-primary/10 rounded-xl transition-all shrink-0 h-10 w-10 flex items-center justify-center" title="Edit User"><Edit2 className="w-4 h-4 shrink-0" /></button>
                                                <button onClick={() => handleResendCredentials(user.id)} className="p-2.5 text-slate-400 hover:text-indigo-500 hover:bg-indigo-50 dark:hover:bg-indigo-500/10 rounded-xl transition-all shrink-0 h-10 w-10 flex items-center justify-center" title="Resend Credentials"><Send className="w-4 h-4 shrink-0" /></button>
                                                <button onClick={() => handleResetPassword(user.id)} className="p-2.5 text-slate-400 hover:text-amber-500 hover:bg-amber-50 dark:hover:bg-amber-500/10 rounded-xl transition-all shrink-0 h-10 w-10 flex items-center justify-center" title="Reset Password"><Key className="w-4 h-4 shrink-0" /></button>
                                                <button onClick={() => toggleStatus(user.id)} className="p-2.5 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 rounded-xl transition-all shrink-0 h-10 w-10 flex items-center justify-center" title="Toggle Status"><Power className="w-4 h-4 shrink-0" /></button>
                                                <button onClick={() => handleDelete(user.id)} className="p-2.5 text-slate-300 hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 rounded-xl transition-all shrink-0 h-10 w-10 flex items-center justify-center" title="Delete User"><Trash2 className="w-4 h-4 shrink-0" /></button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>
            </div>

            {/* Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm animate-in fade-in duration-300">
                    <div className="bg-white dark:bg-slate-900 w-full max-w-xl rounded-[2rem] sm:rounded-[2.5rem] shadow-4xl relative overflow-hidden premium-card flex flex-col max-h-[90vh]">
                        <div className="absolute top-0 left-0 w-full h-1.5 sm:h-2 bg-primary shadow-lg shadow-primary/20 shrink-0" />

                        <div className="p-6 sm:p-10 pb-4 flex items-center gap-4 sm:gap-5 shrink-0">
                            <div className="p-3 sm:p-4 bg-primary rounded-xl sm:rounded-2xl text-white shadow-xl shadow-primary/20 shrink-0">
                                <Users className="w-6 h-6 sm:w-7 sm:h-7" />
                            </div>
                            <div>
                                <h2 className="text-xl sm:text-2xl font-black text-slate-800 dark:text-white tracking-tight">
                                    {editingUser ? 'Edit User' : 'Add User'}
                                </h2>
                                <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Enter user details</p>
                            </div>
                        </div>

                        <form onSubmit={handleSave} className="flex-1 overflow-y-auto p-6 sm:p-10 pt-4 space-y-8 custom-scrollbar">
                            <div className="space-y-4">
                                <label className="premium-label">User Role</label>
                                <select
                                    required
                                    className="premium-input !appearance-auto"
                                    value={formData.roleId}
                                    onChange={(e) => setFormData({ ...formData, roleId: e.target.value, clientId: '', email: '', fullName: '', phone: '' })}
                                >
                                    <option value="">Select Role...</option>
                                    {roles.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
                                </select>
                            </div>

                            {isClientRole && (
                                <div className="space-y-4 animate-in slide-in-from-top-4 duration-500 p-5 sm:p-6 bg-primary/5 rounded-[1.5rem] border border-primary/10">
                                    <label className="text-[10px] font-black text-primary uppercase tracking-[0.2em] flex items-center gap-2 mb-3">
                                        Link to Client
                                    </label>
                                    <select
                                        required
                                        className="premium-input !bg-white dark:!bg-slate-900 !appearance-auto"
                                        value={formData.clientId}
                                        onChange={(e) => handleClientSelect(e.target.value)}
                                    >
                                        <option value="">Select Client...</option>
                                        {clients.map(c => (
                                            <option key={c.id} value={c.id}>{c.name}</option>
                                        ))}
                                    </select>
                                    <p className="text-[9px] font-black text-primary/40 uppercase tracking-widest mt-2 px-1">Details will be updated from the client record</p>
                                </div>
                            )}

                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-8">
                                <div className="sm:col-span-2 space-y-4">
                                    <label className="premium-label">Full Name</label>
                                    <div className="relative group">
                                        <UserIcon className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors" />
                                        <input
                                            required
                                            disabled={isClientRole && formData.clientId}
                                            placeholder="John Doe"
                                            className="premium-input !pl-12 disabled:opacity-40"
                                            value={formData.fullName}
                                            onChange={(e) => setFormData({ ...formData, fullName: e.target.value })}
                                        />
                                    </div>
                                </div>

                                <div className="space-y-4">
                                    <label className="premium-label">Email Address</label>
                                    <div className="relative group">
                                        <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors" />
                                        <input
                                            required
                                            type="email"
                                            disabled={isClientRole && formData.clientId}
                                            placeholder="john@example.com"
                                            className="premium-input !pl-12 disabled:opacity-40"
                                            value={formData.email}
                                            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                        />
                                    </div>
                                </div>

                                <div className="space-y-4">
                                    <label className="premium-label">Phone Number</label>
                                    <div className="relative group">
                                        <Phone className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors" />
                                        <input
                                            type="tel"
                                            placeholder="+123..."
                                            className="premium-input !pl-12"
                                            value={formData.phone}
                                            onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                                        />
                                    </div>
                                </div>

                                <div className="sm:col-span-2 space-y-4">
                                    <div className="flex justify-between items-center">
                                        <label className="premium-label !mb-0">Password</label>
                                        <button
                                            type="button"
                                            onClick={() => {
                                                const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
                                                let retVal = "";
                                                for (let i = 0; i < 16; i++) {
                                                    retVal += charset.charAt(Math.floor(Math.random() * charset.length));
                                                }
                                                setFormData({ ...formData, password: retVal });
                                                setShowPassword(true);
                                            }}
                                            className="text-[9px] font-black text-primary hover:text-white hover:bg-primary bg-primary/5 px-3 py-1 rounded-full border border-primary/20 transition-all flex items-center gap-1.5 uppercase tracking-widest"
                                        >
                                            <RefreshCw className="w-3 h-3" /> Generate
                                        </button>
                                    </div>
                                    <div className="relative group">
                                        <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-300 group-focus-within:text-primary transition-colors" />
                                        <input
                                            required={!editingUser}
                                            type={showPassword ? "text" : "password"}
                                            placeholder={editingUser ? "••••••••" : "Secure Password"}
                                            className="premium-input !pl-12 !pr-12"
                                            value={formData.password}
                                            onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setShowPassword(!showPassword)}
                                            className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-primary transition-colors"
                                        >
                                            {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                                        </button>
                                    </div>
                                    {editingUser && <p className="text-[9px] font-black text-amber-500 uppercase tracking-widest mt-2 px-1">Leave empty to keep existing password</p>}
                                </div>
                            </div>

                            <div className="flex flex-col sm:flex-row gap-4 pt-8 border-t border-slate-100 dark:border-slate-800">
                                <button
                                    type="button"
                                    onClick={() => { setIsModalOpen(false); setEditingUser(null); }}
                                    className="flex-1 py-4 text-[11px] font-black text-slate-400 uppercase tracking-widest hover:bg-slate-50 dark:hover:bg-slate-900 rounded-2xl transition-all order-2 sm:order-1"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    className="btn-primary flex-[1.5] py-4 shadow-2xl flex items-center justify-center gap-2 order-1 sm:order-2"
                                >
                                    <CheckCircle className="w-4 h-4" />
                                    <span>{editingUser ? 'Save Changes' : 'Create User'}</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default UserList;
