import React, { useEffect, useState, useCallback, memo } from 'react';
import { ServerContext } from '@/state/server';
import { getServerSplit, ServerSplit } from './api/getServerSplit';
import { splitServer } from './api/splitServer';
import { deleteSplitServer } from './api/deleteSplitServer';
import getServerResourceUsage, { ServerPowerState } from '@/api/server/getServerResourceUsage';
import Spinner from '@/components/elements/Spinner';
import ServerContentBlock from '@/components/elements/ServerContentBlock';
import useFlash from '@/plugins/useFlash';
import FlashMessageRender from '@/components/FlashMessageRender';
import SplitServerDialog from './SplitServerDialog';
import { Button } from '@/components/elements/button/index';
import tw from 'twin.macro';
import styled from 'styled-components/macro';
import Can from '@/components/elements/Can';
interface SplitServerRowProps {
    server: any;
    isMaster: boolean;
    onDelete: (uuid: string) => void;
    onOpen?: () => void;
    onEdit?: (uuid: string) => void;
    parentSwapZero?: boolean;
}
interface ResourceData {
    cpu: number;
    memory: number;
    disk: number;
    swap: number;
    databases: number;
    backups: number;
    allocations: number;
}
const ServerRow = styled.div<{ $status?: ServerPowerState | null }>`
    ${tw`bg-gray-700 border-l-4 p-4 rounded-md transition-all duration-150`};
    ${({ $status }) => {
        if (!$status || $status === 'offline') {
            return tw`border-red-500`;
        }
        if ($status === 'running') {
            return tw`border-green-500`;
        }
        return tw`border-yellow-500`;
    }};
    &:hover {
        ${tw`bg-gray-600`};
    }
`;
const ServerInfo = styled.div`
    ${tw`flex items-center justify-between`};
`;
const ServerDetails = styled.div`
    ${tw`flex items-center`};
`;
const ServerIcon = styled.div`
    ${tw`w-16 h-16 ml-1 mr-2 flex items-center justify-center flex-shrink-0`};
`;
const ServerMeta = styled.div`
    ${tw`w-full`};
`;
const ServerName = styled.h3`
    ${tw`break-words w-auto h-auto text-base`};
`;
const ServerDescription = styled.p`
    ${tw`text-sm text-neutral-300 break-words line-clamp-2 mb-1`};
`;
const ServerResourceList = styled.div`
    ${tw`flex items-center gap-2`};
`;
const ServerResourceItem = styled.div`
    ${tw`flex items-center text-xs text-neutral-400`};
`;
const ServerResourceValue = styled.span`
    ${tw`text-neutral-200 font-medium ml-1`};
`;
const ActionButtons = styled.div`
    ${tw`flex items-center space-x-2`};
`;
const ActionButton = styled.button`
    ${tw`px-4 py-1 text-sm rounded transition-colors duration-150`};
`;
const PrimaryButton = styled(ActionButton)`
    ${tw`bg-blue-600 hover:bg-blue-700 text-white`};
`;
const SecondaryButton = styled(ActionButton)`
    ${tw`bg-neutral-700 hover:bg-neutral-600 text-neutral-200`};
`;
const DangerButton = styled(ActionButton)`
    ${tw`bg-red-600 hover:bg-red-700 text-white`};
`;
const SidebarCard = styled.div`
    ${tw`bg-gray-700 border-l-4 border-blue-400 p-4 rounded-md mb-4`};
`;
const SidebarTitle = styled.h3`
    ${tw`text-sm font-medium text-neutral-300 uppercase tracking-wider mb-4`};
`;
const ResourceItem = styled.div`
    ${tw`flex justify-between items-center py-2 border-b border-gray-500 last:border-b-0`};
`;
const ResourceLabel = styled.span`
    ${tw`text-sm text-neutral-300`};
`;
const ResourceValue = styled.span`
    ${tw`text-sm font-medium text-neutral-100`};
`;
const ResourceCardItem = styled.div`
    ${tw`bg-gray-600 rounded-lg p-4 flex items-center justify-between transition-all duration-200 hover:bg-gray-500`};
`;
const ResourceCardIcon = styled.div`
    ${tw`w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center mr-3 flex-shrink-0`};
`;
const ResourceCardContent = styled.div`
    ${tw`flex-1`};
`;
const ResourceCardLabel = styled.div`
    ${tw`text-xs text-neutral-400 uppercase tracking-wider mb-1`};
`;
const ResourceCardValue = styled.div<{ color?: string }>`
    ${tw`text-lg font-bold`};
    ${props => props.color === 'red' && tw`text-red-400`};
    ${props => props.color === 'green' && tw`text-green-400`};
    ${props => (!props.color || props.color === 'default') && tw`text-neutral-100`};
`;
const ResourceDisplay = memo(({ label, value, isMemory = false }: { label: string; value: number | string; isMemory?: boolean }) => {
    const getResourceIcon = (label: string) => {
        const labelLower = label.toLowerCase();
        if (labelLower.includes('cpu')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-blue-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
            );
        }
        if (labelLower.includes('memory') || labelLower.includes('ram')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-green-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z" />
                </svg>
            );
        }
        if (labelLower.includes('disk') || labelLower.includes('storage')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-yellow-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4" />
                </svg>
            );
        }
        if (labelLower.includes('swap')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-purple-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
                </svg>
            );
        }
        if (labelLower.includes('database')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-indigo-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4" />
                </svg>
            );
        }
        if (labelLower.includes('allocation') || labelLower.includes('port')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-red-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
            );
        }
        if (labelLower.includes('backup')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-cyan-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M9 19l3 3m0 0l3-3m-3 3V10" />
                </svg>
            );
        }
        if (labelLower.includes('server')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-red-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2" />
                </svg>
            );
        }
        if (labelLower.includes('split')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-pink-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
                </svg>
            );
        }
        if (labelLower.includes('total')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-blue-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                </svg>
            );
        }
        if (labelLower.includes('available')) {
            return (
                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-green-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
            );
        }
        return (
            <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 text-gray-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
        );
    };
    const getValueColor = (value: string | number): 'red' | 'green' | 'default' => {
        if (typeof value === 'string') {
            if (value.includes('Insufficient') || value.includes('Disabled')) {
                return 'red';
            }
            if (value.includes('Unlimited') || value.includes('∞')) {
                return 'green';
            }
        }
        return 'default';
    };
    return (
        <ResourceCardItem>
            <div css={tw`flex items-center flex-1`}>
                <ResourceCardIcon>
                    {getResourceIcon(label)}
                </ResourceCardIcon>
                <ResourceCardContent>
                    <ResourceCardLabel>{label}</ResourceCardLabel>
                    <ResourceCardValue color={getValueColor(value)}>
                        {value}
                    </ResourceCardValue>
                </ResourceCardContent>
            </div>
        </ResourceCardItem>
    );
});
ResourceDisplay.displayName = 'ResourceDisplay';
const ResourceCard = memo(({ title, children }: { title: string; children: React.ReactNode }) => (
    <SidebarCard>
        <SidebarTitle>{title}</SidebarTitle>
        <div css={tw`grid grid-cols-1 md:grid-cols-2 gap-4`}>
            {children}
        </div>
    </SidebarCard>
));
ResourceCard.displayName = 'ResourceCard';
const EmptyState = memo(({ onCreateSplit, canSplit }: { onCreateSplit: () => void; canSplit: boolean }) => (
    <div css={tw`bg-gray-700 border-l-4 border-gray-500 p-8 text-center rounded-md`}>
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" css={tw`mx-auto mb-4 text-neutral-300`}>
            <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" stroke="currentColor" strokeWidth="1.5" fill="none" />
        </svg>
        <h3 css={tw`text-lg font-medium text-neutral-300 mb-2`}>No Split Servers</h3>
        <p css={tw`text-neutral-300 mb-4`}>Create your first split server to get started.</p>
        <Can action={'split.create'}>
            <Button onClick={onCreateSplit} disabled={!canSplit}>
                Create Split Server
            </Button>
        </Can>
    </div>
));
EmptyState.displayName = 'EmptyState';
const SplitServerRow = memo(({ server, isMaster, onDelete, onOpen, onEdit }: SplitServerRowProps) => {
    const [powerStatus, setPowerStatus] = useState<ServerPowerState | null>(null);
    const formatMemory = useCallback((mb: number) => {
        if (mb >= 1024) {
            const gb = (mb / 1024).toFixed(1);
            return `${gb} GB`;
        }
        return `${mb} MB`;
    }, []);
    useEffect(() => {
        const getPowerStatus = () => {
            getServerResourceUsage(server.uuid)
                .then((data) => {
                    setPowerStatus(data.status);
                })
                .catch((error) => {
                    console.error('Failed to get server power status:', error);
                    setPowerStatus(server.status === 'suspended' ? 'offline' : null);
                });
        };
        getPowerStatus();
    }, [server.uuid]);
    const displayStatus = powerStatus || (server.status === 'suspended' ? 'offline' : null);
    return (
        <ServerRow onClick={() => isMaster ? (onOpen && onOpen()) : (onEdit && onEdit(server.uuid))} css={tw`cursor-pointer`} $status={displayStatus}>
            <ServerInfo>
                <ServerDetails>
                    <ServerIcon>
                        <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-16 h-16 text-neutral-300`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2" />
                        </svg>
                    </ServerIcon>
                    <ServerMeta>
                        <div css={tw`flex items-center gap-2`}>
                            <ServerName>{server.name}</ServerName>
                            {isMaster && (
                                <span css={tw`px-2 py-1 text-xs font-medium bg-purple-600 text-white rounded-full`}>
                                    Master
                                </span>
                            )}
                        </div>
                        {server.description && (
                            <ServerDescription>{server.description}</ServerDescription>
                        )}
                        <ServerResourceList>
                            <ServerResourceItem>
                                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 mr-1 text-blue-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                </svg>
                                CPU:<ServerResourceValue>{server.limits.cpu}%</ServerResourceValue>
                            </ServerResourceItem>
                            <ServerResourceItem>
                                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 mr-1 text-green-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z" />
                                </svg>
                                Memory:<ServerResourceValue>{formatMemory(server.limits.memory)}</ServerResourceValue>
                            </ServerResourceItem>
                            <ServerResourceItem>
                                <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 mr-1 text-yellow-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4" />
                                </svg>
                                Disk:<ServerResourceValue>{formatMemory(server.limits.disk)}</ServerResourceValue>
                            </ServerResourceItem>
                            {server.limits.swap > 0 && (
                                <ServerResourceItem>
                                    <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 mr-1 text-purple-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
                                    </svg>
                                    Swap:<ServerResourceValue>{formatMemory(server.limits.swap)}</ServerResourceValue>
                                </ServerResourceItem>
                            )}
                            {(server.featureLimits.databases || 0) > 0 && (
                                <ServerResourceItem>
                                    <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 mr-1 text-indigo-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4" />
                                    </svg>
                                    Databases:<ServerResourceValue>{server.featureLimits.databases}</ServerResourceValue>
                                </ServerResourceItem>
                            )}
                            {(server.featureLimits.allocations || 0) > 0 && (
                                <ServerResourceItem>
                                    <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 mr-1 text-red-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                                    </svg>
                                    Allocations:<ServerResourceValue>{server.featureLimits.allocations}</ServerResourceValue>
                                </ServerResourceItem>
                            )}
                            {(server.featureLimits.backups || 0) > 0 && (
                                <ServerResourceItem>
                                    <svg xmlns="http://www.w3.org/2000/svg" css={tw`w-4 h-4 mr-1 text-cyan-400`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
                                    </svg>
                                    Backups:<ServerResourceValue>{server.featureLimits.backups}</ServerResourceValue>
                                </ServerResourceItem>
                            )}
                        </ServerResourceList>
                    </ServerMeta>
                </ServerDetails>
            </ServerInfo>
        </ServerRow>
    );
});
SplitServerRow.displayName = 'SplitServerRow';
const SplitServerContainer = () => {
    const server = ServerContext.useStoreState((state) => state.server.data!);
    const uuid = server.uuid;
    const [splitData, setSplitData] = useState<ServerSplit | null>(null);
    const [loading, setLoading] = useState(true);
    const [showSplitDialog, setShowSplitDialog] = useState(false);
    const [showEditDialog, setShowEditDialog] = useState(false);
    const [editingUuid, setEditingUuid] = useState<string | null>(null);
    const { addError, clearFlashes, addFlash } = useFlash();
    const loadSplitData = useCallback(() => {
        setLoading(true);
        clearFlashes('server:split');
        getServerSplit(uuid)
            .then((data) => {
                setSplitData(data);
                setLoading(false);
            })
            .catch((error) => {
                console.error(error);
                addError({ key: 'server:split', message: 'Failed to load server split data.' });
                setLoading(false);
            });
    }, [uuid, clearFlashes, addError]);
    const handleSplitServer = useCallback(async (values: any) => {
        try {
            await splitServer(uuid, values);
            addFlash({ type: 'success', key: 'server:split', message: 'Server split successfully.' });
            loadSplitData();
            setShowSplitDialog(false);
        } catch (error) {
            addError({ key: 'server:split', message: 'Failed to split server.' });
            console.error(error);
        }
    }, [uuid, addFlash, addError, loadSplitData]);
    const handleDeleteSplit = useCallback(async (splitUuid: string) => {
        try {
            await deleteSplitServer(uuid, splitUuid);
            addFlash({ type: 'success', key: 'server:split', message: 'Split server deleted successfully.' });
            loadSplitData();
        } catch (error) {
            addError({ key: 'server:split', message: 'Failed to delete split server.' });
            console.error(error);
        }
    }, [uuid, addFlash, addError, loadSplitData]);
    const handleOpenServer = useCallback((serverId: string) => {
        window.location.href = `/server/${serverId}`;
    }, []);
    const handleEditServer = useCallback((serverUuid: string) => {
        setEditingUuid(serverUuid);
        setShowEditDialog(true);
    }, []);
    const handleCloseEditDialog = useCallback(() => {
        setShowEditDialog(false);
        setEditingUuid(null);
    }, []);
    const formatResource = useCallback((mb: number, originalLimit: number) => {
        if (originalLimit === 0) return '∞';
        if (mb < 0) return 'Insufficient';
        if (!mb) return '0 MB';
        if (mb >= 1024) {
            const gb = (mb / 1024).toFixed(1);
            return `${gb} GB`;
        }
        return `${mb} MB`;
    }, []);
    const calculatePercentage = useCallback((used: number, total: number) => {
        if (total === 0) return 0;
        return Math.min(Math.round((used / total) * 100), 100);
    }, []);
    const getSplitErrorMessage = useCallback((splitData: ServerSplit) => {
        if (splitData.split_limit === 0) return 'Splitting is disabled for this server.';
        if (splitData.original_limits.cpu > 0 && splitData.remaining_resources.cpu < 10) return 'CPU is insufficient for splitting (minimum 10% required).';
        if (splitData.original_limits.memory > 0 && splitData.remaining_resources.memory < 128) return 'Memory is insufficient for splitting (minimum 128 MB required).';
        if (splitData.original_limits.disk > 0 && splitData.remaining_resources.disk < 256) return 'Disk is insufficient for splitting (minimum 256 MB required).';
        if (splitData.original_limits.cpu > 0 && splitData.remaining_resources.cpu < 0) return 'CPU is insufficient for splitting.';
        if (splitData.original_limits.memory > 0 && splitData.remaining_resources.memory < 0) return 'Memory is insufficient for splitting.';
        if (splitData.original_limits.disk > 0 && splitData.remaining_resources.disk < 0) return 'Disk is insufficient for splitting.';
        if (splitData.remaining_resources.databases < 0) return 'No available databases for splitting.';
        if (splitData.remaining_resources.allocations < 1) return 'No available allocations for splitting.';
        if (splitData.remaining_resources.backups < 0) return 'No available backups for splitting.';
        return 'Split limit reached.';
    }, []);
    useEffect(() => {
        loadSplitData();
    }, [loadSplitData]);
    if (loading || !splitData) {
        return <Spinner size={'large'} centered />;
    }
    if (!splitData.is_master) {
        return (
            <ServerContentBlock title={'Server Splitter'}>
                <div css={tw`flex flex-col items-center justify-center w-full py-10`}>
                    <div css={tw`bg-red-900/20 border-l-4 border-red-500 rounded p-4 mb-4 w-full md:w-auto`}>
                        <h2 css={tw`text-xl text-center text-neutral-300 mb-2`}>Access Denied</h2>
                        <p css={tw`text-neutral-300 text-center`}>
                            Only master servers can access the Server Splitter.
                            <br />
                            This is a subserver and cannot be split further.
                        </p>
                    </div>
                </div>
            </ServerContentBlock>
        );
    }
    const canSplit = splitData.split_limit !== 0 &&
        (splitData.servers.length - 1) < splitData.split_limit &&
        (splitData.original_limits.cpu === 0 || splitData.remaining_resources.cpu >= 10) &&
        (splitData.original_limits.memory === 0 || splitData.remaining_resources.memory >= 128) &&
        (splitData.original_limits.disk === 0 || splitData.remaining_resources.disk >= 256) &&
        splitData.remaining_resources.databases >= 0 &&
        splitData.remaining_resources.allocations >= 1 &&
        splitData.remaining_resources.backups >= 0;
    const cpuPercentage = calculatePercentage(splitData.total_usage.cpu, splitData.total_usage.cpu + splitData.remaining_resources.cpu);
    const memoryPercentage = calculatePercentage(splitData.total_usage.memory, splitData.total_usage.memory + splitData.remaining_resources.memory);
    const diskPercentage = calculatePercentage(splitData.total_usage.disk, splitData.total_usage.disk + splitData.remaining_resources.disk);
    const splitServers = splitData.servers.filter(server =>
        server.uuid !== uuid && !server.is_master
    );
    const masterServer = splitData.servers.find(s => s.is_master) || splitData.servers.find(s => s.uuid === uuid);
    const remainingResources = splitData.remaining_resources || { cpu: 0, memory: 0, disk: 0, swap: 0, databases: 0, backups: 0, allocations: 0 };
    return (
        <ServerContentBlock title={'Server Splitter'}>
            <FlashMessageRender byKey={'server:split'} />
            <SplitServerDialog
                open={showSplitDialog}
                onClose={() => setShowSplitDialog(false)}
                server={server}
                onSplit={handleSplitServer}
                remainingResources={remainingResources}
            />
            <div css={tw`grid grid-cols-1 lg:grid-cols-12 gap-4`}>
                <aside css={tw`lg:col-span-4 space-y-4 lg:sticky lg:top-4 h-auto`}>
                    {splitServers.length > 0 && (
                        <Can action={'split.create'}>
                            {!canSplit && (
                                <div css={tw`p-4 bg-red-900/20 border-l-4 border-red-500 rounded-md`}>
                                    <p css={tw`text-red-400 text-sm`}>
                                        {getSplitErrorMessage(splitData)}
                                    </p>
                                </div>
                            )}
                            {canSplit && (
                                <Button
                                    css={tw`w-full`}
                                    onClick={() => setShowSplitDialog(true)}
                                    disabled={!canSplit}
                                >
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" css={tw`mr-2`}>
                                        <path d="M12 6v12m-6-6h12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                                    </svg>
                                    Create Split Server
                                </Button>
                            )}
                        </Can>
                    )}
                    <ResourceCard title="Available Resources">
                        <ResourceDisplay
                            label="CPU"
                            value={splitData.original_limits.cpu === 0 ? '∞' :
                                (splitData.remaining_resources.cpu < 0 ? 'Insufficient' :
                                    (splitData.remaining_resources.cpu === 0 ? '0%' : splitData.remaining_resources.cpu + '%'))}
                        />
                        <ResourceDisplay
                            label="Memory"
                            value={formatResource(splitData.remaining_resources.memory, splitData.original_limits.memory)}
                        />
                        <ResourceDisplay
                            label="Disk"
                            value={formatResource(splitData.remaining_resources.disk, splitData.original_limits.disk)}
                        />
                        {splitData.remaining_resources.swap > 0 && (
                            <ResourceDisplay
                                label="Swap"
                                value={formatResource(splitData.remaining_resources.swap, splitData.original_limits.swap)}
                            />
                        )}
                        <ResourceDisplay
                            label="Database"
                            value={splitData.remaining_resources.databases < 0 ? 'Insufficient' : (splitData.remaining_resources.databases || 0)}
                        />
                        <ResourceDisplay
                            label="Allocation"
                            value={splitData.remaining_resources.allocations < 0 ? 'Insufficient' : (splitData.remaining_resources.allocations || 0)}
                        />
                        <ResourceDisplay
                            label="Backup"
                            value={splitData.remaining_resources.backups < 0 ? 'Insufficient' : (splitData.remaining_resources.backups || 0)}
                        />
                    </ResourceCard>
                    <ResourceCard title="Split Information">
                        <ResourceDisplay
                            label="Total"
                            value={splitData.servers.length}
                        />
                        <ResourceDisplay
                            label="Available"
                            value={splitData.split_limit === 0 ? 'Disabled' : Math.max(0, splitData.split_limit - (splitData.servers.length - 1))}
                        />
                    </ResourceCard>
                </aside>
                <div css={tw`lg:col-span-8`}>
                    <div css={tw`mb-4`}>
                        {masterServer && (
                            <div css={tw`mb-4`}>
                                <SplitServerRow
                                    key={masterServer.uuid}
                                    server={masterServer}
                                    isMaster={true}
                                    onDelete={handleDeleteSplit}
                                    onOpen={() => handleOpenServer(masterServer.id)}
                                    onEdit={() => handleEditServer(masterServer.uuid)}
                                    parentSwapZero={splitData.remaining_resources.swap === 0}
                                />
                            </div>
                        )}
                        {splitServers.length === 0 ? (
                            <EmptyState
                                onCreateSplit={() => setShowSplitDialog(true)}
                                canSplit={canSplit}
                            />
                        ) : (
                            <div>
                                <div css={tw`space-y-4`}>
                                    {splitServers.map((server) => (
                                        <SplitServerRow
                                            key={server.uuid}
                                            server={server}
                                            isMaster={false}
                                            onDelete={handleDeleteSplit}
                                            onOpen={() => handleOpenServer(server.id)}
                                            onEdit={() => handleEditServer(server.uuid)}
                                            parentSwapZero={splitData.remaining_resources.swap === 0}
                                        />
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
            <SplitServerDialog
                open={showEditDialog && editingUuid !== null}
                onClose={handleCloseEditDialog}
                server={server}
                editServer={editingUuid ? (splitData?.servers.find(s => s.uuid === editingUuid) || splitData?.servers[0]) : splitData?.servers[0]}
                isEdit={true}
                remainingResources={remainingResources}
                onUpdate={async (values) => {
                    if (!editingUuid) return;
                    const { updateSplitServer } = await import('./api/updateSplitServer');
                    await updateSplitServer(uuid, editingUuid, values);
                    handleCloseEditDialog();
                    loadSplitData();
                }}
                onDelete={async (serverUuid: string) => {
                    await handleDeleteSplit(serverUuid);
                }}
                onOpenServer={(serverId: string) => {
                    handleOpenServer(serverId);
                }}
            />
        </ServerContentBlock>
    );
};
export default SplitServerContainer;
