// 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 LoadingSpinner from '@/components/shared/LoadingSpinner';
import type { SCBStatus } from '@/types';
import { env } from '@/config/env';
import './OverviewPage.css';

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

  if (isLoading) {
    return (
      <div className="page-container">
        <LoadingSpinner fullPage />
      </div>
    );
  }

  if (error) {
    const isNetworkError = (error as any)?.message?.includes('Network') ||
                          (error as any)?.code === 'ERR_NETWORK' ||
                          (error as any)?.isNetworkError;

    return (
      <div className="page-container">
        <div className="error-state">
          {isNetworkError ? (
            <div>
              <h2>API Connection Error</h2>
              <p>The backend API is not available at {env.VITE_API_BASE_URL}</p>
              <p>Please ensure the API server is running.</p>
              <Button
                variant="secondary"
                onClick={() => window.location.reload()}
                style={{ marginTop: '1rem' }}
              >
                Retry
              </Button>
            </div>
          ) : (
            <div>
              <h2>Error loading dashboard data</h2>
              <p>{(error as Error).message}</p>
            </div>
          )}
        </div>
      </div>
    );
  }

  const scbColumns: Column<SCBStatus>[] = [
    { key: 'scbId', header: 'SCB ID', sortable: true },
    { key: 'name', header: 'Name', sortable: true },
    { key: 'country', header: 'Country', sortable: true },
    {
      key: 'connectivity',
      header: 'Status',
      render: (row) => <StatusIndicator status={row.connectivity} />,
    },
  ];

  return (
    <div className="page-container">
      <div className="page-header">
        <h1>DBIS Global Overview</h1>
      </div>
      <DashboardLayout>
        <MetricCard title="Network Health" value={`${data?.networkHealth.filter(h => h.status === 'healthy').length || 0}/${data?.networkHealth.length || 0}`} />
        <MetricCard title="Settlement Throughput" value={`${(data?.settlementThroughput?.txPerSecond || 0).toFixed(1)} tx/s`} />
        <MetricCard title="Daily Volume" value={`$${((data?.settlementThroughput?.dailyVolume || 0) / 1000000).toFixed(1)}M`} />
        <MetricCard title="GRU Price" value={`$${(data?.gruLiquidity?.currentPrice || 0).toFixed(4)}`} />
        <MetricCard title="Risk Flags" value={`${data?.riskFlags?.high || 0} High, ${data?.riskFlags?.medium || 0} Medium`} />
      </DashboardLayout>
      <div className="mt-6">
        <h2 className="text-xl font-semibold mb-4">SCB Status</h2>
        <DataTable data={data?.scbStatus || []} columns={scbColumns} />
      </div>
    </div>
  );
}
