"use client";

import { useState } from "react";
import { Ban, DownloadCloud, KeyRound, Power, RefreshCw, Radio, Search, Trash2, UserPlus, Zap } from "lucide-react";
import { api, useApi, useDebounced } from "@/lib/client";
import { Badge, Button, Card, CardHeader, DataTable, Field, Input, Modal, PageHeader, Select, Tabs, useToast, type Column } from "@/components/ui";
import { formatDateTime, qs } from "@/lib/utils";

interface SessionRow extends Record<string, unknown> {
  id: number;
  username: string;
  routerName: string | null;
  ipAddress: string | null;
  macAddress: string | null;
  uptime: string | null;
  downloadRate: string | null;
  uploadRate: string | null;
  sessionTime: string | null;
  totalDownload: string | null;
  totalUpload: string | null;
  seenAt: string;
  customerName: string | null;
  customerId: number | null;
}
interface SecretRow extends Record<string, unknown> {
  id: number;
  username: string;
  routerId: number;
  routerName: string | null;
  profile: string | null;
  disabled: boolean;
  callerId: string | null;
  comment: string | null;
  lastSyncAt: string | null;
  customerName: string | null;
}

export default function MikrotikPage() {
  const toast = useToast();
  const [tab, setTab] = useState<"active" | "secrets">("active");
  const [filters, setFilters] = useState({ q: "", routerId: "" });
  const debounced = useDebounced(filters, 350);
  const { data: routers } = useApi<{ items: { id: number; name: string }[] }>("/api/routers");
  const { data, loading, reload } = useApi<{ items: SessionRow[] | SecretRow[]; total: number }>(`/api/pppoe${qs({ view: tab, ...debounced })}`, [tab, debounced.q, debounced.routerId]);
  const [modal, setModal] = useState(false);
  const [busy, setBusy] = useState(false);
  const [form, setForm] = useState({ routerId: "", username: "", password: "", profile: "", comment: "" });

  const act = async (username: string, payload: Record<string, unknown>, message: string) => {
    setBusy(true);
    try {
      await api(`/api/pppoe/${username}`, { method: "POST", json: payload });
      toast.push(message, "success");
      void reload();
    } catch (err) {
      toast.push(err instanceof Error ? err.message : "Operation failed", "error");
    } finally {
      setBusy(false);
    }
  };

  const sessionColumns: Column<SessionRow>[] = [
    { key: "username", label: "Username", render: (r) => <span className="font-mono text-xs text-slate-100">{r.username}</span> },
    { key: "customerName", label: "Customer", hideOnMobile: true, render: (r) => String(r.customerName ?? "—") },
    { key: "ipAddress", label: "IP", render: (r) => <span className="font-mono text-xs text-slate-300">{r.ipAddress ?? "—"}</span> },
    { key: "macAddress", label: "MAC", hideOnMobile: true, render: (r) => <span className="font-mono text-[11px] text-slate-500">{r.macAddress ?? "—"}</span> },
    { key: "uptime", label: "Uptime" },
    { key: "downloadRate", label: "Speed", hideOnMobile: true, render: (r) => <span className="font-mono text-[11px]">↓{r.downloadRate ?? "—"} ↑{r.uploadRate ?? "—"}</span> },
    { key: "sessionTime", label: "Session", hideOnMobile: true },
    { key: "routerName", label: "Router", hideOnMobile: true },
    { key: "actions", label: "", render: (r) => (
      <div className="flex gap-1">
        <Button size="sm" variant="ghost" icon={<Power className="h-3.5 w-3.5 text-amber-400" />} onClick={() => void act(r.username, { action: "disconnect" }, "Active session dropped")} />
        <Button size="sm" variant="ghost" icon={<Ban className="h-3.5 w-3.5 text-rose-400" />} onClick={() => void act(r.username, { action: "toggle", disabled: true }, "PPPoE user disabled")} />
      </div>
    ) },
  ];

  const secretColumns: Column<SecretRow>[] = [
    { key: "username", label: "Username", render: (r) => <span className="font-mono text-xs text-slate-100">{r.username}</span> },
    { key: "customerName", label: "Customer", hideOnMobile: true, render: (r) => String(r.customerName ?? "—") },
    { key: "profile", label: "Profile", render: (r) => <span className="font-mono text-xs text-slate-300">{r.profile ?? "default"}</span> },
    { key: "routerName", label: "Router", hideOnMobile: true },
    { key: "callerId", label: "Caller ID", hideOnMobile: true, render: (r) => <span className="font-mono text-[11px] text-slate-500">{r.callerId ?? "—"}</span> },
    { key: "disabled", label: "Status", render: (r) => <Badge value={r.disabled ? "disabled" : "active"} label={r.disabled ? "disabled" : "enabled"} /> },
    { key: "lastSyncAt", label: "Synced", hideOnMobile: true, render: (r) => formatDateTime(r.lastSyncAt) },
    { key: "actions", label: "", render: (r) => (
      <div className="flex flex-wrap gap-1">
        <Button size="sm" variant="ghost" icon={r.disabled ? <Zap className="h-3.5 w-3.5 text-emerald-400" /> : <Ban className="h-3.5 w-3.5 text-rose-400" />} onClick={() => void act(r.username, { action: "toggle", disabled: !r.disabled }, r.disabled ? "PPPoE enabled" : "PPPoE disabled")} />
        <Button size="sm" variant="ghost" icon={<KeyRound className="h-3.5 w-3.5" />} onClick={() => { const pw = prompt(`New password for ${r.username}`); if (pw) void act(r.username, { action: "password", password: pw }, "Password rotated"); }} />
        <Button size="sm" variant="ghost" onClick={() => { const profile = prompt("MikroTik profile name", r.profile ?? "default"); if (profile) void act(r.username, { action: "profile", profile }, "Profile updated"); }}>
          Profile
        </Button>
        <Button size="sm" variant="ghost" icon={<Trash2 className="h-3.5 w-3.5 text-rose-400" />} onClick={() => { if (confirm(`Delete secret ${r.username}?`)) void act(r.username, { action: "delete" }, "Secret removed"); }} />
      </div>
    ) },
  ];

  return (
    <>
      <PageHeader
        title="MikroTik / PPPoE control"
        subtitle="Live sessions, secret inventory and RouterOS synchronisation"
        icon={<Radio className="h-5 w-5" />}
        actions={
          <>
            <Select className="w-44" value={filters.routerId} onChange={(e) => setFilters((f) => ({ ...f, routerId: e.target.value }))}>
              <option value="">All routers</option>
              {(routers?.items ?? []).map((r) => (
                <option key={r.id} value={r.id}>
                  {r.name}
                </option>
              ))}
            </Select>
            <Button
              size="sm"
              variant="secondary"
              icon={<DownloadCloud className="h-4 w-4" />}
              loading={busy}
              onClick={async () => {
                if (!filters.routerId) return toast.push("Select a router to import", "warning");
                setBusy(true);
                try {
                  const res = await api<{ message: string }>("/api/pppoe", { method: "PATCH", json: { routerId: Number(filters.routerId) } });
                  toast.push(res.message, "success");
                  void reload();
                } catch (err) {
                  toast.push(err instanceof Error ? err.message : "Sync failed", "error");
                } finally {
                  setBusy(false);
                }
              }}
            >
              Import / Sync
            </Button>
            <Button size="sm" icon={<UserPlus className="h-4 w-4" />} onClick={() => setModal(true)}>
              Create secret
            </Button>
          </>
        }
      />

      <Card className="mb-4 p-3">
        <div className="flex flex-wrap items-center gap-3">
          <Tabs
            value={tab}
            onChange={setTab}
            tabs={[
              { value: "active", label: "Live sessions", icon: <Zap className="h-3.5 w-3.5" /> },
              { value: "secrets", label: "PPPoE users", icon: <Radio className="h-3.5 w-3.5" /> },
            ]}
          />
          <div className="relative min-w-56 flex-1">
            <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
            <Input className="pl-9" placeholder="Search username…" value={filters.q} onChange={(e) => setFilters((f) => ({ ...f, q: e.target.value }))} />
          </div>
          <Button variant="secondary" size="sm" icon={<RefreshCw className="h-4 w-4" />} onClick={() => void reload()}>
            Refresh
          </Button>
        </div>
      </Card>

      <Card className="p-2">
        <CardHeader title={tab === "active" ? `${data?.total ?? 0} live PPPoE session(s)` : `${data?.total ?? 0} PPPoE secret(s)`} subtitle="Passwords are stored encrypted and never exposed to the client" />
        {tab === "active" ? (
          <DataTable columns={sessionColumns} rows={(data?.items ?? []) as SessionRow[]} loading={loading} rowKey={(r) => r.id} empty="No live sessions" />
        ) : (
          <DataTable columns={secretColumns} rows={(data?.items ?? []) as SecretRow[]} loading={loading} rowKey={(r) => r.id} empty="No PPPoE secrets synced" />
        )}
      </Card>

      <Modal
        open={modal}
        onClose={() => setModal(false)}
        title="Create PPPoE secret"
        subtitle="Pushes the secret to the router and mirrors it in the database"
        footer={
          <>
            <Button variant="secondary" onClick={() => setModal(false)}>
              Cancel
            </Button>
            <Button
              loading={busy}
              onClick={async () => {
                setBusy(true);
                try {
                  await api("/api/pppoe", { method: "POST", json: { ...form, routerId: Number(form.routerId), profile: form.profile || null, comment: form.comment || null } });
                  toast.push("PPPoE secret created", "success");
                  setModal(false);
                  void reload();
                } catch (err) {
                  toast.push(err instanceof Error ? err.message : "Create failed", "error");
                } finally {
                  setBusy(false);
                }
              }}
            >
              Create secret
            </Button>
          </>
        }
      >
        <div className="grid gap-4 sm:grid-cols-2">
          <Field label="Router">
            <Select value={form.routerId} onChange={(e) => setForm({ ...form, routerId: e.target.value })}>
              <option value="">Select router</option>
              {(routers?.items ?? []).map((r) => (
                <option key={r.id} value={r.id}>
                  {r.name}
                </option>
              ))}
            </Select>
          </Field>
          <Field label="Profile">
            <Input value={form.profile} onChange={(e) => setForm({ ...form, profile: e.target.value })} placeholder="default" />
          </Field>
          <Field label="Username">
            <Input value={form.username} onChange={(e) => setForm({ ...form, username: e.target.value })} />
          </Field>
          <Field label="Password">
            <Input value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} />
          </Field>
          <Field label="Comment" className="sm:col-span-2">
            <Input value={form.comment} onChange={(e) => setForm({ ...form, comment: e.target.value })} />
          </Field>
        </div>
      </Modal>
    </>
  );
}
