/**
 * SystemStatusBlock - Block 1: "Estado del Sistema"
 *
 * Displays system status including:
 * - Issues requiring user action
 * - Issues prevented by AI
 * - Last intelligent system run timestamp
 * - AI handling rate and savings
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Activity,
  AlertTriangle,
  Bot,
  CheckCircle2,
  ChevronDown,
  ChevronUp,
  Clock,
  Sparkles,
  TrendingUp,
} from 'lucide-react';
import type { DashboardData, OrchestrationSummary } from '../../../api/hooks/useDashboardData';

interface SystemStatusBlockProps {
  data: DashboardData | undefined;
  loading?: boolean;
}

export function SystemStatusBlock({ data, loading }: SystemStatusBlockProps) {
  const { t } = useTranslation(['dashboard', 'common']);
  const [isExpanded, setIsExpanded] = useState(false);

  if (loading) {
    return (
      <div className="rounded-xl shadow-lg p-6 border border-[var(--border-primary)] bg-[var(--bg-primary)] animate-pulse">
        <div className="flex items-center gap-4">
          <div className="w-16 h-16 bg-[var(--bg-secondary)] rounded-full"></div>
          <div className="flex-1 space-y-3">
            <div className="h-6 bg-[var(--bg-secondary)] rounded w-1/3"></div>
            <div className="h-4 bg-[var(--bg-secondary)] rounded w-1/2"></div>
          </div>
        </div>
      </div>
    );
  }

  const issuesRequiringAction = data?.issuesRequiringAction || 0;
  const issuesPreventedByAI = data?.issuesPreventedByAI || 0;
  const orchestrationSummary = data?.orchestrationSummary;
  const preventedIssues = data?.preventedIssues || [];

  // Determine status: green if no issues, yellow/red if issues exist
  const hasIssues = issuesRequiringAction > 0;
  const status = hasIssues ? 'warning' : 'success';

  // Format last run time
  const formatLastRun = (timestamp: string | null | undefined) => {
    if (!timestamp) return t('dashboard:new_dashboard.system_status.never_run');

    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffMinutes = Math.floor(diffMs / (1000 * 60));

    if (diffMinutes < 1) return t('common:time.just_now', 'Just now');
    if (diffMinutes < 60) return t('common:time.minutes_ago', '{{count}} min ago', { count: diffMinutes });
    if (diffHours < 24) return t('common:time.hours_ago', '{{count}}h ago', { count: diffHours });

    return date.toLocaleDateString();
  };

  // Status styling
  const statusStyles = {
    success: {
      bg: 'bg-[var(--color-success-50)]',
      border: 'border-[var(--color-success-200)]',
      iconBg: 'bg-[var(--color-success-100)]',
      iconColor: 'text-[var(--color-success-600)]',
    },
    warning: {
      bg: 'bg-[var(--color-warning-50)]',
      border: 'border-[var(--color-warning-200)]',
      iconBg: 'bg-[var(--color-warning-100)]',
      iconColor: 'text-[var(--color-warning-600)]',
    },
  };

  const styles = statusStyles[status];

  return (
    <div className={`rounded-xl shadow-lg border ${styles.border} ${styles.bg} overflow-hidden`}>
      {/* Main Content */}
      <div className="p-6">
        <div className="flex items-start gap-4">
          {/* Status Icon */}
          <div className={`w-16 h-16 rounded-full ${styles.iconBg} flex items-center justify-center flex-shrink-0`}>
            {hasIssues ? (
              <AlertTriangle className={`w-8 h-8 ${styles.iconColor}`} />
            ) : (
              <CheckCircle2 className={`w-8 h-8 ${styles.iconColor}`} />
            )}
          </div>

          {/* Content */}
          <div className="flex-1 min-w-0">
            {/* Title */}
            <h2 className="text-xl font-bold text-[var(--text-primary)] mb-1">
              {t('dashboard:new_dashboard.system_status.title')}
            </h2>

            {/* Status Message */}
            <p className="text-[var(--text-secondary)] mb-4">
              {hasIssues
                ? t('dashboard:new_dashboard.system_status.issues_requiring_action', {
                    count: issuesRequiringAction,
                  })
                : t('dashboard:new_dashboard.system_status.all_clear')}
            </p>

            {/* Stats Row */}
            <div className="flex flex-wrap gap-4">
              {/* Issues Requiring Action */}
              <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-[var(--bg-primary)] border border-[var(--border-primary)]">
                <AlertTriangle
                  className={`w-5 h-5 ${
                    issuesRequiringAction > 0 ? 'text-[var(--color-warning-500)]' : 'text-[var(--text-tertiary)]'
                  }`}
                />
                <span className="text-sm font-medium text-[var(--text-primary)]">
                  {issuesRequiringAction}
                </span>
                <span className="text-sm text-[var(--text-secondary)]">
                  {t('dashboard:new_dashboard.system_status.action_needed_label')}
                </span>
              </div>

              {/* Issues Prevented by AI */}
              <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-[var(--bg-primary)] border border-[var(--border-primary)]">
                <Bot className="w-5 h-5 text-[var(--color-primary)]" />
                <span className="text-sm font-medium text-[var(--text-primary)]">
                  {issuesPreventedByAI}
                </span>
                <span className="text-sm text-[var(--text-secondary)]">
                  {t('dashboard:new_dashboard.system_status.ai_prevented_label')}
                </span>
              </div>

              {/* Last Run */}
              <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-[var(--bg-primary)] border border-[var(--border-primary)]">
                <Clock className="w-5 h-5 text-[var(--text-tertiary)]" />
                <span className="text-sm text-[var(--text-secondary)]">
                  {t('dashboard:new_dashboard.system_status.last_run_label')}:
                </span>
                <span className="text-sm font-medium text-[var(--text-primary)]">
                  {formatLastRun(orchestrationSummary?.runTimestamp)}
                </span>
              </div>
            </div>
          </div>

          {/* Expand Button (if there are prevented issues to show) */}
          {issuesPreventedByAI > 0 && (
            <button
              onClick={() => setIsExpanded(!isExpanded)}
              className="p-2 rounded-lg hover:bg-[var(--bg-secondary)] transition-colors"
              aria-label={isExpanded ? 'Collapse' : 'Expand'}
            >
              {isExpanded ? (
                <ChevronUp className="w-5 h-5 text-[var(--text-tertiary)]" />
              ) : (
                <ChevronDown className="w-5 h-5 text-[var(--text-tertiary)]" />
              )}
            </button>
          )}
        </div>
      </div>

      {/* Expanded AI Details Section */}
      {isExpanded && issuesPreventedByAI > 0 && (
        <div className="border-t border-[var(--border-primary)] bg-[var(--bg-primary)] p-6">
          <h3 className="text-sm font-semibold text-[var(--text-primary)] mb-4 flex items-center gap-2">
            <Sparkles className="w-4 h-4 text-[var(--color-primary)]" />
            {t('dashboard:new_dashboard.system_status.ai_prevented_details')}
          </h3>

          {/* AI Stats */}
          {orchestrationSummary && (
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-4">
              {orchestrationSummary.aiHandlingRate !== undefined && (
                <div className="p-3 rounded-lg bg-[var(--bg-secondary)]">
                  <div className="flex items-center gap-2 text-sm text-[var(--text-secondary)] mb-1">
                    <Activity className="w-4 h-4" />
                    {t('dashboard:new_dashboard.system_status.ai_handling_rate')}
                  </div>
                  <div className="text-xl font-bold text-[var(--color-primary)]">
                    {Math.round(orchestrationSummary.aiHandlingRate)}%
                  </div>
                </div>
              )}

              {orchestrationSummary.estimatedSavingsEur !== undefined && orchestrationSummary.estimatedSavingsEur > 0 && (
                <div className="p-3 rounded-lg bg-[var(--bg-secondary)]">
                  <div className="flex items-center gap-2 text-sm text-[var(--text-secondary)] mb-1">
                    <TrendingUp className="w-4 h-4" />
                    {t('dashboard:new_dashboard.system_status.estimated_savings')}
                  </div>
                  <div className="text-xl font-bold text-[var(--color-success-600)]">
                    €{orchestrationSummary.estimatedSavingsEur.toLocaleString()}
                  </div>
                </div>
              )}

              <div className="p-3 rounded-lg bg-[var(--bg-secondary)]">
                <div className="flex items-center gap-2 text-sm text-[var(--text-secondary)] mb-1">
                  <Bot className="w-4 h-4" />
                  {t('dashboard:new_dashboard.system_status.issues_prevented')}
                </div>
                <div className="text-xl font-bold text-[var(--color-primary)]">
                  {issuesPreventedByAI}
                </div>
              </div>
            </div>
          )}

          {/* Prevented Issues List */}
          {preventedIssues.length > 0 && (
            <div className="space-y-2">
              {preventedIssues.slice(0, 5).map((issue: any, index: number) => (
                <div
                  key={issue.id || index}
                  className="flex items-center gap-3 p-3 rounded-lg bg-[var(--bg-secondary)] border border-[var(--border-primary)]"
                >
                  <CheckCircle2 className="w-5 h-5 text-[var(--color-success-500)] flex-shrink-0" />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-[var(--text-primary)] truncate">
                      {issue.title || issue.message || t('dashboard:new_dashboard.system_status.issue_prevented')}
                    </p>
                    {issue.business_impact?.financial_impact_eur && (
                      <p className="text-xs text-[var(--text-secondary)]">
                        {t('dashboard:new_dashboard.system_status.saved')}: €{issue.business_impact.financial_impact_eur.toLocaleString()}
                      </p>
                    )}
                  </div>
                </div>
              ))}

              {preventedIssues.length > 5 && (
                <p className="text-sm text-[var(--text-secondary)] text-center py-2">
                  {t('dashboard:new_dashboard.system_status.and_more', {
                    count: preventedIssues.length - 5,
                  })}
                </p>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default SystemStatusBlock;
