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

type Metric = { key: string; name: string };
type Report = {
    id: number; name: string; format: string; frequency: string; metric_count: number;
    recipients: string[]; is_active: boolean; last_run_at: string | null; last_status: string | null;
};

export default function Reports() {
    const props = usePage().props as unknown as { reports: Report[]; metrics: Metric[] };
    const { reports, metrics } = props;
    const [form, setForm] = useState({ name: '', format: 'csv', frequency: 'manual', metric_keys: [] as string[], recipients: '' });

    const toggle = (k: string) =>
        setForm((f) => ({ ...f, metric_keys: f.metric_keys.includes(k) ? f.metric_keys.filter((x) => x !== k) : [...f.metric_keys, k] }));

    const create = () => {
        if (!form.name || form.metric_keys.length === 0) return;
        router.post('/reports', {
            ...form,
            recipients: form.recipients.split(',').map((s) => s.trim()).filter(Boolean),
        }, { preserveScroll: true, onSuccess: () => setForm({ name: '', format: 'csv', frequency: 'manual', metric_keys: [], recipients: '' }) });
    };

    return (
        <>
            <Head title="Reports" />
            <div className="mx-auto w-full max-w-4xl px-6 py-8">
                <h1 className="mb-6 flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                    <FileText className="size-5 text-primary" /> Reports
                </h1>

                <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 report</h2>
                    <div className="grid gap-3">
                        <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Report name"
                            className="rounded-md border border-border bg-background px-3 py-2 text-sm" />
                        <div className="flex gap-2">
                            <select value={form.format} onChange={(e) => setForm({ ...form, format: e.target.value })}
                                className="rounded-md border border-border bg-background px-3 py-2 text-sm">
                                <option value="csv">CSV</option><option value="html">HTML</option><option value="pdf">PDF (print-ready)</option>
                            </select>
                            <select value={form.frequency} onChange={(e) => setForm({ ...form, frequency: e.target.value })}
                                className="rounded-md border border-border bg-background px-3 py-2 text-sm">
                                <option value="manual">Manual</option><option value="daily">Daily</option>
                                <option value="weekly">Weekly</option><option value="monthly">Monthly</option>
                            </select>
                        </div>
                        <div>
                            <p className="mb-1.5 text-xs font-medium text-muted-foreground">Metrics to include</p>
                            <div className="flex flex-wrap gap-1.5">
                                {metrics.map((m) => (
                                    <button key={m.key} onClick={() => toggle(m.key)}
                                        className={`rounded-full border px-2.5 py-1 text-xs ${form.metric_keys.includes(m.key) ? 'border-primary bg-primary text-primary-foreground' : 'border-border hover:bg-muted'}`}>
                                        {m.name}
                                    </button>
                                ))}
                            </div>
                        </div>
                        <input value={form.recipients} onChange={(e) => setForm({ ...form, recipients: e.target.value })}
                            placeholder="Email recipients (comma-separated)"
                            className="rounded-md border border-border bg-background px-3 py-2 text-sm" />
                        <button onClick={create} className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90">
                            Create report
                        </button>
                    </div>
                </section>

                <div className="space-y-2">
                    {reports.map((r) => (
                        <div key={r.id} className="flex items-center justify-between rounded-lg border border-border bg-card p-4">
                            <div>
                                <p className="font-medium text-foreground">{r.name}</p>
                                <p className="mt-0.5 text-xs text-muted-foreground">
                                    {r.format.toUpperCase()} · {r.frequency} · {r.metric_count} metrics
                                    {r.last_run_at && ` · last run ${r.last_run_at} (${r.last_status})`}
                                </p>
                            </div>
                            <div className="flex gap-1">
                                <button title="Run now" onClick={() => router.post(`/reports/${r.id}/run`, {}, { preserveScroll: true })}
                                    className="rounded p-1.5 text-muted-foreground hover:bg-muted"><Play className="size-4" /></button>
                                {r.last_status === 'success' && (
                                    <a title="Download" href={`/reports/${r.id}/download`}
                                        className="rounded p-1.5 text-muted-foreground hover:bg-muted"><Download className="size-4" /></a>
                                )}
                                <button title="Delete" onClick={() => router.delete(`/reports/${r.id}`, { preserveScroll: true })}
                                    className="rounded p-1.5 text-muted-foreground hover:text-destructive"><Trash2 className="size-4" /></button>
                            </div>
                        </div>
                    ))}
                    {reports.length === 0 && (
                        <p className="rounded-xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">
                            No reports yet. Create one above to generate and schedule metric exports.
                        </p>
                    )}
                </div>
            </div>
        </>
    );
}
