/**
 * Monitoring Dashboard - Phase 3.4
 *
 * Real-time monitoring of secret health, rotation compliance,
 * access patterns, and critical alerts.
 */

import React, { useState, useEffect } from 'react';
import {
  AlertTriangle,
  TrendingUp,
  Clock,
  CheckCircle,
  XCircle,
  Activity,
  Shield,
  Zap,
} from 'lucide-react';

interface ExpiringSecret {
  path: string;
  domain: string;
  daysRemaining: number;
  severity: 'critical' | 'warning' | 'info';
}

interface FailedAccess {
  timestamp: string;
  user: string;
  secretPath: string;
  reason: string;
  workspace: string;
}

interface RotationMetrics {
  total: number;
  completed: number;
  pending: number;
  failed: number;
  disabled: number;
  complianceRate: number; // Percentage of secrets rotated on schedule
}

interface SharingMetrics {
  activeGrants: number;
  pendingGrants: number;
  revokedGrants: number;
  totalAccesses: number;
  failedAccesses: number;
}

interface DashboardMetrics {
  expiringSecrets: ExpiringSecret[];
  failedAccessAttempts: FailedAccess[];
  rotationMetrics: RotationMetrics;
  sharingMetrics: SharingMetrics;
  totalSecrets: number;
  temporalSecrets: number;
  permanentSecrets: number;
  lastUpdated: string;
}

interface MonitoringDashboardProps {
  metrics: DashboardMetrics;
  onSecretClick?: (secretPath: string) => void;
  onApproveAccess?: (accessId: string) => void;
  onDenyAccess?: (accessId: string) => void;
}

/**
 * Severity badge for expiring secrets
 */
