// DBIS Risk & Compliance 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 Heatmap from '@/components/shared/Heatmap';
import React from 'react';
import PermissionGate from '@/components/auth/PermissionGate';
import { AdminPermission } from '@/constants/permissions';
import ConfirmationDialog from '@/components/shared/ConfirmationDialog';
import toast from 'react-hot-toast';
import { formatDistanceToNow } from 'date-fns';
import './RiskCompliancePage.css';

interface RiskAlert {
  id: string;
  type: string;
  severity: 'high' | 'medium' | 'low';
  description: string;
  timestamp: string;
  acknowledged: boolean;
  assignedTo?: string;
}

interface OmegaIncident {
  id: string;
  type: string;
  severity: string;
  description: string;
  timestamp: string;
  status: 'open' | 'resolved' | 'escalated';
}

export default function RiskCompliancePage() {
  const [showStressTestModal, setShowStressTestModal] = useState(false);
  const [showAcknowledgeModal, setShowAcknowledgeModal] = useState(false);
  const [selectedAlert, setSelectedAlert] = useState<RiskAlert | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['risk-compliance'],
    queryFn: () => dbisAdminApi.getRiskComplianceDashboard(),
    refetchInterval: 10000,
  });

  const riskAlerts: RiskAlert[] = data?.risk?.alerts || [
    {
      id: 'alert-1',
      type: 'Liquidity Shock',
      severity: 'high',
      description: 'Unusual liquidity drain detected in SCB-002',
      timestamp: new Date().toISOString(),
      acknowledged: false,
    },
    {
      id: 'alert-2',
      type: 'FX Volatility',
      severity: 'medium',
      description: 'Increased volatility in GRU/USD pair',
      timestamp: new Date(Date.now() - 3600000).toISOString(),
      acknowledged: true,
      assignedTo: 'Risk Officer',
    },
  ];

  const omegaIncidents: OmegaIncident[] = data?.omega?.incidents || [
    {
      id: 'inc-1',
      type: 'Settlement Delay',
      severity: 'medium',
      description: 'Delayed settlement detected in corridor SCB-001 → SCB-003',
      timestamp: new Date().toISOString(),
      status: 'open',
    },
  ];

  // SARE Heatmap data (risk by SCB and risk type)
  const sareHeatmapData = [
    { x: 'SCB-001', y: 'Liquidity', value: 0.3, label: 'Low risk' },
    { x: 'SCB-001', y: 'FX', value: 0.5, label: 'Medium risk' },
    { x: 'SCB-002', y: 'Liquidity', value: 0.8, label: 'High risk' },
    { x: 'SCB-002', y: 'FX', value: 0.4, label: 'Low-medium risk' },
    { x: 'SCB-003', y: 'Liquidity', value: 0.2, label: 'Low risk' },
    { x: 'SCB-003', y: 'FX', value: 0.6, label: 'Medium-high risk' },
  ];

  const alertColumns: Column<RiskAlert>[] = [
    {
      key: 'type',
      header: 'Type',
      sortable: true,
    },
    {
      key: 'severity',
      header: 'Severity',
      render: (row) => (
        <span className={`severity-badge severity-badge--${row.severity}`}>{row.severity}</span>
      ),
    },
    { key: 'description', header: 'Description' },
    {
      key: 'timestamp',
      header: 'Time',
      render: (row) => formatDistanceToNow(new Date(row.timestamp), { addSuffix: true }),
    },
    {
      key: 'acknowledged',
      header: 'Status',
      render: (row) => (
        <span className={row.acknowledged ? 'status-acknowledged' : 'status-pending'}>
          {row.acknowledged ? 'Acknowledged' : 'Pending'}
        </span>
      ),
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (row) => (
        <PermissionGate permission={AdminPermission.RISK_ACKNOWLEDGE_ALERT}>
          {!row.acknowledged && (
            <Button
              size="small"
              variant="primary"
              onClick={() => {
                setSelectedAlert(row);
                setShowAcknowledgeModal(true);
              }}
            >
              Acknowledge
            </Button>
          )}
        </PermissionGate>
      ),
    },
  ];

  const incidentColumns: Column<OmegaIncident>[] = [
    { key: 'type', header: 'Type', sortable: true },
    {
      key: 'severity',
      header: 'Severity',
      render: (row) => (
        <span className={`severity-badge severity-badge--${row.severity}`}>{row.severity}</span>
      ),
    },
    { key: 'description', header: 'Description' },
    {
      key: 'timestamp',
      header: 'Time',
      render: (row) => formatDistanceToNow(new Date(row.timestamp), { addSuffix: true }),
    },
    {
      key: 'status',
      header: 'Status',
      render: (row) => (
        <span className={`status-badge status-badge--${row.status}`}>{row.status}</span>
      ),
    },
  ];

  return (
    <div className="page-container">
      <div className="page-header">
        <h1>Risk & Compliance</h1>
        <PermissionGate permission={AdminPermission.RISK_TRIGGER_STRESS_TEST}>
          <Button variant="secondary" onClick={() => setShowStressTestModal(true)}>
            Trigger Stress Test
          </Button>
        </PermissionGate>
      </div>

      <DashboardLayout>
        {/* Risk Overview */}
        <MetricCard
          title="High Risk Alerts"
          value={riskAlerts.filter((a) => a.severity === 'high' && !a.acknowledged).length}
          variant="danger"
        />
        <MetricCard
          title="Medium Risk Alerts"
          value={riskAlerts.filter((a) => a.severity === 'medium' && !a.acknowledged).length}
          variant="warning"
        />
        <MetricCard
          title="Ω-Layer Incidents"
          value={omegaIncidents.filter((i) => i.status === 'open').length}
          variant="info"
        />

        {/* SARE Heatmap */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>SARE (Sovereign AI Risk Engine) Heatmap</h2>
          </div>
          <div className="widget__content">
            <Heatmap
              data={sareHeatmapData}
              xLabels={['SCB-001', 'SCB-002', 'SCB-003']}
              yLabels={['Liquidity', 'FX']}
              height={300}
            />
          </div>
        </div>

        {/* ARI Alerts */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>ARI (Autonomous Regulatory Intelligence) Alerts</h2>
          </div>
          <div className="widget__content">
            <DataTable data={riskAlerts} columns={alertColumns} loading={isLoading} searchable />
          </div>
        </div>

        {/* Ω-Layer Incidents */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>Ω-Layer Incidents</h2>
          </div>
          <div className="widget__content">
            <DataTable data={omegaIncidents} columns={incidentColumns} loading={isLoading} searchable />
          </div>
        </div>
      </DashboardLayout>

      {/* Stress Test Modal */}
      <ConfirmationDialog
        isOpen={showStressTestModal}
        onClose={() => setShowStressTestModal(false)}
        onConfirm={() => {
          toast.success('Stress test triggered');
          setShowStressTestModal(false);
        }}
        title="Trigger Targeted Stress Test"
        message="This will run a stress test on the selected scenarios. Continue?"
        confirmText="Run Test"
      />

      {/* Acknowledge Alert Modal */}
      <ConfirmationDialog
        isOpen={showAcknowledgeModal}
        onClose={() => setShowAcknowledgeModal(false)}
        onConfirm={() => {
          toast.success('Alert acknowledged');
          setShowAcknowledgeModal(false);
        }}
        title="Acknowledge Alert"
        message={`Acknowledge ${selectedAlert?.type} alert: ${selectedAlert?.description}?`}
        confirmText="Acknowledge"
      />
    </div>
  );
}
