'use client';

/**
 * Asset Alerts Section - EE Component
 *
 * Displays active RMM alerts for an asset with actions to acknowledge
 * or create tickets from alerts.
 */

import React, { useState, useEffect } from 'react';
import { AlertTriangle, Check, ExternalLink, Ticket, ChevronDown, ChevronUp, RefreshCw } from 'lucide-react';
import { Button } from '@alga-psa/ui/components/Button';
import type { Asset } from '@/interfaces/asset.interfaces';
import type { RmmAlert } from '../../interfaces/rmm.interfaces';
import { getAssetAlerts, acknowledgeRmmAlert, createTicketFromRmmAlert } from '../../lib/actions/integrations/ninjaoneActions';
import { toast } from 'react-hot-toast';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';

interface AssetAlertsSectionProps {
  asset: Asset;
  className?: string;
}

/**
 * Format relative time from ISO string
 */
function formatRelativeTime(isoString: string): string {
  const date = new Date(isoString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMinutes = Math.floor(diffMs / (1000 * 60));
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

  if (diffMinutes < 1) {
    return 'Just now';
  } else if (diffMinutes < 60) {
    return `${diffMinutes}m ago`;
  } else if (diffHours < 24) {
    return `${diffHours}h ago`;
  } else if (diffDays < 7) {
    return `${diffDays}d ago`;
  } else {
    return date.toLocaleDateString();
  }
}

/**
 * Get severity color classes
 */
function getSeverityClasses(severity: string): string {
  switch (severity?.toUpperCase()) {
    case 'CRITICAL':
      return 'bg-red-500/15 text-red-600 border-red-500/30';
    case 'MAJOR':
      return 'bg-orange-500/15 text-orange-600 border-orange-500/30';
    case 'MODERATE':
      return 'bg-yellow-500/15 text-yellow-600 border-yellow-500/30';
    case 'MINOR':
      return 'bg-blue-500/15 text-blue-600 border-blue-500/30';
    default:
      return 'bg-gray-500/15 text-gray-600 border-gray-500/30';
  }
}

/**
 * Asset Alerts Section
 */
export function AssetAlertsSection({ asset, className = '' }: AssetAlertsSectionProps) {
  const { t } = useTranslation('msp/assets');
  const [alerts, setAlerts] = useState<RmmAlert[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isExpanded, setIsExpanded] = useState(true);
  const [processingAlertId, setProcessingAlertId] = useState<string | null>(null);

  const loadAlerts = React.useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await getAssetAlerts(asset.asset_id);
      if (result.success && result.alerts) {
        setAlerts(result.alerts);
      }
    } catch (error) {
      console.error('Failed to load alerts:', error);
    } finally {
      setIsLoading(false);
    }
  }, [asset.asset_id]);

  // Fetch alerts on mount - must be called before any early returns
  useEffect(() => {
    if (!asset.rmm_provider || !asset.rmm_device_id) {
      return;
    }
    loadAlerts();
  }, [asset.asset_id, asset.rmm_provider, asset.rmm_device_id, loadAlerts]);

  // Don't render if not RMM managed
  if (!asset.rmm_provider || !asset.rmm_device_id) {
    return null;
  }

  const handleAcknowledge = async (alertId: string) => {
    setProcessingAlertId(alertId);
    try {
      const result = await acknowledgeRmmAlert(alertId);
      if (result.success) {
        toast.success(t('alerts.messages.alertAcknowledged'));
        // Update local state
        setAlerts(prev => prev.map(a =>
          a.alert_id === alertId
            ? { ...a, status: 'acknowledged', acknowledged_at: new Date().toISOString() }
            : a
        ));
      } else {
        toast.error(result.error || t('alerts.messages.acknowledgeFailed'));
      }
    } catch (error) {
      toast.error(t('alerts.messages.acknowledgeFailed'));
    } finally {
      setProcessingAlertId(null);
    }
  };

  const handleCreateTicket = async (alertId: string) => {
    setProcessingAlertId(alertId);
    try {
      const result = await createTicketFromRmmAlert(alertId);
      if (result.success && result.ticketId) {
        toast.success(t('alerts.messages.ticketCreated'));
        // Update local state
        setAlerts(prev => prev.map(a =>
          a.alert_id === alertId
            ? { ...a, ticket_id: result.ticketId }
            : a
        ));
      } else {
        toast.error(result.error || t('alerts.messages.ticketCreateFailed'));
      }
    } catch (error) {
      toast.error(t('alerts.messages.ticketCreateFailed'));
    } finally {
      setProcessingAlertId(null);
    }
  };

  const activeAlerts = alerts.filter(a => a.status === 'active' || a.status === 'acknowledged');
  const hasAlerts = activeAlerts.length > 0;

  return (
    <div className={`bg-white rounded-lg border border-gray-200 ${className}`}>
      {/* Header */}
      <div
        role="button"
        tabIndex={0}
        className="w-full flex items-center justify-between p-4 text-left hover:bg-gray-50 cursor-pointer"
        onClick={() => setIsExpanded(!isExpanded)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            setIsExpanded(!isExpanded);
          }
        }}
      >
        <div className="flex items-center gap-2">
          <AlertTriangle className={`h-5 w-5 ${hasAlerts ? 'text-amber-500' : 'text-gray-400'}`} />
          <span className="font-medium">{t('alerts.activeAlerts')}</span>
          {hasAlerts && (
            <span className="inline-flex items-center justify-center px-2 py-0.5 text-xs font-medium rounded-full bg-warning/15 text-warning-foreground">
              {activeAlerts.length}
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          <Button
            id="refresh-alerts-btn"
            variant="ghost"
            size="sm"
            onClick={(e) => {
              e.stopPropagation();
              loadAlerts();
            }}
            disabled={isLoading}
          >
            <RefreshCw className={`h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
          </Button>
          {isExpanded ? (
            <ChevronUp className="h-4 w-4 text-gray-400" />
          ) : (
            <ChevronDown className="h-4 w-4 text-gray-400" />
          )}
        </div>
      </div>

      {/* Content */}
      {isExpanded && (
        <div className="border-t border-gray-200">
          {isLoading && alerts.length === 0 ? (
            <div className="p-4 text-center text-gray-500">
              <RefreshCw className="h-5 w-5 animate-spin mx-auto mb-2" />
              Loading alerts...
            </div>
          ) : !hasAlerts ? (
            <div className="p-4 text-center text-gray-500">
              <Check className="h-5 w-5 mx-auto mb-2 text-green-500" />
              No active alerts
            </div>
          ) : (
            <div className="divide-y divide-gray-100">
              {activeAlerts.map((alert) => (
                <div key={alert.alert_id} className="p-4">
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <span className={`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded border ${getSeverityClasses(alert.severity)}`}>
                          {alert.severity}
                        </span>
                        {alert.status === 'acknowledged' && (
                          <span className="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded bg-gray-100 text-gray-600">
                            Acknowledged
                          </span>
                        )}
                        {alert.ticket_id && (
                          <span className="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded bg-purple-100 text-purple-600">
                            <Ticket className="h-3 w-3 mr-1" />
                            Ticket Created
                          </span>
                        )}
                      </div>
                      <p className="text-sm font-medium text-gray-900 truncate">
                        {alert.activity_type?.replace(/_/g, ' ')}
                      </p>
                      {alert.message && (
                        <p className="text-sm text-gray-600 mt-1 line-clamp-2">
                          {alert.message}
                        </p>
                      )}
                      <p className="text-xs text-gray-400 mt-1">
                        {formatRelativeTime(alert.triggered_at)}
                      </p>
                    </div>
                    <div className="flex items-center gap-1">
                      {alert.status !== 'acknowledged' && (
                        <Button
                          id={`acknowledge-alert-${alert.alert_id}`}
                          variant="ghost"
                          size="sm"
                          onClick={() => handleAcknowledge(alert.alert_id)}
                          disabled={processingAlertId === alert.alert_id}
                          title={t('alerts.acknowledge')}
                        >
                          <Check className="h-4 w-4" />
                        </Button>
                      )}
                      {!alert.ticket_id && (
                        <Button
                          id={`create-ticket-from-alert-${alert.alert_id}`}
                          variant="ghost"
                          size="sm"
                          onClick={() => handleCreateTicket(alert.alert_id)}
                          disabled={processingAlertId === alert.alert_id}
                          title={t('alerts.createTicket')}
                        >
                          <Ticket className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default AssetAlertsSection;