const SeverityBadge: React.FC<{ severity: ExpiringSecret['severity'] }> = ({ severity }) => {
  const styles: Record<ExpiringSecret['severity'], string> = {
    critical: 'bg-red-100 text-red-800 border border-red-300',
    warning: 'bg-yellow-100 text-yellow-800 border border-yellow-300',
    info: 'bg-blue-100 text-blue-800 border border-blue-300',
  };

  const icons: Record<ExpiringSecret['severity'], React.ReactNode> = {
    critical: <AlertTriangle size={16} className="mr-1" />,
    warning: <Clock size={16} className="mr-1" />,
    info: <Activity size={16} className="mr-1" />,
  };

  return (
    <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${styles[severity]}`}>
      {icons[severity]}
      {severity.charAt(0).toUpperCase() + severity.slice(1)}
    </span>
  );
};

/**
 * Expiring Secrets Alert Card
 */
const ExpiringSecretsCard: React.FC<{
  secrets: ExpiringSecret[];
  onSecretClick?: (secretPath: string) => void;
}> = ({ secrets, onSecretClick }) => {
  const criticalCount = secrets.filter((s) => s.severity === 'critical').length;
  const warningCount = secrets.filter((s) => s.severity === 'warning').length;

  return (
    <div className="bg-white rounded-lg border border-gray-200 p-6 shadow-sm">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-gray-900">Expiring Secrets</h3>
        <div className="flex gap-2">
          {criticalCount > 0 && (
            <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-800">
              <AlertTriangle size={14} className="mr-1" />
              {criticalCount} Critical
            </span>
          )}
          {warningCount > 0 && (
            <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-yellow-100 text-yellow-800">
              <Clock size={14} className="mr-1" />
              {warningCount} Warning
            </span>
          )}
        </div>
      </div>

      <div className="space-y-3 max-h-64 overflow-y-auto">
        {secrets.length === 0 ? (
          <div className="text-center py-8">
            <CheckCircle className="mx-auto text-green-600 mb-2" size={32} />
            <p className="text-sm text-gray-600">All secrets are healthy</p>
          </div>
        ) : (
          secrets.map((secret, idx) => (
            <div
              key={idx}
              className="p-3 rounded-lg border border-gray-200 hover:border-gray-300 transition-colors cursor-pointer"
              onClick={() => onSecretClick?.(secret.path)}
            >
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <p className="font-medium text-gray-900 text-sm">{secret.path}</p>
                  <p className="text-xs text-gray-500 mt-1">Domain: {secret.domain}</p>
                </div>
                <div className="flex items-center gap-3 ml-4">
                  <div className="text-right">
                    <p className="font-semibold text-sm text-gray-900">
                      {secret.daysRemaining === 0
                        ? 'Expires Today'
                        : secret.daysRemaining === 1
                        ? 'Expires Tomorrow'
                        : `${secret.daysRemaining} days`}
                    </p>
                  </div>
                  <SeverityBadge severity={secret.severity} />
                </div>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
};

/**
 * Failed Access Attempts Card
 */
const FailedAccessesCard: React.FC<{ accesses: FailedAccess[] }> = ({ accesses }) => {
  const recentAccesses = accesses.slice(0, 5);

  return (
    <div className="bg-white rounded-lg border border-gray-200 p-6 shadow-sm">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-gray-900">Failed Access Attempts</h3>
        {accesses.length > 0 && (
          <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-800">
            <XCircle size={14} className="mr-1" />
            {accesses.length} in last 24h
          </span>
        )}
      </div>

      <div className="space-y-3 max-h-64 overflow-y-auto">
        {accesses.length === 0 ? (
          <div className="text-center py-8">
            <Shield className="mx-auto text-green-600 mb-2" size={32} />
            <p className="text-sm text-gray-600">No failed access attempts</p>
          </div>
        ) : (
          recentAccesses.map((access, idx) => (
            <div key={idx} className="p-3 rounded-lg border border-red-200 bg-red-50">
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <p className="font-medium text-gray-900 text-sm">
                    {access.user} attempted access
                  </p>
                  <p className="text-xs text-gray-600 mt-1">
                    Secret: {access.secretPath}
                  </p>
                  <p className="text-xs text-red-700 mt-1">Reason: {access.reason}</p>
                  <p className="text-xs text-gray-500 mt-1">
                    {new Date(access.timestamp).toLocaleString()}
                  </p>
                </div>
                <span className="text-xs bg-red-100 text-red-800 px-2 py-1 rounded whitespace-nowrap ml-2">
                  {access.workspace}
                </span>
              </div>
            </div>
          ))
        )}
        {accesses.length > 5 && (
          <div className="text-center pt-2">
            <a href="#" className="text-xs text-blue-600 hover:text-blue-800">
              View all {accesses.length} attempts
            </a>
          </div>
        )}
      </div>
    </div>
  );
};

/**
 * Rotation Compliance Card
 */
const RotationComplianceCard: React.FC<{ metrics: RotationMetrics }> = ({ metrics }) => {
  const complianceColor =
    metrics.complianceRate >= 90
      ? 'text-green-600'
      : metrics.complianceRate >= 70
      ? 'text-yellow-600'
      : 'text-red-600';

  const complianceBg =
    metrics.complianceRate >= 90
      ? 'bg-green-50'
      : metrics.complianceRate >= 70
      ? 'bg-yellow-50'
      : 'bg-red-50';

  return (
    <div className="bg-white rounded-lg border border-gray-200 p-6 shadow-sm">
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-lg font-semibold text-gray-900">Rotation Compliance</h3>
        <div className={`text-right p-4 rounded-lg ${complianceBg}`}>
          <p className={`text-3xl font-bold ${complianceColor}`}>
            {metrics.complianceRate}%
          </p>
          <p className="text-xs text-gray-600">Compliant</p>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div className="p-3 bg-green-50 rounded-lg border border-green-200">
          <div className="flex items-center mb-1">
            <CheckCircle size={16} className="text-green-600 mr-2" />
            <p className="text-sm font-medium text-gray-900">Completed</p>
          </div>
          <p className="text-2xl font-bold text-green-600">{metrics.completed}</p>
          <p className="text-xs text-gray-600 mt-1">
            of {metrics.total} rotations
          </p>
        </div>

        <div className="p-3 bg-yellow-50 rounded-lg border border-yellow-200">
          <div className="flex items-center mb-1">
            <Clock size={16} className="text-yellow-600 mr-2" />
            <p className="text-sm font-medium text-gray-900">Pending</p>
          </div>
          <p className="text-2xl font-bold text-yellow-600">{metrics.pending}</p>
          <p className="text-xs text-gray-600 mt-1">Due for rotation</p>
        </div>

        <div className="p-3 bg-red-50 rounded-lg border border-red-200">
          <div className="flex items-center mb-1">
            <XCircle size={16} className="text-red-600 mr-2" />
            <p className="text-sm font-medium text-gray-900">Failed</p>
          </div>
          <p className="text-2xl font-bold text-red-600">{metrics.failed}</p>
          <p className="text-xs text-gray-600 mt-1">Rotation failures</p>
        </div>

        <div className="p-3 bg-gray-50 rounded-lg border border-gray-200">
          <div className="flex items-center mb-1">
            <Zap size={16} className="text-gray-600 mr-2" />
            <p className="text-sm font-medium text-gray-900">Disabled</p>
          </div>
          <p className="text-2xl font-bold text-gray-600">{metrics.disabled}</p>
          <p className="text-xs text-gray-600 mt-1">Auto-rotation disabled</p>
        </div>
      </div>
    </div>
  );
};

/**
 * Secrets Overview Card
 */
const SecretsOverviewCard: React.FC<{
  total: number;
  temporal: number;
  permanent: number;
}> = ({ total, temporal, permanent }) => {
  return (
    <div className="bg-white rounded-lg border border-gray-200 p-6 shadow-sm">
      <h3 className="text-lg font-semibold text-gray-900 mb-4">Secrets Overview</h3>

      <div className="space-y-4">
        <div>
          <div className="flex items-center justify-between mb-2">
            <p className="text-sm font-medium text-gray-700">Total Secrets</p>
            <p className="text-2xl font-bold text-gray-900">{total}</p>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div className="bg-blue-600 h-2 rounded-full" style={{ width: '100%' }} />
          </div>
        </div>

        <div>
          <div className="flex items-center justify-between mb-2">
            <p className="text-sm font-medium text-gray-700">Temporal Secrets</p>
            <p className="text-lg font-semibold text-yellow-600">{temporal}</p>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div
              className="bg-yellow-600 h-2 rounded-full"
              style={{ width: `${total > 0 ? (temporal / total) * 100 : 0}%` }}
            />
          </div>
          <p className="text-xs text-gray-600 mt-1">
            {total > 0 ? ((temporal / total) * 100).toFixed(1) : 0}% of total
          </p>
        </div>

        <div>
          <div className="flex items-center justify-between mb-2">
            <p className="text-sm font-medium text-gray-700">Permanent Secrets</p>
            <p className="text-lg font-semibold text-green-600">{permanent}</p>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div
              className="bg-green-600 h-2 rounded-full"
              style={{ width: `${total > 0 ? (permanent / total) * 100 : 0}%` }}
            />
          </div>
          <p className="text-xs text-gray-600 mt-1">
            {total > 0 ? ((permanent / total) * 100).toFixed(1) : 0}% of total
          </p>
        </div>
      </div>
    </div>
  );
};

/**
 * Sharing Metrics Card
 */
const SharingMetricsCard: React.FC<{ metrics: SharingMetrics }> = ({ metrics }) => {
  const successRate =
    metrics.totalAccesses > 0
      ? (((metrics.totalAccesses - metrics.failedAccesses) / metrics.totalAccesses) * 100).toFixed(1)
      : '0';

  return (
    <div className="bg-white rounded-lg border border-gray-200 p-6 shadow-sm">
      <h3 className="text-lg font-semibold text-gray-900 mb-4">Sharing Metrics</h3>

      <div className="grid grid-cols-2 gap-4 mb-4">
        <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
          <p className="text-sm text-gray-600 mb-1">Active Grants</p>
          <p className="text-2xl font-bold text-blue-600">{metrics.activeGrants}</p>
        </div>

        <div className="p-3 bg-yellow-50 rounded-lg border border-yellow-200">
          <p className="text-sm text-gray-600 mb-1">Pending Approval</p>
          <p className="text-2xl font-bold text-yellow-600">{metrics.pendingGrants}</p>
        </div>

        <div className="p-3 bg-red-50 rounded-lg border border-red-200">
          <p className="text-sm text-gray-600 mb-1">Revoked</p>
          <p className="text-2xl font-bold text-red-600">{metrics.revokedGrants}</p>
        </div>

        <div className="p-3 bg-green-50 rounded-lg border border-green-200">
          <p className="text-sm text-gray-600 mb-1">Success Rate</p>
          <p className="text-2xl font-bold text-green-600">{successRate}%</p>
        </div>
      </div>

      <div>
        <p className="text-sm font-medium text-gray-900 mb-2">Total Accesses</p>
        <div className="space-y-2">
          <div className="flex justify-between items-center text-sm">
            <span className="text-gray-600">Successful: {metrics.totalAccesses - metrics.failedAccesses}</span>
          </div>
          <div
            className="w-full bg-gray-200 rounded-full h-2"
            style={{
              background: `linear-gradient(to right, #10b981 ${successRate}%, #ef4444 ${successRate}%)`,
            }}
          />
          <div className="flex justify-between items-center text-sm">
            <span className="text-gray-600">Failed: {metrics.failedAccesses}</span>
          </div>
        </div>
      </div>
    </div>
  );
};

/**
 * Main Monitoring Dashboard Component
 */
export const MonitoringDashboard: React.FC<MonitoringDashboardProps> = ({
  metrics,
  onSecretClick,
  onApproveAccess,
  onDenyAccess,
}) => {
  return (
    <div className="bg-gray-50 p-6 rounded-lg">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900">Secrets Monitoring</h1>
        <p className="text-gray-600 mt-2">
          Real-time monitoring of secret health, rotation compliance, and access patterns
        </p>
        <p className="text-xs text-gray-500 mt-2">
          Last updated: {new Date(metrics.lastUpdated).toLocaleString()}
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <ExpiringSecretsCard secrets={metrics.expiringSecrets} onSecretClick={onSecretClick} />
        <FailedAccessesCard accesses={metrics.failedAccessAttempts} />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <RotationComplianceCard metrics={metrics.rotationMetrics} />
        <SecretsOverviewCard
          total={metrics.totalSecrets}
          temporal={metrics.temporalSecrets}
          permanent={metrics.permanentSecrets}
        />
        <SharingMetricsCard metrics={metrics.sharingMetrics} />
      </div>
    </div>
  );
};

export default MonitoringDashboard;
