import React, { useEffect, useState, useCallback } from "react";
import { api } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Label } from "@/components/ui/label";
import {
    Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from "@/components/ui/dialog";
import { toast } from "sonner";
import {
    Users as UIcon, KeyRound, RefreshCw, Trash2, ShieldOff, Power, Copy, Eye, EyeOff,
    AlertTriangle, Activity, ShieldCheck, Lock,
} from "lucide-react";

const ROLE_BADGE = {
    admin: "bg-rose-500/20 text-rose-200 border-rose-500/40",
    manager: "bg-indigo-500/20 text-indigo-200 border-indigo-500/40",
    accountant: "bg-emerald-500/20 text-emerald-200 border-emerald-500/40",
    cashier: "bg-amber-500/20 text-amber-200 border-amber-500/40",
    viewer: "bg-slate-500/20 text-slate-200 border-slate-500/40",
    staff: "bg-amber-500/20 text-amber-200 border-amber-500/40",
};

export default function AdminUsers() {
    const [users, setUsers] = useState([]);
    const [roles, setRoles] = useState([]);
    const [loading, setLoading] = useState(true);
    const [active, setActive] = useState(null);

    const load = useCallback(async () => {
        setLoading(true);
        try {
            const [u, r] = await Promise.all([api.get("/users"), api.get("/permissions/roles")]);
            setUsers(u.data);
            setRoles(r.data?.roles || []);
        } catch (e) { toast.error(e.response?.data?.detail || "Failed to load"); }
        finally { setLoading(false); }
    }, []);

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

    return (
        <div className="space-y-5" data-testid="admin-users-page">
            <header>
                <div className="text-[10px] uppercase tracking-[0.2em] gold-text font-semibold">User Control</div>
                <h1 className="font-display text-3xl font-bold text-white tracking-tight flex items-center gap-2">
                    <UIcon className="h-7 w-7 text-amber-400" /> Users & Passwords
                </h1>
                <p className="text-sm text-blue-100/70 mt-1">Reset · Force-change · Deactivate · Revoke sessions</p>
            </header>

            <div className="glass-card rounded-2xl overflow-hidden">
                {loading ? <div className="p-8 text-center text-blue-200/60 text-sm">Loading…</div> : (
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="text-left text-[10px] uppercase tracking-wider text-blue-200/60 border-b border-white/10">
                                <th className="px-5 py-3">Name / Email</th>
                                <th>Role</th>
                                <th>Status</th>
                                <th>Last Activity</th>
                                <th className="text-right pr-5">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {users.map((u) => {
                                const roleObj = roles.find((r) => r.name === u.role);
                                const isActiveUser = u.is_active !== false;
                                return (
                                    <tr key={u.id} className="border-b border-white/5 hover:bg-white/5 transition" data-testid={`admin-user-row-${u.id}`}>
                                        <td className="px-5 py-3">
                                            <div className="font-medium text-white">{u.name}</div>
                                            <div className="text-xs text-blue-200/60 font-mono">{u.email}</div>
                                        </td>
                                        <td>
                                            <Badge variant="outline" className={`${ROLE_BADGE[u.role] || ROLE_BADGE.staff} text-[10px] capitalize`}>{roleObj?.label || u.role}</Badge>
                                        </td>
                                        <td>
                                            {isActiveUser
                                                ? <Badge className="bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 text-[10px]">ACTIVE</Badge>
                                                : <Badge className="bg-rose-500/20 text-rose-300 border border-rose-500/40 text-[10px]">DISABLED</Badge>}
                                        </td>
                                        <td className="text-xs text-blue-200/60">{(u.last_login || u.created_at || "").slice(0, 10)}</td>
                                        <td className="text-right pr-5">
                                            <Button size="sm" variant="outline" onClick={() => setActive(u)} className="border-amber-500/30 text-amber-300 hover:bg-amber-500/15" data-testid={`admin-user-actions-${u.id}`}>
                                                Manage
                                            </Button>
                                        </td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                )}
            </div>

            {active && <UserActionsDialog user={active} onClose={() => { setActive(null); load(); }} />}
        </div>
    );
}

function UserActionsDialog({ user, onClose }) {
    const [tab, setTab] = useState("reset");
    const [pw, setPw] = useState("");
    const [showPw, setShowPw] = useState(false);
    const [force, setForce] = useState(true);
    const [tempResult, setTempResult] = useState(null);
    const [activity, setActivity] = useState([]);
    const [busy, setBusy] = useState(false);

    useEffect(() => {
        api.get(`/admin/users/${user.id}/activity`).then((r) => setActivity(r.data || [])).catch(() => {});
    }, [user.id]);

    const doReset = async () => {
        if (pw.length < 8) { toast.error("Password must be at least 8 characters"); return; }
        setBusy(true);
        try {
            await api.post(`/admin/users/${user.id}/reset-password`, { new_password: pw, force_change: force });
            toast.success("Password reset");
            setPw("");
            setTempResult(null);
        } catch (e) { toast.error(e.response?.data?.detail || "Failed"); }
        finally { setBusy(false); }
    };

    const doTemp = async () => {
        setBusy(true);
        try {
            const { data } = await api.post(`/admin/users/${user.id}/temp-password`);
            setTempResult(data);
            toast.success("Temp password generated — share securely with user");
        } catch (e) { toast.error(e.response?.data?.detail || "Failed"); }
        finally { setBusy(false); }
    };

    const doToggle = async () => {
        if (!window.confirm(`${user.is_active === false ? "Activate" : "Deactivate"} this account?`)) return;
        try {
            const { data } = await api.post(`/admin/users/${user.id}/toggle-active`);
            toast.success(`Account ${data.is_active ? "activated" : "deactivated"}`);
            onClose();
        } catch (e) { toast.error(e.response?.data?.detail || "Failed"); }
    };

    const doRevoke = async () => {
        if (!window.confirm("Revoke ALL active sessions for this user? They will be logged out everywhere.")) return;
        try {
            await api.post(`/admin/users/${user.id}/revoke-sessions`);
            toast.success("Sessions revoked");
        } catch (e) { toast.error(e.response?.data?.detail || "Failed"); }
    };

    const doForce = async (enabled) => {
        try {
            await api.post(`/admin/users/${user.id}/force-change`, { enabled });
            toast.success(`Force-change ${enabled ? "enabled" : "disabled"}`);
        } catch (e) { toast.error(e.response?.data?.detail || "Failed"); }
    };

    return (
        <Dialog open onOpenChange={(v) => !v && onClose()}>
            <DialogContent className="max-w-2xl">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        Manage <span className="text-amber-500">{user.name}</span>
                        <Badge variant="outline" className="text-[10px] font-mono">{user.email}</Badge>
                    </DialogTitle>
                </DialogHeader>

                <div className="flex border-b">
                    {["reset", "temp", "actions", "activity"].map((t) => (
                        <button key={t} onClick={() => setTab(t)} className={`px-3 py-2 text-xs uppercase tracking-wider transition ${tab === t ? "text-amber-600 dark:text-amber-400 border-b-2 border-amber-500" : "text-muted-foreground hover:text-foreground"}`} data-testid={`uad-tab-${t}`}>
                            {t === "reset" ? "Reset PW" : t === "temp" ? "Temp PW" : t === "actions" ? "Actions" : "Activity"}
                        </button>
                    ))}
                </div>

                <div className="pt-3">
                    {tab === "reset" && (
                        <div className="space-y-3">
                            <Label className="text-xs uppercase">New Password</Label>
                            <div className="relative">
                                <Input type={showPw ? "text" : "password"} value={pw} onChange={(e) => setPw(e.target.value)} placeholder="At least 8 characters, mix letters+digits" className="pr-10" data-testid="uad-reset-pw" />
                                <button type="button" onClick={() => setShowPw((s) => !s)} className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground" tabIndex={-1}>
                                    {showPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                                </button>
                            </div>
                            <label className="flex items-center gap-2 text-sm cursor-pointer">
                                <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} className="accent-amber-500" />
                                Force user to change password on next login
                            </label>
                            <Button onClick={doReset} disabled={busy || pw.length < 8} className="w-full bg-amber-500 text-amber-950 hover:bg-amber-400" data-testid="uad-reset-submit">
                                <KeyRound className="h-4 w-4 mr-1.5" /> Set Password
                            </Button>
                        </div>
                    )}
                    {tab === "temp" && (
                        <div className="space-y-3">
                            <p className="text-sm text-muted-foreground">Generate a random 12-char password. User will be forced to change it on next login.</p>
                            <Button onClick={doTemp} disabled={busy} className="bg-primary hover:bg-primary/90" data-testid="uad-temp-submit">
                                <RefreshCw className={`h-4 w-4 mr-1.5 ${busy ? "animate-spin" : ""}`} /> Generate Temporary Password
                            </Button>
                            {tempResult?.temp_password && (
                                <div className="rounded-lg border border-amber-500/40 bg-amber-50/40 dark:bg-amber-950/30 p-3">
                                    <div className="text-[10px] uppercase tracking-wider text-amber-700 dark:text-amber-300 mb-1">SHARE THIS PASSWORD SECURELY</div>
                                    <div className="flex items-center gap-2">
                                        <code className="font-mono text-lg font-bold flex-1">{tempResult.temp_password}</code>
                                        <Button size="icon" variant="ghost" onClick={() => { navigator.clipboard.writeText(tempResult.temp_password); toast.success("Copied"); }}>
                                            <Copy className="h-4 w-4" />
                                        </Button>
                                    </div>
                                    <p className="text-xs text-amber-700/80 dark:text-amber-300/80 mt-2">⚠️ This is the only time you'll see this password.</p>
                                </div>
                            )}
                        </div>
                    )}
                    {tab === "actions" && (
                        <div className="space-y-2">
                            <ActionRow icon={Power} label={user.is_active === false ? "Activate Account" : "Deactivate Account"} desc="Lock or unlock login access" onClick={doToggle} testid="uad-action-toggle" />
                            <ActionRow icon={ShieldOff} label="Revoke All Sessions" desc="Force log-out across all devices" onClick={doRevoke} danger testid="uad-action-revoke" />
                            <ActionRow icon={Lock} label="Require Password Change" desc="User must set a new password next time" onClick={() => doForce(true)} testid="uad-action-force-on" />
                            <ActionRow icon={ShieldCheck} label="Lift Password Change Requirement" desc="Clear force-change flag" onClick={() => doForce(false)} testid="uad-action-force-off" />
                        </div>
                    )}
                    {tab === "activity" && (
                        <div className="space-y-2 max-h-72 overflow-y-auto">
                            {activity.length === 0 ? <p className="text-xs text-muted-foreground text-center py-6">No recent activity.</p> : activity.map((a) => (
                                <div key={a._id} className="flex items-center justify-between gap-2 border rounded-md px-3 py-2 text-xs">
                                    <div>
                                        <div className="font-mono text-[11px]">{a.action}</div>
                                        <div className="text-[10px] text-muted-foreground">{a.resource} · IP {a.ip || "—"}</div>
                                    </div>
                                    <span className="text-[10px] text-muted-foreground">{(a.ts || "").slice(0, 19).replace("T", " ")}</span>
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                <DialogFooter><Button variant="outline" onClick={onClose}>Close</Button></DialogFooter>
            </DialogContent>
        </Dialog>
    );
}

function ActionRow({ icon: Icon, label, desc, onClick, danger, testid }) {
    return (
        <button type="button" onClick={onClick} data-testid={testid} className={`w-full flex items-start gap-3 rounded-lg border px-3 py-2.5 text-left hover:bg-muted/40 transition ${danger ? "border-rose-500/30 hover:border-rose-500/50" : "border-border"}`}>
            <Icon className={`h-4 w-4 mt-0.5 flex-shrink-0 ${danger ? "text-rose-500" : "text-amber-500"}`} />
            <div className="min-w-0">
                <div className="text-sm font-semibold">{label}</div>
                <div className="text-[11px] text-muted-foreground">{desc}</div>
            </div>
        </button>
    );
}
