"use client";

import { useState } from "react";
import useSWR from "swr";
import { Database, RefreshCw, Wrench } from "lucide-react";
import { toast } from "sonner";
import { apiSend, ApiError, fetcher } from "@/lib/api";
import { PageHeader, StatCard } from "@/components/page-header";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

interface Tabel {
  nama: string;
  baris: number;
  ukuran: number;
}

function formatBytes(bytes: number) {
  if (!bytes) return "0 B";
  const units = ["B", "KB", "MB", "GB"];
  const index = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
  return `${(bytes / 1024 ** index).toLocaleString("id-ID", { maximumFractionDigits: 1 })} ${units[index]}`;
}

export default function DatabasePage() {
  const { data, isLoading, mutate } = useSWR<Tabel[]>("/database/tabel", fetcher);
  const [selected, setSelected] = useState<string[]>([]);
  const [running, setRunning] = useState(false);

  const rows = data ?? [];
  const totalRows = rows.reduce((sum, table) => sum + table.baris, 0);
  const totalSize = rows.reduce((sum, table) => sum + table.ukuran, 0);

  function toggle(name: string) {
    setSelected((current) =>
      current.includes(name) ? current.filter((item) => item !== name) : [...current, name],
    );
  }

  async function optimize() {
    if (!selected.length) {
      toast.error("Pilih minimal satu tabel");
      return;
    }
    setRunning(true);
    try {
      const result = await apiSend<{ dioptimalkan: number }>("/database/optimasi", "POST", {
        tabel: selected,
      });
      toast.success(`${result.dioptimalkan} tabel dioptimalkan`);
      setSelected([]);
      await mutate();
    } catch (error) {
      toast.error(error instanceof ApiError ? error.message : "Gagal mengoptimalkan tabel");
    } finally {
      setRunning(false);
    }
  }

  return (
    <div className="space-y-5">
      <PageHeader
        title="Database"
        description="Daftar tabel, jumlah baris, dan ukuran penyimpanan basis data desa."
        action={
          <div className="flex flex-wrap gap-2">
            <Button asChild variant="outline">
              <a href="/api/backend/database/unduh" download>
                <Database className="h-4 w-4" />
                Unduh Database
              </a>
            </Button>
            <Button onClick={optimize} disabled={running || !selected.length}>
              {running ? <RefreshCw className="h-4 w-4 animate-spin" /> : <Wrench className="h-4 w-4" />}
              Optimasi ({selected.length})
            </Button>
          </div>
        }
      />

      <div className="grid gap-4 sm:grid-cols-3">
        <StatCard title="Jumlah Tabel" value={rows.length} icon={Database} />
        <StatCard title="Total Baris" value={totalRows.toLocaleString("id-ID")} icon={Database} tone="sky" />
        <StatCard title="Ukuran Data" value={formatBytes(totalSize)} icon={Database} tone="amber" />
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Tabel Basis Data</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto rounded-lg border border-border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-10" />
                  <TableHead>Tabel</TableHead>
                  <TableHead className="text-right">Baris</TableHead>
                  <TableHead className="text-right">Ukuran</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading && (
                  <TableRow>
                    <TableCell colSpan={4} className="py-6 text-center text-sm text-muted-foreground">
                      Memuat data…
                    </TableCell>
                  </TableRow>
                )}
                {rows.map((table) => (
                  <TableRow key={table.nama}>
                    <TableCell>
                      <input
                        type="checkbox"
                        checked={selected.includes(table.nama)}
                        onChange={() => toggle(table.nama)}
                        className="h-4 w-4 accent-[hsl(var(--primary))]"
                        aria-label={`Pilih ${table.nama}`}
                      />
                    </TableCell>
                    <TableCell className="font-mono text-xs">{table.nama}</TableCell>
                    <TableCell className="text-right">{table.baris.toLocaleString("id-ID")}</TableCell>
                    <TableCell className="text-right">{formatBytes(table.ukuran)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
