"use client";
import { useState, useEffect } from "react";
import { Zap, Check, X, Loader2, Plus, Trash2, Globe, BellRing } from "lucide-react";
import { useUI } from "@/context/UIContext";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
const EVENTS = ["job_complete", "job_failed", "disk_warning", "job_started", "extract_complete"];

export default function WebhooksPage() {
    const { toast, alert } = useUI();
    const [webhooks, setWebhooks] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [showForm, setShowForm] = useState(false);
    const [form, setForm] = useState({ name: "", url: "", secret: "", events: ["job_complete", "job_failed"] });

    const authHeaders = () => ({ "Content-Type": "application/json", Authorization: `Bearer ${localStorage.getItem("mhb_token") || ""}` });

    async function load() {
        setLoading(true);
        const res = await fetch(`${API}/api/advanced/webhooks`, { headers: authHeaders() });
        const data = await res.json();
        setWebhooks(data.webhooks || []);
        setLoading(false);
    }

    useEffect(() => { load(); }, []);

    async function handleAdd() {
        if (!form.url) return;
        const res = await fetch(`${API}/api/advanced/webhooks`, {
            method: "POST", headers: authHeaders(),
            body: JSON.stringify(form),
        });
        const data = await res.json();
        if (data.success) { toast("Webhook added!", "success"); load(); setShowForm(false); setForm({ name: "", url: "", secret: "", events: ["job_complete", "job_failed"] }); }
    }

    async function handleDelete(id: string) {
        await fetch(`${API}/api/advanced/webhooks/${id}`, { method: "DELETE", headers: authHeaders() });
        setWebhooks(prev => prev.filter(w => w.id !== id));
        toast("Webhook removed", "info");
    }

    function toggleEvent(ev: string) {
        setForm(prev => ({ ...prev, events: prev.events.includes(ev) ? prev.events.filter(e => e !== ev) : [...prev.events, ev] }));
    }

    return (
        <div className="space-y-6 max-w-2xl mx-auto pb-20">
            <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-orange-500/10 flex items-center justify-center"><Zap className="w-6 h-6 text-orange-400" /></div>
                    <div>
                        <h1 className="text-2xl font-extrabold text-white">Webhooks</h1>
                        <p className="text-white/40 text-sm">Send HTTP POST events to external services on job events.</p>
                    </div>
                </div>
                <button onClick={() => setShowForm(s => !s)} className="btn-primary px-4 py-2 text-sm flex items-center gap-2">
                    <Plus className="w-4 h-4" /> Add Webhook
                </button>
            </div>

            {showForm && (
                <div className="card p-6 bg-black/40 border-white/10 space-y-4">
                    <h3 className="font-black text-white text-sm">New Webhook</h3>
                    <div className="space-y-3">
                        <input value={form.name} onChange={e => setForm(p => ({ ...p, name: e.target.value }))} placeholder="Name (e.g. Slack, n8n)" className="input w-full" />
                        <input value={form.url} onChange={e => setForm(p => ({ ...p, url: e.target.value }))} placeholder="https://hooks.example.com/..." className="input w-full font-mono text-xs" />
                        <input value={form.secret} onChange={e => setForm(p => ({ ...p, secret: e.target.value }))} placeholder="Secret (optional, sent as X-MHBD-Secret header)" className="input w-full" type="password" />
                        <div>
                            <p className="text-[10px] font-black uppercase tracking-widest text-white/30 mb-2">Trigger on</p>
                            <div className="flex flex-wrap gap-2">
                                {EVENTS.map(ev => (
                                    <button key={ev} onClick={() => toggleEvent(ev)} className={`px-3 py-1.5 rounded-lg text-[10px] font-black transition-all border ${form.events.includes(ev) ? "bg-orange-500/15 border-orange-500/30 text-orange-400" : "bg-white/5 border-white/10 text-white/30"}`}>
                                        {ev.replace(/_/g, " ")}
                                    </button>
                                ))}
                            </div>
                        </div>
                        <div className="flex gap-2">
                            <button onClick={() => setShowForm(false)} className="flex-1 btn-ghost py-2.5 text-sm">Cancel</button>
                            <button onClick={handleAdd} disabled={!form.url} className="flex-1 btn-primary py-2.5 text-sm"><Check className="w-4 h-4" /> Save</button>
                        </div>
                    </div>
                </div>
            )}

            {loading ? <div className="flex justify-center py-12"><Loader2 className="w-6 h-6 animate-spin text-accent-cyan" /></div> : (
                <div className="space-y-3">
                    {webhooks.length === 0 && <div className="text-center py-16 text-white/20"><Globe className="w-10 h-10 mx-auto mb-3" /><p>No webhooks yet</p></div>}
                    {webhooks.map(w => (
                        <div key={w.id} className="card p-4 bg-black/40 border-white/10 flex items-center gap-4 group">
                            <div className="w-9 h-9 rounded-xl bg-orange-500/10 flex items-center justify-center shrink-0"><BellRing className="w-4 h-4 text-orange-400" /></div>
                            <div className="flex-1 min-w-0">
                                <p className="font-black text-white text-sm">{w.name || "Webhook"}</p>
                                <p className="text-[10px] font-mono text-white/30 truncate">{w.url}</p>
                                <div className="flex gap-1 mt-1 flex-wrap">
                                    {(w.events || []).map((e: string) => <span key={e} className="text-[8px] px-1.5 py-0.5 rounded bg-white/5 text-white/30">{e}</span>)}
                                </div>
                            </div>
                            <button onClick={() => handleDelete(w.id)} className="p-2 rounded-xl text-red-400/40 hover:text-red-400 hover:bg-red-500/10 opacity-0 group-hover:opacity-100 transition-all shrink-0"><Trash2 className="w-4 h-4" /></button>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
