import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { Bell, Plus, Trash2, Play, Power } from 'lucide-react';

type Metric = { key: string; name: string; unit: string };
type Rule = {
    id: number; name: string; metric_key: string; operator: string; threshold: number;
    window: string; notify_email: boolean; is_active: boolean; last_triggered_at: string | null;
};

const OP_LABEL: Record<string, string> = {
    gt: 'is above', gte: 'is at or above', lt: 'is below', lte: 'is at or below',
    eq: 'equals', pct_change_gt: 'increases more than %', pct_change_lt: 'decreases more than %',
};

export default function Alerts() {
    const props = usePage().props as unknown as { rules: Rule[]; metrics: Metric[]; operators: string[] };
    const { rules, metrics, operators } = props;
    const [form, setForm] = useState({ name: '', metric_key: '', operator: 'gt', threshold: '', notify_email: false });

    const create = () => {
        if (!form.name || !form.metric_key || form.threshold === '') return;
        router.post('/alerts', { ...form, threshold: parseFloat(form.threshold) }, {
            preserveScroll: true,
            onSuccess: () => setForm({ name: '', metric_key: '', operator: 'gt', threshold: '', notify_email: false }),
        });
    };

    return (
        <>
            <Head title="Alerts" />
            <div className="mx-auto w-full max-w-4xl px-6 py-8">
                <header className="mb-6 flex items-center justify-between">
                    <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                        <Bell className="size-5 text-primary" /> Alerts
                    </h1>
                    <button onClick={() => router.post('/alerts/test-run', {}, { preserveScroll: true })}
                        className="inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-sm font-medium hover:bg-muted">
                        <Play className="size-3.5" /> Run now
                    </button>
                </header>

                <section className="mb-8 rounded-xl border border-border bg-card p-5">
                    <h2 className="mb-3 flex items-center gap-2 font-medium text-foreground"><Plus className="size-4 text-primary" /> New alert</h2>
                    <div className="grid gap-3 sm:grid-cols-2">
                        <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Alert name"
                            className="rounded-md border border-border bg-background px-3 py-2 text-sm sm:col-span-2" />
                        <select value={form.metric_key} onChange={(e) => setForm({ ...form, metric_key: e.target.value })}
                            className="rounded-md border border-border bg-background px-3 py-2 text-sm">
                            <option value="">Select metric…</option>
                            {metrics.map((m) => <option key={m.key} value={m.key}>{m.name}</option>)}
                        </select>
                        <div className="flex gap-2">
                            <select value={form.operator} onChange={(e) => setForm({ ...form, operator: e.target.value })}
                                className="flex-1 rounded-md border border-border bg-background px-2 py-2 text-sm">
                                {operators.map((o) => <option key={o} value={o}>{OP_LABEL[o] ?? o}</option>)}
                            </select>
                            <input value={form.threshold} onChange={(e) => setForm({ ...form, threshold: e.target.value })} type="number" placeholder="value"
                                className="w-24 rounded-md border border-border bg-background px-3 py-2 text-sm" />
                        </div>
                        <label className="flex items-center gap-2 text-sm text-muted-foreground">
                            <input type="checkbox" checked={form.notify_email} onChange={(e) => setForm({ ...form, notify_email: e.target.checked })} />
                            Also email me
                        </label>
                        <button onClick={create}
                            className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90">
                            Create alert
                        </button>
                    </div>
                </section>

                <div className="space-y-2">
                    {rules.map((r) => (
                        <div key={r.id} className="flex items-center justify-between rounded-lg border border-border bg-card p-4">
                            <div>
                                <div className="flex items-center gap-2">
                                    <span className="font-medium text-foreground">{r.name}</span>
                                    {!r.is_active && <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">paused</span>}
                                    {r.last_triggered_at && <span className="rounded bg-amber-100 px-1.5 py-0.5 text-[10px] text-amber-700 dark:bg-amber-500/15 dark:text-amber-300">triggered {r.last_triggered_at}</span>}
                                </div>
                                <p className="mt-0.5 text-xs text-muted-foreground">
                                    {r.metric_key} {OP_LABEL[r.operator] ?? r.operator} {r.threshold}
                                    {r.notify_email && ' · emails you'}
                                </p>
                            </div>
                            <div className="flex gap-1">
                                <button title="Toggle" onClick={() => router.post(`/alerts/${r.id}/toggle`, {}, { preserveScroll: true })}
                                    className="rounded p-1.5 text-muted-foreground hover:bg-muted"><Power className="size-4" /></button>
                                <button title="Delete" onClick={() => router.delete(`/alerts/${r.id}`, { preserveScroll: true })}
                                    className="rounded p-1.5 text-muted-foreground hover:text-destructive"><Trash2 className="size-4" /></button>
                            </div>
                        </div>
                    ))}
                    {rules.length === 0 && (
                        <p className="rounded-xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
                            No alerts yet. Create one above to get notified when a metric crosses a threshold.
                        </p>
                    )}
                </div>
            </div>
        </>
    );
}
