// DBIS GAS & QPS Control Page
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 GaugeChart from '@/components/shared/GaugeChart';
import PermissionGate from '@/components/auth/PermissionGate';
import { AdminPermission } from '@/constants/permissions';
import ConfirmationDialog from '@/components/shared/ConfirmationDialog';
import toast from 'react-hot-toast';
import './GASQPSPage.css';

interface GASMetrics {
  assetType: string;
  currentLimit: number;
  used: number;
  available: number;
  status: 'normal' | 'warning' | 'critical';
}

interface QPSMapping {
  scbId: string;
  fiId: string;
  profile: string;
  status: 'enabled' | 'disabled';
  validationLevel: 'standard' | 'strict';
}

export default function GASQPSPage() {
  const [showLimitModal, setShowLimitModal] = useState(false);
  const [showThrottleModal, setShowThrottleModal] = useState(false);
  const [selectedAsset, setSelectedAsset] = useState<string | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['gas-qps'],
    queryFn: () => dbisAdminApi.getGASQPSDashboard(),
    refetchInterval: 10000,
  });

  const gasMetrics: GASMetrics[] = data?.gas?.metrics || [
    { assetType: 'Fiat', currentLimit: 1000000, used: 750000, available: 250000, status: 'normal' },
    { assetType: 'CBDC', currentLimit: 500000, used: 450000, available: 50000, status: 'warning' },
    { assetType: 'GRU', currentLimit: 2000000, used: 1900000, available: 100000, status: 'critical' },
    { assetType: 'SSU', currentLimit: 800000, used: 400000, available: 400000, status: 'normal' },
  ];

  const qpsMappings: QPSMapping[] = data?.qps?.mappings || [
    { scbId: 'scb-001', fiId: 'fi-001', profile: 'Standard', status: 'enabled', validationLevel: 'standard' },
    { scbId: 'scb-002', fiId: 'fi-002', profile: 'Enhanced', status: 'enabled', validationLevel: 'strict' },
  ];

  const gasColumns: Column<GASMetrics>[] = [
    { key: 'assetType', header: 'Asset Type', sortable: true },
    {
      key: 'currentLimit',
      header: 'Current Limit',
      render: (row) => `$${row.currentLimit.toLocaleString()}`,
    },
    {
      key: 'used',
      header: 'Used',
      render: (row) => `$${row.used.toLocaleString()}`,
    },
    {
      key: 'available',
      header: 'Available',
      render: (row) => `$${row.available.toLocaleString()}`,
    },
    {
      key: 'utilization',
      header: 'Utilization',
      render: (row) => {
        const percent = (row.used / row.currentLimit) * 100;
        return (
          <div className="utilization-bar">
            <div
              className={`utilization-bar__fill utilization-bar__fill--${row.status}`}
              style={{ width: `${percent}%` }}
            />
            <span className="utilization-bar__text">{percent.toFixed(1)}%</span>
          </div>
        );
      },
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (row) => (
        <PermissionGate permission={AdminPermission.GAS_SET_LIMITS}>
          <Button
            size="small"
            variant="secondary"
            onClick={() => {
              setSelectedAsset(row.assetType);
              setShowLimitModal(true);
            }}
          >
            Adjust Limit
          </Button>
        </PermissionGate>
      ),
    },
  ];

  const qpsColumns: Column<QPSMapping>[] = [
    { key: 'scbId', header: 'SCB ID', sortable: true },
    { key: 'fiId', header: 'FI ID', sortable: true },
    { key: 'profile', header: 'Profile', sortable: true },
    {
      key: 'status',
      header: 'Status',
      render: (row) => (
        <span className={`status-badge status-badge--${row.status}`}>{row.status}</span>
      ),
    },
    {
      key: 'validationLevel',
      header: 'Validation',
      render: (row) => (
        <span className={`validation-badge validation-badge--${row.validationLevel}`}>
          {row.validationLevel}
        </span>
      ),
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (row) => (
        <div className="table-actions">
          <PermissionGate permission={AdminPermission.QPS_ENABLE_DISABLE}>
            <Button size="small" variant="secondary">
              {row.status === 'enabled' ? 'Disable' : 'Enable'}
            </Button>
          </PermissionGate>
        </div>
      ),
    },
  ];

  const totalUtilization = gasMetrics.reduce((sum, m) => sum + (m.used / m.currentLimit) * 100, 0) / gasMetrics.length;

  return (
    <div className="page-container">
      <div className="page-header">
        <h1>GAS & QPS Control</h1>
        <PermissionGate permission={AdminPermission.GAS_THROTTLE_BANDWIDTH}>
          <Button variant="secondary" onClick={() => setShowThrottleModal(true)}>
            Throttle Bandwidth
          </Button>
        </PermissionGate>
      </div>

      <DashboardLayout>
        {/* GAS Overview */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>GAS (Global Asset Settlement) Metrics</h2>
          </div>
          <div className="widget__content">
            <div className="gas-overview-grid">
              <MetricCard
                title="Total Capacity"
                value={`$${gasMetrics.reduce((sum, m) => sum + m.currentLimit, 0).toLocaleString()}`}
                variant="primary"
              />
              <MetricCard
                title="Total Used"
                value={`$${gasMetrics.reduce((sum, m) => sum + m.used, 0).toLocaleString()}`}
                variant="warning"
              />
              <MetricCard
                title="Total Available"
                value={`$${gasMetrics.reduce((sum, m) => sum + m.available, 0).toLocaleString()}`}
                variant="success"
              />
              <div className="gauge-widget">
                <h3>Overall Utilization</h3>
                <GaugeChart
                  value={totalUtilization}
                  target={80}
                  color={totalUtilization > 80 ? '#ef4444' : totalUtilization > 60 ? '#f59e0b' : '#10b981'}
                />
              </div>
            </div>
            <DataTable data={gasMetrics} columns={gasColumns} loading={isLoading} />
          </div>
        </div>

        {/* QPS Control */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>QPS (Quantum Payment System) Mappings</h2>
          </div>
          <div className="widget__content">
            <DataTable data={qpsMappings} columns={qpsColumns} loading={isLoading} searchable />
          </div>
        </div>
      </DashboardLayout>

      {/* Adjust Limit Modal */}
      <ConfirmationDialog
        isOpen={showLimitModal}
        onClose={() => setShowLimitModal(false)}
        onConfirm={() => {
          toast.success(`Limit adjusted for ${selectedAsset}`);
          setShowLimitModal(false);
        }}
        title={`Adjust Limit - ${selectedAsset}`}
        message="Enter the new limit for this asset type:"
        confirmText="Update"
      />

      {/* Throttle Bandwidth Modal */}
      <ConfirmationDialog
        isOpen={showThrottleModal}
        onClose={() => setShowThrottleModal(false)}
        onConfirm={() => {
          toast.success('Bandwidth throttled successfully');
          setShowThrottleModal(false);
        }}
        title="Throttle Bandwidth"
        message="This will reduce the maximum throughput for all settlement types. Continue?"
        confirmText="Throttle"
        variant="danger"
      />
    </div>
  );
}
