import { useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router';
import { useTranslation } from 'react-i18next';
import { ArrowLeft, Pencil, Trash2, Plus } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import {
useIPAMNetwork, useIPAMNetworkStats, useIPAMAllocations, useIPAMPools,
useUpdateNetwork, useDeleteNetwork, useCreatePool, useUpdatePool, useDeletePool, useIPAMIPMap,
} from '@/hooks/use-ipam';
import type { IPAMNetwork, IPAMPool } from '@/types';
import { WorkspaceSelect } from './WorkspaceSelect';
import { toast } from 'sonner';
import { useConfirm } from '@/components/shared/ConfirmDialog';
export default function IPAMNetworkDetailPage() {
const { t } = useTranslation();
const { id } = useParams<{ id: string }>();
const nid = Number(id);
const { data: network } = useIPAMNetwork(nid);
const { data: stats } = useIPAMNetworkStats(nid);
const { data: pools = [] } = useIPAMPools(nid);
const { data: allocations = [] } = useIPAMAllocations({ network_id: nid, limit: 100 });
if (!network) return
{t('common.loading')}
;
return (
} variant="ghost" size="sm">
{network.name}
{network.network}
{network.is_active ? 'Active' : 'Inactive'}
{/* Stats */}
{/* Utilization bar */}
{t('ipam.utilization')}
{(stats?.utilization_percent ?? network.utilization_percent ?? 0).toFixed(1)}%
{/* Network info */}
{t('ipam.network_info')}
{network.description && }
{/* Pools */}
{/* IP map */}
{/* Allocations */}
{t('ipam.allocations')} ({allocations.length})
IP
{t('common.status')}
{t('ipam.resource')}
MAC
{t('ipam.description')}
{allocations.map(a => (
{a.ip_address}
{a.status}
{a.resource_name || '—'}
{a.mac_address || '—'}
{a.description || '—'}
))}
{allocations.length === 0 && (
{t('common.no_data')}
)}
);
}
function NetworkActions({ network }: { network: IPAMNetwork }) {
const { t } = useTranslation();
const navigate = useNavigate();
const updateNet = useUpdateNetwork();
const deleteNet = useDeleteNetwork();
const [editOpen, setEditOpen] = useState(false);
const [delOpen, setDelOpen] = useState(false);
const [force, setForce] = useState(false);
const [form, setForm] = useState({
name: network.name,
network: network.network,
gateway: network.gateway ?? '',
vlan_id: network.vlan_id ? String(network.vlan_id) : '',
dns_primary: network.dns_primary ?? '',
dns_secondary: network.dns_secondary ?? '',
dns_domain: network.dns_domain ?? '',
proxmox_bridge: network.proxmox_bridge ?? '',
workspace_id: network.workspace_id ?? undefined,
is_default: !!network.is_default,
is_active: network.is_active,
description: network.description ?? '',
});
const handleSave = () => {
updateNet.mutate(
{
id: network.id,
name: form.name,
gateway: form.gateway || undefined,
vlan_id: form.vlan_id ? Number(form.vlan_id) : undefined,
dns_primary: form.dns_primary || undefined,
dns_secondary: form.dns_secondary || undefined,
dns_domain: form.dns_domain || undefined,
proxmox_bridge: form.proxmox_bridge || undefined,
// null явно очищает привязку области на бэкенде (undefined был бы исключён из update)
workspace_id: (form.workspace_id ?? null) as number | undefined,
is_default: form.is_default,
is_active: form.is_active,
description: form.description || undefined,
},
{
onSuccess: () => { toast.success(t('ipam.network_updated')); setEditOpen(false); },
onError: (e: Error) => toast.error(e.message),
},
);
};
const handleDelete = () => {
deleteNet.mutate(
{ id: network.id, force },
{
onSuccess: () => { toast.success(t('ipam.network_deleted')); navigate('/ipam/networks'); },
onError: (e: Error) => { toast.error(e.message); setForce(true); },
},
);
};
return (
<>
>
);
}
const emptyPool = { name: '', pool_type: 'static', range_start: '', range_end: '', auto_assign: false, description: '' };
function PoolsCard({ networkId, pools }: { networkId: number; pools: IPAMPool[] }) {
const { t } = useTranslation();
const confirm = useConfirm();
const createPool = useCreatePool();
const updatePool = useUpdatePool();
const deletePool = useDeletePool();
const [open, setOpen] = useState(false);
const [editing, setEditing] = useState(null);
const [form, setForm] = useState(emptyPool);
const openCreate = () => { setEditing(null); setForm(emptyPool); setOpen(true); };
const openEdit = (p: IPAMPool) => {
setEditing(p);
setForm({ name: p.name, pool_type: p.pool_type, range_start: p.range_start, range_end: p.range_end, auto_assign: p.auto_assign, description: p.description ?? '' });
setOpen(true);
};
const handleSubmit = () => {
const payload = {
name: form.name,
pool_type: form.pool_type as IPAMPool['pool_type'],
range_start: form.range_start,
range_end: form.range_end,
auto_assign: form.auto_assign,
description: form.description || undefined,
};
if (editing) {
updatePool.mutate({ id: editing.id, ...payload }, {
onSuccess: () => { toast.success(t('ipam.pool_updated')); setOpen(false); },
onError: (e: Error) => toast.error(e.message),
});
} else {
createPool.mutate({ network_id: networkId, ...payload }, {
onSuccess: () => { toast.success(t('ipam.pool_created')); setOpen(false); },
onError: (e: Error) => toast.error(e.message),
});
}
};
const handleDelete = async (p: IPAMPool) => {
if (!await confirm(t('ipam.delete_pool_confirm', { name: p.name }))) return;
deletePool.mutate(p.id, {
onSuccess: () => toast.success(t('ipam.pool_deleted')),
onError: (e: Error) => toast.error(e.message),
});
};
return (
{t('ipam.pools')} ({pools.length})
{t('common.name')}
{t('common.type')}
{t('ipam.range')}
{t('ipam.usage')}
{pools.map(pool => (
{pool.name}
{pool.pool_type}
{pool.range_start} — {pool.range_end}
{pool.used_ips ?? 0} / {pool.total_ips ?? 0}
))}
{pools.length === 0 && (
{t('common.no_data')}
)}
);
}
const ipMapColors: Record = {
gateway: 'bg-purple-500',
allocated: 'bg-blue-500',
reserved: 'bg-warning',
available: 'bg-muted',
};
function IPMapCard({ networkId }: { networkId: number }) {
const { t } = useTranslation();
const { data, isLoading } = useIPAMIPMap(networkId);
const entries = data?.ip_map ?? [];
const MAX = 1024;
const shown = entries.slice(0, MAX);
return (
{t('ipam.ip_map')}{entries.length > 0 && ` (${entries.length})`}
{isLoading ? (
{t('common.loading')}
) : entries.length === 0 ? (
{t('common.no_data')}
) : (
<>
{shown.map(e => {
const label = [
e.proxmox_vmid != null ? `VMID ${e.proxmox_vmid}` : null,
e.resource_name || e.hostname || null,
e.ip_address,
].filter(Boolean).join(' · ');
return (
);
})}
{entries.length > MAX && (
{t('ipam.ip_map_truncated', { shown: MAX, total: entries.length })}
)}
{(['gateway', 'allocated', 'reserved', 'available'] as const).map(s => (
{t(`ipam.${s}`, s)}
))}
>
)}
);
}
function Field({ label, children, full }: { label: string; children: React.ReactNode; full?: boolean }) {
return (
{children}
);
}
function StatCard({ label, value }: { label: string; value: number }) {
return (
{value}
{label}
);
}
function InfoRow({ label, value }: { label: string; value: string }) {
return (
{label}
{value}
);
}