"use client";

import { useState } from "react";
import { DatabaseBackup, Download, Plus, RefreshCw, Trash2 } from "lucide-react";
import { api, useApi } from "@/lib/client";
import { Badge, Button, Card, DataTable, PageHeader, useToast, type Column } from "@/components/ui";
import { formatDateTime } from "@/lib/utils";

interface BackupRow extends Record<string, unknown> {
  id: number;
  filename: string;
  sizeBytes: number;
  type: string;
  status: string;
  createdAt: string;
  creator: string | null;
}

export default function BackupsPage() {
  const toast = useToast();
  const { data, loading, reload } = useApi<{ items: BackupRow[] }>("/api/backups");
  const [busy, setBusy] = useState(false);

  const columns: Column<BackupRow>[] = [
    { key: "filename", label: "File", render: (r) => <span className="font-mono text-xs text-slate-200">{r.filename}</span> },
    { key: "type", label: "Type", render: (r) => <Badge value={r.type === "cron" ? "active" : "unknown"} label={r.type} /> },
    { key: "sizeBytes", label: "Size", render: (r) => `${(r.sizeBytes / 1024).toFixed(1)} KB` },
    { key: "creator", label: "Created by", render: (r) => String(r.creator ?? "system") },
    { key: "createdAt", label: "Created", render: (r) => formatDateTime(r.createdAt) },
    { key: "status", label: "Status", render: (r) => <Badge value={r.status === "completed" ? "active" : "expired"} label={r.status} /> },
    {
      key: "actions",
      label: "",
      render: (r) => (
        <div className="flex gap-1">
          <a href={`/api/backups/${r.id}/download`} download>
            <Button size="sm" variant="ghost" icon={<Download className="h-3.5 w-3.5" />}>
              Download
            </Button>
          </a>
          <Button
            size="sm"
            variant="ghost"
            icon={<Trash2 className="h-3.5 w-3.5 text-rose-400" />}
            onClick={async () => {
              if (!confirm(`Delete ${r.filename}?`)) return;
              try {
                await api(`/api/backups/${r.id}`, { method: "DELETE" });
                toast.push("Backup deleted", "success");
                void reload();
              } catch (err) {
                toast.push(err instanceof Error ? err.message : "Delete failed", "error");
              }
            }}
          />
        </div>
      ),
    },
  ];

  return (
    <>
      <PageHeader
        title="Database backups"
        subtitle="Manual and scheduled JSON snapshots with secrets redacted"
        icon={<DatabaseBackup className="h-5 w-5" />}
        actions={
          <>
            <Button variant="secondary" size="sm" icon={<RefreshCw className="h-4 w-4" />} onClick={() => void reload()}>
              Refresh
            </Button>
            <Button
              size="sm"
              loading={busy}
              icon={<Plus className="h-4 w-4" />}
              onClick={async () => {
                setBusy(true);
                try {
                  const res = await api<{ filename: string }>("/api/backups", { method: "POST" });
                  toast.push(`Backup created: ${res.filename}`, "success");
                  void reload();
                } catch (err) {
                  toast.push(err instanceof Error ? err.message : "Backup failed", "error");
                } finally {
                  setBusy(false);
                }
              }}
            >
              Backup now
            </Button>
          </>
        }
      />

      <Card className="mb-4 p-4 text-xs text-slate-400">
        <p className="font-semibold text-slate-200">Cron automation</p>
        <p className="mt-1">
          Schedule <code className="rounded bg-white/8 px-1">GET /api/cron/backup</code> nightly with your <code className="rounded bg-white/8 px-1">CRON_SECRET</code> bearer token to
          create automatic backups. Snapshots exclude password hashes, router API credentials and gateway secrets.
        </p>
      </Card>

      <Card className="p-2">
        <DataTable columns={columns} rows={data?.items ?? []} loading={loading} rowKey={(r) => r.id} empty="No backups yet" />
      </Card>
    </>
  );
}
