"use client";

import { useState } from "react";
import { Package as PackageIcon, Pencil, Plus, Trash2 } from "lucide-react";
import { api, useApi } from "@/lib/client";
import { Badge, Button, Card, DataTable, Field, Input, Modal, PageHeader, Select, Textarea, useToast, type Column } from "@/components/ui";
import { money } from "@/lib/utils";

interface Pkg extends Record<string, unknown> {
  id: number;
  name: string;
  speed: string;
  downloadSpeed: string;
  uploadSpeed: string;
  price: string;
  billingCycle: string;
  routerProfile: string | null;
  graceDays: number;
  description: string | null;
  isActive: boolean;
  customerCount: number;
}

const empty = { name: "", speed: "", downloadSpeed: "", uploadSpeed: "", price: "0", billingCycle: "monthly", routerProfile: "", graceDays: "5", description: "", isActive: true };

export default function PackagesPage() {
  const toast = useToast();
  const { data, loading, reload } = useApi<{ items: Pkg[] }>("/api/packages?all=true");
  const [modal, setModal] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [form, setForm] = useState(empty);
  const [busy, setBusy] = useState(false);

  const openCreate = () => {
    setEditId(null);
    setForm(empty);
    setModal(true);
  };
  const openEdit = (pkg: Pkg) => {
    setEditId(pkg.id);
    setForm({
      name: pkg.name,
      speed: pkg.speed,
      downloadSpeed: pkg.downloadSpeed,
      uploadSpeed: pkg.uploadSpeed,
      price: pkg.price,
      billingCycle: pkg.billingCycle,
      routerProfile: pkg.routerProfile ?? "",
      graceDays: String(pkg.graceDays),
      description: pkg.description ?? "",
      isActive: pkg.isActive,
    });
    setModal(true);
  };

  const save = async () => {
    setBusy(true);
    try {
      const payload = { ...form, price: Number(form.price), graceDays: Number(form.graceDays), routerProfile: form.routerProfile || null };
      if (editId) await api(`/api/packages/${editId}`, { method: "PUT", json: payload });
      else await api("/api/packages", { method: "POST", json: payload });
      toast.push(editId ? "Package updated" : "Package created", "success");
      setModal(false);
      void reload();
    } catch (err) {
      toast.push(err instanceof Error ? err.message : "Save failed", "error");
    } finally {
      setBusy(false);
    }
  };

  const columns: Column<Pkg>[] = [
    { key: "name", label: "Package", render: (r) => <span className="font-medium text-slate-100">{r.name}</span> },
    { key: "speed", label: "Speed", render: (r) => <span className="font-mono text-xs text-slate-300">↓{r.downloadSpeed} / ↑{r.uploadSpeed}</span> },
    { key: "price", label: "Price", render: (r) => money(r.price) },
    { key: "billingCycle", label: "Cycle", hideOnMobile: true, render: (r) => <Badge value="unknown" label={r.billingCycle} /> },
    { key: "routerProfile", label: "MikroTik profile", hideOnMobile: true, render: (r) => <span className="font-mono text-xs text-slate-400">{r.routerProfile ?? "—"}</span> },
    { key: "graceDays", label: "Grace", hideOnMobile: true },
    { key: "customerCount", label: "Customers", render: (r) => <span className="font-semibold text-brand-400">{r.customerCount}</span> },
    { key: "isActive", label: "Status", render: (r) => <Badge value={r.isActive ? "active" : "inactive"} /> },
    {
      key: "actions",
      label: "",
      render: (r) => (
        <div className="flex gap-1">
          <Button size="sm" variant="ghost" icon={<Pencil className="h-3.5 w-3.5" />} onClick={() => openEdit(r)}>
            Edit
          </Button>
          <Button
            size="sm"
            variant="ghost"
            icon={<Trash2 className="h-3.5 w-3.5 text-rose-400" />}
            onClick={async () => {
              if (!confirm(`Delete ${r.name}?`)) return;
              try {
                await api(`/api/packages/${r.id}`, { method: "DELETE" });
                toast.push("Package deleted", "success");
                void reload();
              } catch (err) {
                toast.push(err instanceof Error ? err.message : "Delete failed", "error");
              }
            }}
          />
        </div>
      ),
    },
  ];

  return (
    <>
      <PageHeader
        title="Package management"
        subtitle="Speed profiles, pricing and MikroTik profile mapping"
        icon={<PackageIcon className="h-5 w-5" />}
        actions={
          <Button size="sm" icon={<Plus className="h-4 w-4" />} onClick={openCreate}>
            New package
          </Button>
        }
      />
      <Card className="p-2">
        <DataTable columns={columns} rows={data?.items ?? []} loading={loading} rowKey={(r) => r.id} />
      </Card>

      <Modal
        open={modal}
        onClose={() => setModal(false)}
        title={editId ? "Edit package" : "New package"}
        subtitle="Price is used for monthly bill generation"
        footer={
          <>
            <Button variant="secondary" onClick={() => setModal(false)}>
              Cancel
            </Button>
            <Button loading={busy} onClick={() => void save()}>
              Save package
            </Button>
          </>
        }
      >
        <div className="grid gap-4 sm:grid-cols-2">
          <Field label="Package name">
            <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
          </Field>
          <Field label="Advertised speed">
            <Input value={form.speed} onChange={(e) => setForm({ ...form, speed: e.target.value })} placeholder="10 Mbps" />
          </Field>
          <Field label="Download speed">
            <Input value={form.downloadSpeed} onChange={(e) => setForm({ ...form, downloadSpeed: e.target.value })} />
          </Field>
          <Field label="Upload speed">
            <Input value={form.uploadSpeed} onChange={(e) => setForm({ ...form, uploadSpeed: e.target.value })} />
          </Field>
          <Field label="Price">
            <Input type="number" value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} />
          </Field>
          <Field label="Billing cycle">
            <Select value={form.billingCycle} onChange={(e) => setForm({ ...form, billingCycle: e.target.value })}>
              {["monthly", "quarterly", "half_yearly", "yearly"].map((c) => (
                <option key={c} value={c}>
                  {c}
                </option>
              ))}
            </Select>
          </Field>
          <Field label="MikroTik router profile">
            <Input value={form.routerProfile} onChange={(e) => setForm({ ...form, routerProfile: e.target.value })} placeholder="10mbps" />
          </Field>
          <Field label="Grace days">
            <Input type="number" value={form.graceDays} onChange={(e) => setForm({ ...form, graceDays: e.target.value })} />
          </Field>
          <Field label="Description" className="sm:col-span-2">
            <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
          </Field>
          <label className="flex items-center gap-2 text-xs text-slate-300">
            <input type="checkbox" className="h-4 w-4 accent-brand-500" checked={form.isActive} onChange={(e) => setForm({ ...form, isActive: e.target.checked })} />
            Active (available for assignment)
          </label>
        </div>
      </Modal>
    </>
  );
}
