// ================================================================
// frontend/src/components/domain/dashboard/AutoActionCountdownComponent.tsx
// ================================================================
/**
 * Auto Action Countdown Component
 *
 * Displays countdown timer for ESCALATION type alerts where AI will
 * automatically take action unless user intervenes.
 *
 * Design Philosophy:
 * - High urgency visual design
 * - Clear countdown timer
 * - One-click cancel button
 * - Shows what action will be taken
 */

import React, { useState, useEffect } from 'react';
import { AlertTriangle, Clock, XCircle, CheckCircle } from 'lucide-react';
import { Button } from '../../ui/Button';
import { Badge } from '../../ui/Badge';
import { useTranslation } from 'react-i18next';
import { useTenantCurrency } from '../../../hooks/useTenantCurrency';

export interface AutoActionCountdownProps {
  actionDescription: string;
  countdownSeconds: number;
  onCancel: () => Promise<void>;
  financialImpactEur?: number;
  alertId: string;
  className?: string;
}

export function AutoActionCountdownComponent({
  actionDescription,
  countdownSeconds,
  onCancel,
  financialImpactEur,
  alertId,
  className = '',
}: AutoActionCountdownProps) {
  const { t } = useTranslation('alerts');
  const { currencySymbol } = useTenantCurrency();
  const [timeRemaining, setTimeRemaining] = useState(countdownSeconds);
  const [isCancelling, setIsCancelling] = useState(false);
  const [isCancelled, setIsCancelled] = useState(false);

  useEffect(() => {
    if (timeRemaining <= 0 || isCancelled) return;

    const timer = setInterval(() => {
      setTimeRemaining((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [timeRemaining, isCancelled]);

  const handleCancel = async () => {
    setIsCancelling(true);
    try {
      await onCancel();
      setIsCancelled(true);
    } catch (error) {
      console.error('Failed to cancel auto-action:', error);
    } finally {
      setIsCancelling(false);
    }
  };

  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const getUrgencyLevel = (seconds: number): 'critical' | 'warning' | 'info' => {
    if (seconds <= 60) return 'critical';
    if (seconds <= 300) return 'warning';
    return 'info';
  };

  const urgency = getUrgencyLevel(timeRemaining);
  const progressPercentage = ((countdownSeconds - timeRemaining) / countdownSeconds) * 100;

  // Cancelled state
  if (isCancelled) {
    return (
      <div
        className={`rounded-lg p-4 border ${className}`}
        style={{
          backgroundColor: 'var(--color-success-50)',
          borderColor: 'var(--color-success-300)',
        }}
      >
        <div className="flex items-center gap-3">
          <CheckCircle className="w-6 h-6 flex-shrink-0" style={{ color: 'var(--color-success-600)' }} />
          <div className="flex-1">
            <h4 className="font-semibold" style={{ color: 'var(--color-success-700)' }}>
              {t('auto_action.cancelled_title', 'Auto-action Cancelled')}
            </h4>
            <p className="text-sm mt-1" style={{ color: 'var(--color-success-600)' }}>
              {t('auto_action.cancelled_message', 'The automatic action has been prevented. You can now handle this manually.')}
            </p>
          </div>
        </div>
      </div>
    );
  }

  // Action completed (countdown reached 0)
  if (timeRemaining <= 0) {
    return (
      <div
        className={`rounded-lg p-4 border ${className}`}
        style={{
          backgroundColor: 'var(--bg-secondary)',
          borderColor: 'var(--border-primary)',
        }}
      >
        <div className="flex items-center gap-3">
          <Clock className="w-6 h-6 flex-shrink-0" style={{ color: 'var(--text-tertiary)' }} />
          <div className="flex-1">
            <h4 className="font-semibold" style={{ color: 'var(--text-primary)' }}>
              {t('auto_action.completed_title', 'Auto-action Executed')}
            </h4>
            <p className="text-sm mt-1" style={{ color: 'var(--text-secondary)' }}>
              {actionDescription}
            </p>
          </div>
        </div>
      </div>
    );
  }

  // Active countdown
  return (
    <div
      className={`rounded-lg p-4 border-2 shadow-lg ${className}`}
      style={{
        backgroundColor:
          urgency === 'critical'
            ? 'var(--color-error-50)'
            : urgency === 'warning'
            ? 'var(--color-warning-50)'
            : 'var(--color-info-50)',
        borderColor:
          urgency === 'critical'
            ? 'var(--color-error-400)'
            : urgency === 'warning'
            ? 'var(--color-warning-400)'
            : 'var(--color-info-400)',
      }}
    >
      {/* Header */}
      <div className="flex items-start justify-between gap-3 mb-3">
        <div className="flex items-center gap-3 flex-1">
          <div
            className={`p-2 rounded-full ${
              urgency === 'critical' ? 'animate-pulse' : ''
            }`}
            style={{
              backgroundColor:
                urgency === 'critical'
                  ? 'var(--color-error-100)'
                  : urgency === 'warning'
                  ? 'var(--color-warning-100)'
                  : 'var(--color-info-100)',
            }}
          >
            <AlertTriangle
              className="w-5 h-5"
              style={{
                color:
                  urgency === 'critical'
                    ? 'var(--color-error-600)'
                    : urgency === 'warning'
                    ? 'var(--color-warning-600)'
                    : 'var(--color-info-600)',
              }}
            />
          </div>
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-1">
              <h4 className="font-bold" style={{ color: 'var(--text-primary)' }}>
                {t('auto_action.title', 'Auto-action Pending')}
              </h4>
              <Badge
                variant={urgency === 'critical' ? 'error' : urgency === 'warning' ? 'warning' : 'info'}
                size="sm"
              >
                {urgency === 'critical'
                  ? t('auto_action.urgency.critical', 'URGENT')
                  : urgency === 'warning'
                  ? t('auto_action.urgency.warning', 'SOON')
                  : t('auto_action.urgency.info', 'SCHEDULED')}
              </Badge>
            </div>
            <p className="text-sm font-medium" style={{ color: 'var(--text-secondary)' }}>
              {actionDescription}
            </p>
          </div>
        </div>

        {/* Countdown Timer */}
        <div className="text-center flex-shrink-0">
          <div
            className="text-2xl font-bold tabular-nums"
            style={{
              color:
                urgency === 'critical'
                  ? 'var(--color-error-600)'
                  : urgency === 'warning'
                  ? 'var(--color-warning-600)'
                  : 'var(--color-info-600)',
            }}
          >
            {formatTime(timeRemaining)}
          </div>
          <div className="text-xs font-medium" style={{ color: 'var(--text-tertiary)' }}>
            {t('auto_action.remaining', 'remaining')}
          </div>
        </div>
      </div>

      {/* Progress Bar */}
      <div className="mb-3 rounded-full overflow-hidden" style={{ backgroundColor: 'var(--bg-tertiary)', height: '6px' }}>
        <div
          className="h-full transition-all duration-1000 ease-linear"
          style={{
            width: `${progressPercentage}%`,
            backgroundColor:
              urgency === 'critical'
                ? 'var(--color-error-500)'
                : urgency === 'warning'
                ? 'var(--color-warning-500)'
                : 'var(--color-info-500)',
          }}
        />
      </div>

      {/* Financial Impact & Cancel Button */}
      <div className="flex items-center justify-between gap-3">
        {financialImpactEur !== undefined && financialImpactEur > 0 && (
          <div className="text-sm">
            <span className="font-medium" style={{ color: 'var(--text-secondary)' }}>
              {t('auto_action.financial_impact', 'Impact:')}
            </span>{' '}
            <span className="font-bold" style={{ color: 'var(--text-primary)' }}>
              {currencySymbol}{financialImpactEur.toFixed(2)}
            </span>
          </div>
        )}

        <Button
          variant="outline"
          size="sm"
          onClick={handleCancel}
          disabled={isCancelling}
          className="ml-auto bg-white/80 hover:bg-white flex items-center gap-2"
        >
          <XCircle className="w-4 h-4" />
          {isCancelling
            ? t('auto_action.cancelling', 'Cancelling...')
            : t('auto_action.cancel_button', 'Cancel Auto-action')}
        </Button>
      </div>

      {/* Help Text */}
      <div
        className="mt-3 text-xs p-2 rounded"
        style={{
          backgroundColor: 'var(--bg-primary)',
          color: 'var(--text-tertiary)',
        }}
      >
        {t(
          'auto_action.help_text',
          'AI will automatically execute this action when the timer expires. Click "Cancel" to prevent it and handle manually.'
        )}
      </div>
    </div>
  );
}
