// DBIS Global Overview Dashboard
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 StatusIndicator from '@/components/shared/StatusIndicator';
import DataTable, { Column } from '@/components/shared/DataTable';
import Button from '@/components/shared/Button';
import PieChart from '@/components/shared/PieChart';
import { AdminPermission } from '@/constants/permissions';
import PermissionGate from '@/components/auth/PermissionGate';
import LoadingSpinner from '@/components/shared/LoadingSpinner';
import { TableSkeleton } from '@/components/shared/Skeleton';
import ExportButton from '@/components/shared/ExportButton';
import { REFETCH_INTERVALS } from '@/constants/config';
import type { SCBStatus } from '@/types';
import { formatDistanceToNow } from 'date-fns';
import './OverviewPage.css';

export default function OverviewPage() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['dbis-overview'],
    queryFn: () => dbisAdminApi.getGlobalOverview(),
    refetchInterval: () => {
      // Use longer interval when tab is hidden
      return document.hidden ? 30000 : 10000;
    },
  });

  if (isLoading) {
    return (
      <div className="page-container" role="status" aria-label="Loading dashboard">
        <div className="page-header">
          <h1>Global Overview</h1>
        </div>
        <DashboardLayout>
          <TableSkeleton rows={5} cols={4} />
        </DashboardLayout>
      </div>
    );
  }

  if (error) {
    return (
      <div className="page-container">
        <div className="error-state">Error loading dashboard data</div>
      </div>
    );
  }

  const assetTypeData = data?.settlementThroughput.byAssetType
    ? Object.entries(data.settlementThroughput.byAssetType).map(([name, value]) => ({
        name: name.toUpperCase(),
        value,
      }))
    : [];

  const scbColumns: Column<SCBStatus>[] = [
    {
      key: 'name',
      header: 'SCB Name',
      sortable: true,
    },
    {
      key: 'country',
      header: 'Country',
      sortable: true,
    },
    {
      key: 'status',
      header: 'Status',
      render: (row) => (
        <span className={`status-badge status-badge--${row.status}`}>{row.status}</span>
      ),
    },
    {
      key: 'connectivity',
      header: 'Connectivity',
      render: (row) => <StatusIndicator status={row.connectivity} />,
    },
    {
      key: 'latency',
      header: 'Latency',
      render: (row) => (row.latency ? `${row.latency}ms` : '-'),
    },
    {
      key: 'errorRate',
      header: 'Error Rate',
      render: (row) => (row.errorRate ? `${(row.errorRate * 100).toFixed(2)}%` : '-'),
    },
    {
      key: 'openIncidents',
      header: 'Open Incidents',
      render: (row) => (
        <span className={row.openIncidents > 0 ? 'incident-count--has-incidents' : ''}>
          {row.openIncidents}
        </span>
      ),
    },
  ];

  return (
    <div className="page-container">
      <header className="page-header">
        <h1>Global Overview</h1>
        <div className="page-header__actions">
          {data?.scbStatus && (
            <ExportButton
              data={data.scbStatus}
              columns={scbColumns}
              filename="dbis-global-overview"
              exportType="csv"
            />
          )}
          <Button 
            variant="secondary" 
            size="small" 
            onClick={() => window.location.reload()}
            aria-label="Refresh dashboard data"
          >
            Refresh
          </Button>
        </div>
      </header>

      <DashboardLayout>
        {/* Network Health Widget */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>Network Health</h2>
          </div>
          <div className="widget__content">
            <div className="network-health-grid">
              {data?.networkHealth.map((subsystem) => (
                <div key={subsystem.subsystem} className="network-health-card">
                  <StatusIndicator status={subsystem.status} size="large" pulse={subsystem.status === 'healthy'} />
                  <div className="network-health-card__info">
                    <div className="network-health-card__name">{subsystem.subsystem}</div>
                    {subsystem.lastHeartbeat && (
                      <div className="network-health-card__heartbeat">
                        {formatDistanceToNow(new Date(subsystem.lastHeartbeat), { addSuffix: true })}
                      </div>
                    )}
                    {subsystem.latency !== undefined && (
                      <div className="network-health-card__latency">{subsystem.latency}ms</div>
                    )}
                  </div>
                  <PermissionGate permission={AdminPermission.NETWORK_QUIESCE_SUBSYSTEM}>
                    <Button size="small" variant="secondary">
                      Quiesce
                    </Button>
                  </PermissionGate>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Settlement Throughput Widget */}
        <div className="widget">
          <div className="widget__header">
            <h2>Settlement Throughput</h2>
          </div>
          <div className="widget__content">
            <MetricCard
              title="Transactions/sec"
              value={data?.settlementThroughput.txPerSecond.toFixed(2) || '0'}
              variant="primary"
            />
            <MetricCard
              title="Daily Volume"
              value={`$${(data?.settlementThroughput.dailyVolume || 0).toLocaleString()}`}
              variant="success"
            />
            {assetTypeData.length > 0 && (
              <div className="widget__chart">
                <PieChart data={assetTypeData} height={200} />
              </div>
            )}
          </div>
        </div>

        {/* GRU & Liquidity Widget */}
        <div className="widget">
          <div className="widget__header">
            <h2>GRU & Liquidity</h2>
          </div>
          <div className="widget__content">
            <MetricCard
              title="Current GRU Price"
              value={`$${data?.gruLiquidity.currentPrice.toFixed(4) || '0'}`}
              trend={{
                value: (data?.gruLiquidity.volatility || 0) * 100,
                isPositive: false,
              }}
              variant="primary"
            />
            <PermissionGate permission={AdminPermission.VIEW_GRU_COMMAND}>
              <Button variant="primary" fullWidth>
                Open GRU Command Center
              </Button>
            </PermissionGate>
          </div>
        </div>

        {/* Risk Flags Widget */}
        <div className="widget">
          <div className="widget__header">
            <h2>Risk Flags</h2>
          </div>
          <div className="widget__content">
            <div className="risk-flags">
              <div className="risk-flag risk-flag--high">
                <div className="risk-flag__count">{data?.riskFlags.high || 0}</div>
                <div className="risk-flag__label">High</div>
              </div>
              <div className="risk-flag risk-flag--medium">
                <div className="risk-flag__count">{data?.riskFlags.medium || 0}</div>
                <div className="risk-flag__label">Medium</div>
              </div>
              <div className="risk-flag risk-flag--low">
                <div className="risk-flag__count">{data?.riskFlags.low || 0}</div>
                <div className="risk-flag__label">Low</div>
              </div>
            </div>
            <PermissionGate permission={AdminPermission.RISK_ACKNOWLEDGE_ALERT}>
              <Button variant="secondary" fullWidth>
                Acknowledge Alerts
              </Button>
            </PermissionGate>
          </div>
        </div>

        {/* SCB Status Table */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>SCB Status</h2>
          </div>
          <div className="widget__content">
            <DataTable
              data={data?.scbStatus || []}
              columns={scbColumns}
              searchable
              pagination={
                data?.scbStatus
                  ? {
                      page: 1,
                      limit: 50,
                      total: data.scbStatus.length,
                      onPageChange: () => {},
                    }
                  : undefined
              }
            />
          </div>
        </div>
      </DashboardLayout>
    </div>
  );
}
