// DBIS Metaverse & Edge Screen
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { dbisAdminApi } from '@/services/api/dbisAdminApi';
import DashboardLayout from '@/components/layout/DashboardLayout';
import MetricCard from '@/components/shared/MetricCard';
import DataTable, { Column } from '@/components/shared/DataTable';
import Button from '@/components/shared/Button';
import StatusIndicator from '@/components/shared/StatusIndicator';
import PermissionGate from '@/components/auth/PermissionGate';
import { AdminPermission } from '@/constants/permissions';
import ConfirmationDialog from '@/components/shared/ConfirmationDialog';
import toast from 'react-hot-toast';
import './MetaverseEdgePage.css';

interface MetaverseNode {
  id: string;
  name: string;
  region: string;
  status: 'active' | 'degraded' | 'offline';
  onRampEnabled: boolean;
  dailyLimit: number;
  kycRequired: boolean;
  connections: number;
}

interface EdgeNode {
  id: string;
  region: string;
  gpuCount: number;
  load: number;
  priority: 'settlement' | 'rendering' | 'balanced';
  status: 'healthy' | 'overloaded' | 'quarantined';
}

export default function MetaverseEdgePage() {
  const [showQuarantineModal, setShowQuarantineModal] = useState(false);
  const [selectedNode, setSelectedNode] = useState<EdgeNode | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['metaverse-edge'],
    queryFn: () => dbisAdminApi.getMetaverseEdgeDashboard(),
    refetchInterval: 10000,
  });

  const metaverseNodes: MetaverseNode[] = data?.metaverse?.nodes || [
    {
      id: 'men-001',
      name: 'Decentraland Gateway',
      region: 'US-East',
      status: 'active',
      onRampEnabled: true,
      dailyLimit: 1000000,
      kycRequired: true,
      connections: 1250,
    },
    {
      id: 'men-002',
      name: 'Sandbox Hub',
      region: 'EU-Central',
      status: 'active',
      onRampEnabled: true,
      dailyLimit: 800000,
      kycRequired: true,
      connections: 980,
    },
  ];

  const edgeNodes: EdgeNode[] = data?.edge?.nodes || [
    { id: 'edge-001', region: 'US-West', gpuCount: 100, load: 65, priority: 'settlement', status: 'healthy' },
    { id: 'edge-002', region: 'EU-East', gpuCount: 80, load: 85, priority: 'balanced', status: 'overloaded' },
    { id: 'edge-003', region: 'Asia-Pacific', gpuCount: 120, load: 45, priority: 'rendering', status: 'healthy' },
  ];

  const metaverseColumns: Column<MetaverseNode>[] = [
    { key: 'name', header: 'Node Name', sortable: true },
    { key: 'region', header: 'Region', sortable: true },
    {
      key: 'status',
      header: 'Status',
      render: (row) => <StatusIndicator status={row.status} showLabel />,
    },
    {
      key: 'onRampEnabled',
      header: 'On-Ramp',
      render: (row) => (
        <span className={`status-badge status-badge--${row.onRampEnabled ? 'enabled' : 'disabled'}`}>
          {row.onRampEnabled ? 'Enabled' : 'Disabled'}
        </span>
      ),
    },
    {
      key: 'dailyLimit',
      header: 'Daily Limit',
      render: (row) => `$${row.dailyLimit.toLocaleString()}`,
    },
    {
      key: 'connections',
      header: 'Connections',
      render: (row) => row.connections.toLocaleString(),
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (row) => (
        <PermissionGate permission={AdminPermission.METAVERSE_ENABLE_ONRAMP}>
          <Button
            size="small"
            variant="secondary"
            onClick={() => {
              toast.success(`On-ramp ${row.onRampEnabled ? 'disabled' : 'enabled'}`);
            }}
          >
            {row.onRampEnabled ? 'Disable' : 'Enable'}
          </Button>
        </PermissionGate>
      ),
    },
  ];

  const edgeColumns: Column<EdgeNode>[] = [
    { key: 'id', header: 'Node ID', sortable: true },
    { key: 'region', header: 'Region', sortable: true },
    {
      key: 'gpuCount',
      header: 'GPU Count',
      render: (row) => row.gpuCount.toLocaleString(),
    },
    {
      key: 'load',
      header: 'Load',
      render: (row) => (
        <div className="load-bar">
          <div
            className={`load-bar__fill load-bar__fill--${row.status}`}
            style={{ width: `${row.load}%` }}
          />
          <span className="load-bar__text">{row.load}%</span>
        </div>
      ),
    },
    {
      key: 'priority',
      header: 'Priority',
      render: (row) => (
        <span className={`priority-badge priority-badge--${row.priority}`}>{row.priority}</span>
      ),
    },
    {
      key: 'status',
      header: 'Status',
      render: (row) => <StatusIndicator status={row.status} showLabel />,
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (row) => (
        <div className="table-actions">
          <PermissionGate permission={AdminPermission.EDGE_DRAIN_LOAD}>
            <Button size="small" variant="secondary">
              Drain Load
            </Button>
          </PermissionGate>
          {row.status !== 'quarantined' && (
            <PermissionGate permission={AdminPermission.EDGE_QUARANTINE}>
              <Button
                size="small"
                variant="danger"
                onClick={() => {
                  setSelectedNode(row);
                  setShowQuarantineModal(true);
                }}
              >
                Quarantine
              </Button>
            </PermissionGate>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className="page-container">
      <div className="page-header">
        <h1>Metaverse & Edge</h1>
      </div>

      <DashboardLayout>
        {/* Metaverse Nodes */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>Metaverse Economic Nodes (MEN)</h2>
          </div>
          <div className="widget__content">
            <div className="metrics-row">
              <MetricCard
                title="Total Nodes"
                value={metaverseNodes.length}
                variant="primary"
              />
              <MetricCard
                title="Active Nodes"
                value={metaverseNodes.filter((n) => n.status === 'active').length}
                variant="success"
              />
              <MetricCard
                title="Total Connections"
                value={metaverseNodes.reduce((sum, n) => sum + n.connections, 0).toLocaleString()}
                variant="info"
              />
            </div>
            <DataTable data={metaverseNodes} columns={metaverseColumns} loading={isLoading} searchable />
          </div>
        </div>

        {/* 6G Edge GPU Grid */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>6G Edge GPU Grid</h2>
          </div>
          <div className="widget__content">
            <div className="metrics-row">
              <MetricCard
                title="Total GPUs"
                value={edgeNodes.reduce((sum, n) => sum + n.gpuCount, 0).toLocaleString()}
                variant="primary"
              />
              <MetricCard
                title="Average Load"
                value={`${Math.round(edgeNodes.reduce((sum, n) => sum + n.load, 0) / edgeNodes.length)}%`}
                variant="warning"
              />
              <MetricCard
                title="Quarantined Nodes"
                value={edgeNodes.filter((n) => n.status === 'quarantined').length}
                variant="danger"
              />
            </div>
            <DataTable data={edgeNodes} columns={edgeColumns} loading={isLoading} searchable />
          </div>
        </div>
      </DashboardLayout>

      {/* Quarantine Confirmation */}
      <ConfirmationDialog
        isOpen={showQuarantineModal}
        onClose={() => setShowQuarantineModal(false)}
        onConfirm={() => {
          toast.success(`Node ${selectedNode?.id} quarantined`);
          setShowQuarantineModal(false);
        }}
        title="Quarantine Edge Node"
        message={`Are you sure you want to quarantine node ${selectedNode?.id}? This will isolate it from the network.`}
        confirmText="Quarantine"
        variant="danger"
      />
    </div>
  );
}
