/**
 * AdminTutorialsManager — Super Admin page to attach video tutorials to
 * every RBS module. The Floating AI bubble then shows a "▶ Watch 2-min
 * tutorial" button for users who have `video_tutorials` enabled.
 *
 * Layout:
 *   - Left: list of all 21 modules from `moduleGuide.js`. Each row shows
 *     module title + a "saved/no video" badge + the current YouTube URL.
 *   - Right: editor for the currently-selected module — paste video URL,
 *     custom title, description, language, active toggle. Save / Delete.
 *
 * Per-user gate is configured in Admin → User Feature Controls (the existing
 * page) by toggling the new "Video Tutorials (AI Guide)" feature key.
 */
import React, { useEffect, useMemo, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import {
    Video, Youtube, Save, Trash2, CheckCircle2, AlertCircle, Search, ExternalLink, Play, BookOpen, Upload, Download,
} from "lucide-react";
import { toast } from "sonner";
import { api } from "@/lib/api";
import { MODULE_GUIDES } from "@/lib/moduleGuide";

const BASE = process.env.REACT_APP_BACKEND_URL;

export default function AdminTutorialsManager() {
    const [tutorials, setTutorials] = useState([]);
    const [selectedPath, setSelectedPath] = useState(MODULE_GUIDES[0]?.path || "/dashboard");
    const [search, setSearch] = useState("");
    const [form, setForm] = useState({
        module_path: "", title: "", video_url: "", description: "",
        duration_seconds: 120, language: "hi", is_active: true,
    });

    const load = async () => {
        try {
            const { data } = await api.get("/module-tutorials");
            setTutorials(data || []);
        } catch (e) { toast.error("Load failed"); }
    };
    useEffect(() => { load(); }, []);

    // Build a lookup of path → tutorial for the side panel
    const tutorialByPath = useMemo(() => {
        const m = {};
        for (const t of tutorials) m[t.module_path] = t;
        return m;
    }, [tutorials]);

    // Selected module guide details
    const selectedModule = useMemo(
        () => MODULE_GUIDES.find((g) => g.path === selectedPath) || MODULE_GUIDES[0],
        [selectedPath]
    );

    // When user picks a module, pre-fill form from existing tutorial (if any)
    useEffect(() => {
        const existing = tutorialByPath[selectedPath];
        if (existing) {
            setForm({
                module_path: existing.module_path,
                title: existing.title || "",
                video_url: existing.video_url || "",
                description: existing.description || "",
                duration_seconds: existing.duration_seconds || 120,
                language: existing.language || "hi",
                is_active: existing.is_active !== false,
            });
        } else {
            setForm({
                module_path: selectedPath,
                title: selectedModule?.title || "",
                video_url: "",
                description: selectedModule?.description || "",
                duration_seconds: 120,
                language: "hi",
                is_active: true,
            });
        }
    }, [selectedPath, tutorialByPath, selectedModule]);

    const setField = (k, v) => setForm((f) => ({ ...f, [k]: v }));

    const save = async () => {
        if (!form.video_url.trim()) { toast.error("Video URL is required"); return; }
        try {
            // URL-encode the path segment so leading / passes through
            const encoded = encodeURIComponent(form.module_path).replace(/%2F/g, "/");
            await api.put(`/module-tutorials${encoded}`, form);
            toast.success("Tutorial saved");
            load();
        } catch (e) { toast.error(e.response?.data?.detail || "Save failed"); }
    };

    const remove = async () => {
        if (!tutorialByPath[selectedPath]) { toast.info("Nothing to delete"); return; }
        if (!window.confirm(`Delete tutorial for ${selectedPath}?`)) return;
        try {
            const encoded = encodeURIComponent(selectedPath).replace(/%2F/g, "/");
            await api.delete(`/module-tutorials${encoded}`);
            toast.success("Deleted");
            load();
        } catch (e) { toast.error("Delete failed"); }
    };

    const filteredModules = useMemo(() => {
        if (!search.trim()) return MODULE_GUIDES;
        const q = search.toLowerCase();
        return MODULE_GUIDES.filter((g) => g.title.toLowerCase().includes(q) || g.path.includes(q));
    }, [search]);

    // ----- Bulk CSV import / template ---------------------------------------
    const downloadTemplate = () => {
        // Build a CSV pre-filled with every known module path + the recommended columns
        const headers = "module_path,title,video_url,description,duration_seconds,language,is_active";
        const rows = MODULE_GUIDES.map((g) => `${g.path},"${g.title.replace(/"/g, "''")}",https://youtu.be/REPLACE_ID,"${(g.description || "").replace(/"/g, "''")}",120,hi,true`);
        const blob = new Blob([headers + "\n" + rows.join("\n")], { type: "text/csv;charset=utf-8" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a"); a.href = url; a.download = "rbs-tutorials-template.csv"; a.click();
        URL.revokeObjectURL(url);
        toast.success("Template downloaded — fill in YouTube URLs and upload");
    };

    const onBulkUpload = async (ev) => {
        const file = ev.target.files?.[0];
        if (!file) return;
        ev.target.value = "";          // allow re-upload of same file
        const form = new FormData();
        form.append("file", file);
        try {
            const resp = await fetch(`${BASE}/api/module-tutorials/bulk-import`, { method: "POST", body: form, credentials: "include" });
            const data = await resp.json();
            if (!resp.ok) throw new Error(data?.detail || resp.statusText);
            toast.success(`${data.inserted} inserted · ${data.updated} updated · ${data.skipped} skipped · ${data.errors?.length || 0} errors`);
            load();
        } catch (e) { toast.error("Upload failed: " + (e.message?.slice(0, 100) || "")); }
    };

    return (
        <div className="space-y-5" data-testid="admin-tutorials-page">
            <header className="flex flex-wrap items-end justify-between gap-3">
                <div>
                    <div className="text-[10px] uppercase tracking-[0.2em] text-rose-500 font-semibold">AI Onboarding</div>
                    <h1 className="font-display text-3xl font-bold flex items-center gap-2">
                        <Video className="h-7 w-7 text-rose-500" /> Module Video Tutorials
                    </h1>
                    <p className="text-sm text-muted-foreground mt-1">
                        Apne YouTube / Vimeo tutorials yahan paste karein. Floating AI bubble har screen par <em>&ldquo;▶ Watch 2-min tutorial&rdquo;</em> button dikhayega — per-user ON/OFF Admin → User Feature Controls se control hota hai.
                    </p>
                </div>
                <a href="/admin/user-features" className="text-xs underline text-blue-600 hover:text-blue-800" data-testid="link-user-features">
                    Per-user ON/OFF →
                </a>
            </header>

            {/* Bulk CSV row */}
            <Card>
                <CardContent className="p-4 flex flex-wrap items-center gap-3">
                    <div className="flex-1 min-w-[200px]">
                        <div className="font-display font-bold text-sm flex items-center gap-1.5"><Upload className="h-4 w-4 text-emerald-600" />Bulk Import from CSV</div>
                        <p className="text-[11px] text-muted-foreground">Saare 21 modules ek hi CSV se upload karein — har module ke liye click karne ki zarurat nahi</p>
                    </div>
                    <Button size="sm" variant="outline" onClick={downloadTemplate} data-testid="tut-bulk-template">
                        <Download className="h-3.5 w-3.5 mr-1.5" />Download Template CSV
                    </Button>
                    <label className="cursor-pointer">
                        <input type="file" accept=".csv" onChange={onBulkUpload} className="hidden" data-testid="tut-bulk-input" />
                        <Button asChild size="sm" className="bg-emerald-600 hover:bg-emerald-700 text-white">
                            <span><Upload className="h-3.5 w-3.5 mr-1.5" />Upload CSV</span>
                        </Button>
                    </label>
                </CardContent>
            </Card>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {/* Module list */}
                <Card className="md:col-span-1">
                    <CardHeader>
                        <CardTitle className="text-base flex items-center gap-2"><BookOpen className="h-4 w-4" />Modules ({MODULE_GUIDES.length})</CardTitle>
                        <div className="relative mt-1">
                            <Search className="absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
                            <Input placeholder="Filter…" value={search} onChange={(e) => setSearch(e.target.value)} className="h-8 pl-7 text-xs" data-testid="tutorials-search" />
                        </div>
                    </CardHeader>
                    <CardContent className="p-2 max-h-[600px] overflow-y-auto">
                        <ul className="space-y-1">
                            {filteredModules.map((g) => {
                                const t = tutorialByPath[g.path];
                                const isActive = selectedPath === g.path;
                                return (
                                    <li key={g.path}>
                                        <button
                                            onClick={() => setSelectedPath(g.path)}
                                            className={`w-full text-left p-2 rounded-md border transition ${
                                                isActive ? "bg-amber-500/10 border-amber-500/40" : "hover:bg-muted border-border"
                                            }`}
                                            data-testid={`tutorial-row-${g.path.replace(/\//g, "-")}`}
                                        >
                                            <div className="flex items-center gap-2">
                                                <span className="text-base">{g.emoji}</span>
                                                <span className="font-medium text-sm flex-1 truncate">{g.title}</span>
                                                {t?.video_url ? (
                                                    <Badge variant="outline" className="text-[9px] border-emerald-500/30 text-emerald-600"><CheckCircle2 className="h-2.5 w-2.5 mr-0.5" />Set</Badge>
                                                ) : (
                                                    <Badge variant="outline" className="text-[9px] text-muted-foreground"><AlertCircle className="h-2.5 w-2.5 mr-0.5" />No video</Badge>
                                                )}
                                            </div>
                                            <div className="text-[10px] text-muted-foreground font-mono mt-0.5 truncate">{g.path}</div>
                                        </button>
                                    </li>
                                );
                            })}
                        </ul>
                    </CardContent>
                </Card>

                {/* Editor */}
                <Card className="md:col-span-2">
                    <CardHeader>
                        <CardTitle className="text-base flex items-center gap-2">
                            <span className="text-2xl">{selectedModule?.emoji}</span>
                            {selectedModule?.title}
                            <code className="ml-auto text-[10px] text-muted-foreground font-mono">{selectedPath}</code>
                        </CardTitle>
                        <p className="text-xs text-muted-foreground">{selectedModule?.description}</p>
                    </CardHeader>
                    <CardContent className="space-y-3">
                        <div>
                            <Label htmlFor="tut-url" className="text-xs">Video URL * <span className="text-[10px] text-muted-foreground">(YouTube, Vimeo, ya direct MP4)</span></Label>
                            <Input
                                id="tut-url"
                                value={form.video_url}
                                onChange={(e) => setField("video_url", e.target.value)}
                                placeholder="https://youtube.com/watch?v=… or https://youtu.be/…"
                                className="mt-1 font-mono text-sm"
                                data-testid="tut-video-url"
                            />
                        </div>

                        <div className="grid grid-cols-2 gap-2">
                            <div>
                                <Label htmlFor="tut-title" className="text-xs">Custom Title (optional)</Label>
                                <Input id="tut-title" value={form.title} onChange={(e) => setField("title", e.target.value)} placeholder={selectedModule?.title} className="mt-1" data-testid="tut-title" />
                            </div>
                            <div>
                                <Label htmlFor="tut-duration" className="text-xs">Duration (seconds)</Label>
                                <Input id="tut-duration" type="number" value={form.duration_seconds} onChange={(e) => setField("duration_seconds", Number(e.target.value))} className="mt-1" data-testid="tut-duration" />
                            </div>
                        </div>

                        <div>
                            <Label htmlFor="tut-desc" className="text-xs">Description / Talking points</Label>
                            <Textarea id="tut-desc" rows={3} value={form.description} onChange={(e) => setField("description", e.target.value)} placeholder="Is video mein kya seekhenge…" className="mt-1" data-testid="tut-desc" />
                        </div>

                        <div className="flex items-center gap-4">
                            <div className="flex-1">
                                <Label className="text-xs">Language</Label>
                                <select value={form.language} onChange={(e) => setField("language", e.target.value)} className="w-full mt-1 h-9 rounded border bg-background px-3 text-sm" data-testid="tut-language">
                                    <option value="hi">Hindi</option>
                                    <option value="en">English</option>
                                    <option value="hi-en">Hinglish</option>
                                </select>
                            </div>
                            <div className="pt-5">
                                <label className="flex items-center gap-2 text-sm">
                                    <Switch checked={form.is_active} onCheckedChange={(v) => setField("is_active", v)} data-testid="tut-active" />
                                    <span>Active (visible to users)</span>
                                </label>
                            </div>
                        </div>

                        {form.video_url && (
                            <div className="rounded-lg border border-amber-500/30 bg-amber-500/5 p-3" data-testid="tut-preview">
                                <Label className="text-xs font-semibold text-amber-700 dark:text-amber-400 mb-2 block">📺 Preview</Label>
                                <a href={form.video_url} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 text-sm text-blue-600 hover:underline">
                                    <Play className="h-4 w-4" /> Open video in new tab <ExternalLink className="h-3 w-3" />
                                </a>
                            </div>
                        )}

                        <div className="flex flex-wrap gap-2 pt-2 border-t">
                            <Button onClick={save} className="bg-emerald-600 hover:bg-emerald-700 text-white" data-testid="tut-save">
                                <Save className="h-4 w-4 mr-1.5" /> Save Tutorial
                            </Button>
                            {tutorialByPath[selectedPath] && (
                                <Button variant="outline" onClick={remove} className="border-rose-500/30 text-rose-600" data-testid="tut-delete">
                                    <Trash2 className="h-4 w-4 mr-1.5" /> Delete
                                </Button>
                            )}
                        </div>
                    </CardContent>
                </Card>
            </div>
        </div>
    );
}
