/**
 * PilotActivationWizard — single super-admin card that activates the
 * pilot bundle (offline + auto-msg flags) for ONE user with a 48h soak.
 *
 * Mounted inside the existing `/admin/features` page so it adds no new
 * route. The wizard is admin-only (the parent route is already gated).
 *
 * UX flow:
 *   1. Pick a user from the dropdown
 *   2. Optional note + soak duration (default 48h)
 *   3. Click "Activate Pilot" → POST /api/pilot/activate
 *   4. The active-pilots list below shows live countdown + Revoke + Promote
 *
 * The actual feature gating is done by the existing `feature_flags` engine —
 * this wizard is just a thin orchestrator that flips three flag's
 * `enabled_users[]` for the chosen user_id and tracks the 48h timer in
 * Mongo so a forgotten pilot is automatically demoted.
 */
import React, { useCallback, useEffect, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Rocket, Clock, ShieldCheck, X, Zap, AlertTriangle, RotateCw } from "lucide-react";
import { toast } from "sonner";
import { api, formatApiError } from "@/lib/api";

export default function PilotActivationWizard() {
    const [users, setUsers] = useState([]);
    const [pilots, setPilots] = useState([]);
    const [userId, setUserId] = useState("");
    const [note, setNote] = useState("");
    const [hours, setHours] = useState(48);
    const [busy, setBusy] = useState(false);

    const refresh = useCallback(async () => {
        try {
            const [u, p] = await Promise.all([
                api.get("/admin/users"),
                api.get("/pilot"),
            ]);
            setUsers(u.data?.items || u.data || []);
            setPilots(p.data || []);
        } catch (e) {
            // Silent — section just shows the empty state.
        }
    }, []);
    useEffect(() => { refresh(); const id = setInterval(refresh, 30_000); return () => clearInterval(id); }, [refresh]);

    const activate = async () => {
        if (!userId) { toast.error("Pick a user first"); return; }
        setBusy(true);
        try {
            const { data } = await api.post("/pilot/activate", {
                user_id: userId, soak_hours: hours, note: note || "",
            });
            toast.success(`Pilot activated — expires ${new Date(data.expires_at).toLocaleString("en-IN")}`);
            setUserId(""); setNote(""); setHours(48);
            refresh();
        } catch (e) {
            toast.error(formatApiError(e?.response?.data?.detail || "Activation failed"));
        } finally { setBusy(false); }
    };

    const revoke = async (uid) => {
        if (!window.confirm("Revoke pilot for this user? Their offline + auto-msg access will turn off immediately.")) return;
        try {
            await api.post("/pilot/revoke", { user_id: uid });
            toast.success("Pilot revoked");
            refresh();
        } catch { toast.error("Revoke failed"); }
    };

    const promote = async (uid) => {
        if (!window.confirm("Promote pilot flags GLOBALLY for ALL users? This is the final step — every customer will see offline + auto-msg behaviour. Continue?")) return;
        try {
            await api.post("/pilot/promote", { user_id: uid });
            toast.success("Promoted — flags now enabled globally for everyone");
            refresh();
        } catch { toast.error("Promote failed"); }
    };

    return (
        <Card data-testid="pilot-activation-wizard" className="border-amber-500/30">
            <CardContent className="p-5 space-y-4">
                <div className="flex items-start gap-3">
                    <div className="p-2 rounded-lg bg-gradient-to-br from-amber-500/30 to-amber-700/10">
                        <Rocket className="h-4 w-4 text-amber-400" />
                    </div>
                    <div className="flex-1">
                        <h2 className="font-display text-lg font-semibold flex items-center gap-2">
                            Pilot Customer Activation
                            <Badge variant="outline" className="text-[10px] font-normal">v12.41</Badge>
                        </h2>
                        <p className="text-xs text-muted-foreground mt-0.5">
                            Ek pilot user ko 48h ke liye Phase 1 (Offline) + Phase 2 (Auto Transaction Messages) dono enable karen.
                            Soak timer khatam hone par auto-demote ho jaata hai. Manual revoke ya promote bhi available.
                        </p>
                    </div>
                </div>

                {/* Wizard */}
                <div className="grid grid-cols-1 lg:grid-cols-4 gap-2 p-3 rounded-md bg-muted/30">
                    <div className="lg:col-span-2">
                        <Label className="text-xs">Pilot User</Label>
                        <select
                            value={userId}
                            onChange={(e) => setUserId(e.target.value)}
                            className="w-full mt-1 text-sm rounded-md border border-input bg-background px-2 py-1.5"
                            data-testid="pilot-user-select"
                        >
                            <option value="">-- pick a user --</option>
                            {users.map((u) => (
                                <option key={u.id || u._id} value={u.id || u._id}>
                                    {u.name || u.email} {u.role === "admin" ? "(admin)" : ""}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div>
                        <Label className="text-xs">Soak (hours)</Label>
                        <Input
                            type="number"
                            min={1} max={168}
                            value={hours}
                            onChange={(e) => setHours(Math.max(1, Math.min(168, parseInt(e.target.value || "48"))))}
                            className="mt-1 text-sm"
                            data-testid="pilot-hours-input"
                        />
                    </div>
                    <div className="flex flex-col">
                        <Label className="text-xs">&nbsp;</Label>
                        <Button
                            onClick={activate}
                            disabled={busy || !userId}
                            className="mt-1 bg-amber-500 hover:bg-amber-400 text-amber-950"
                            data-testid="pilot-activate-btn"
                        >
                            <Zap className="h-3.5 w-3.5 mr-1" />
                            {busy ? "Activating..." : "Activate Pilot"}
                        </Button>
                    </div>
                    <div className="lg:col-span-4">
                        <Label className="text-xs">Note (optional)</Label>
                        <Input
                            value={note}
                            onChange={(e) => setNote(e.target.value)}
                            placeholder="e.g. pilot for Goa branch, testing on Vyapar migration"
                            className="mt-1 text-sm"
                            data-testid="pilot-note-input"
                        />
                    </div>
                </div>

                {/* Active pilots list */}
                <div>
                    <div className="flex items-center justify-between mb-2">
                        <h3 className="text-sm font-medium flex items-center gap-1.5">
                            <ShieldCheck className="h-3.5 w-3.5 text-emerald-500" />
                            Active Pilots ({pilots.length})
                        </h3>
                        <button onClick={refresh} className="text-[10px] text-muted-foreground hover:text-foreground" data-testid="pilot-refresh">
                            <RotateCw className="h-3 w-3 inline" /> refresh
                        </button>
                    </div>
                    {pilots.length === 0 ? (
                        <p className="text-xs text-muted-foreground text-center py-4 border border-dashed border-border/60 rounded">
                            Koi active pilot nahi. Upar user pick karke &quot;Activate&quot; karein.
                        </p>
                    ) : (
                        <div className="space-y-1.5">
                            {pilots.map((p) => (
                                <PilotRow key={p.id} pilot={p} onRevoke={revoke} onPromote={promote} />
                            ))}
                        </div>
                    )}
                </div>
            </CardContent>
        </Card>
    );
}

function PilotRow({ pilot, onRevoke, onPromote }) {
    const hours = pilot.hours_remaining || 0;
    const tone = hours < 6 ? "text-rose-500" : hours < 12 ? "text-amber-500" : "text-emerald-500";
    return (
        <div
            className="flex items-center justify-between gap-2 p-2.5 rounded-md border border-border/70 hover:border-amber-500/40 transition"
            data-testid={`pilot-row-${pilot.user_id}`}
        >
            <div className="min-w-0 flex-1">
                <div className="text-sm font-medium truncate">{pilot.user_name || pilot.user_email}</div>
                <div className="flex items-center gap-2 text-[11px] mt-0.5">
                    <span className={`flex items-center gap-0.5 ${tone}`}>
                        <Clock className="h-3 w-3" /> {hours.toFixed(1)}h left
                    </span>
                    <span className="text-muted-foreground truncate">{pilot.user_email}</span>
                    {hours < 6 && <AlertTriangle className="h-3 w-3 text-rose-500" />}
                </div>
                {pilot.note && <div className="text-[10px] text-muted-foreground italic mt-0.5 truncate">{pilot.note}</div>}
            </div>
            <div className="flex items-center gap-1">
                <Button
                    size="sm" variant="outline"
                    onClick={() => onPromote(pilot.user_id)}
                    className="h-7 text-xs border-emerald-500/40 hover:bg-emerald-500/10"
                    data-testid={`pilot-promote-${pilot.user_id}`}
                >
                    Promote
                </Button>
                <Button
                    size="sm" variant="outline"
                    onClick={() => onRevoke(pilot.user_id)}
                    className="h-7 text-xs border-rose-500/40 hover:bg-rose-500/10"
                    data-testid={`pilot-revoke-${pilot.user_id}`}
                >
                    <X className="h-3 w-3 mr-1" /> Revoke
                </Button>
            </div>
        </div>
    );
}
