import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { RefreshCw, Database, Zap, Info, AlertCircle, CheckCircle, Clock } from 'lucide-react';
import { api } from '../../services/api';
import toast from 'react-hot-toast';
import LoadingSpinner from '../ui/LoadingSpinner';
import PerformanceIndicator from '../ui/PerformanceIndicator';
import LicenseManager from '../license/LicenseManager';

interface CacheStats {
  cache: {
    table_exists: boolean;
    row_count: number;
    table_size_mb: number;
    index_count: number;
    last_sync: string | null;
  };
  health: {
    status: 'HEALTHY' | 'WARNING' | 'CRITICAL';
    cache_count: number;
    actual_count: number;
    missing_count: number;
    orphaned_count: number;
  };
  sync: {
    is_running: boolean;
    processed: number;
    total: number;
    last_error: string | null;
  };
  performance: {
    avg_query_time_ms: number;
    cache_hit_rate: number;
    variations_per_second: number;
  };
  system: {
    wordpress_version: string;
    woocommerce_version: string;
    php_version: string;
    php_memory_limit: string;
    mysql_version: string;
    table_engine: string;
  };
}

export default function SettingsTab() {
  const { t, i18n } = useTranslation();
  const [stats, setStats] = useState<CacheStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [resyncing, setResyncing] = useState(false);
  const [testing, setTesting] = useState(false);

  useEffect(() => {
    loadStats();
  }, []);

  const loadStats = async () => {
    try {
      setLoading(true);
      const response = await api.get('/cache/stats');
      setStats(response.data.data);
    } catch (error) {
      toast.error(t('settings_load_failed'));
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleResync = async () => {
    if (!confirm(t('settings_confirm_resync'))) {
      return;
    }

    try {
      setResyncing(true);
      const response = await api.post('/cache/resync');
      toast.success(response.data.message);
      
      // Reload stats after 3 seconds
      setTimeout(() => {
        loadStats();
      }, 3000);
    } catch (error: any) {
      toast.error(error.response?.data?.message || t('settings_resync_failed'));
      console.error(error);
    } finally {
      setResyncing(false);
    }
  };

  const handlePerformanceTest = async () => {
    try {
      setTesting(true);
      const start = performance.now();
      const response = await api.get('/cache/test');
      const totalTime = performance.now() - start;

      toast.success(
        `Query: ${response.data.data.query_time_ms}ms | Total: ${totalTime.toFixed(2)}ms`,
        { duration: 4000 }
      );
    } catch (error) {
      toast.error(t('settings_test_failed'));
      console.error(error);
    } finally {
      setTesting(false);
    }
  };

  if (loading || !stats) {
    return (
      <div className="flex items-center justify-center h-64">
        <LoadingSpinner size="xl" />
      </div>
    );
  }

  const getHealthColor = (status: string) => {
    switch (status) {
      case 'HEALTHY':
        return 'text-green-600 bg-green-50 border-green-200';
      case 'WARNING':
        return 'text-yellow-600 bg-yellow-50 border-yellow-200';
      case 'CRITICAL':
        return 'text-red-600 bg-red-50 border-red-200';
      default:
        return 'text-gray-600 bg-gray-50 border-gray-200';
    }
  };

  const getHealthIcon = (status: string) => {
    switch (status) {
      case 'HEALTHY':
        return <CheckCircle className="w-5 h-5" />;
      case 'WARNING':
        return <AlertCircle className="w-5 h-5" />;
      case 'CRITICAL':
        return <AlertCircle className="w-5 h-5" />;
      default:
        return <Info className="w-5 h-5" />;
    }
  };

  // Get current locale for number formatting
  const locale = i18n.language === 'hu' ? 'hu-HU' : 'en-US';

  return (
    <div className="p-6 space-y-4 max-h-screen overflow-y-auto">
      {/* Header with Action Buttons */}
      <div className="flex items-center justify-between flex-wrap gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">{t('settings_title')}</h2>
          <p className="text-sm text-gray-600 mt-1">
            {t('settings_description')}
          </p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={handleResync}
            disabled={resyncing || stats.sync.is_running}
            className="flex items-center gap-2 px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-medium"
          >
            <RefreshCw className={`w-4 h-4 ${resyncing ? 'animate-spin' : ''}`} />
            {resyncing ? t('settings_resyncing') : t('settings_resync_cache')}
          </button>

          <button
            onClick={handlePerformanceTest}
            disabled={testing}
            className="flex items-center gap-2 px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-medium"
          >
            <Zap className={`w-4 h-4 ${testing ? 'animate-pulse' : ''}`} />
            {testing ? t('settings_testing') : t('settings_performance_test')}
          </button>
          
          <button
            onClick={loadStats}
            className="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
          >
            <RefreshCw className="w-4 h-4" />
            {t('settings_refresh')}
          </button>
        </div>
      </div>

      {/* Sync Status Banner */}
      {stats.sync.is_running && (
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <div className="flex items-center gap-3">
            <LoadingSpinner size="sm" />
            <div className="flex-1">
              <p className="font-semibold text-blue-900">{t('settings_sync_in_progress')}</p>
              <p className="text-sm text-blue-700 mt-1">
                {t('settings_variations_processed', {
                  processed: (stats.sync.processed || 0).toLocaleString(locale),
                  total: (stats.sync.total || 0).toLocaleString(locale)
                })}
              </p>
            </div>
            <div className="text-2xl font-bold text-blue-600">
              {stats.sync.total > 0 ? Math.round(((stats.sync.processed || 0) / stats.sync.total) * 100) : 0}%
            </div>
          </div>
        </div>
      )}

      {/* Main Layout: 1/2 - 1/2 Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        
        {/* LEFT COLUMN (1/2): System Statistics & Monitoring */}
        <div className="lg:col-span-1 space-y-4">
      
      {/* Cache Statistics Card */}
      <div className="bg-white rounded-lg border border-gray-200 shadow-sm">
        <div className="px-4 py-3 border-b border-gray-200">
          <div className="flex items-center gap-2">
            <Database className="w-4 h-4 text-blue-600" />
            <h3 className="text-base font-semibold text-gray-900">{t('settings_cache_statistics')}</h3>
          </div>
        </div>
        <div className="p-4">
          <div className="grid grid-cols-2 gap-3">
            <div>
              <p className="text-xs text-gray-600">{t('settings_table_status')}</p>
              <p className="text-sm font-semibold text-gray-900 mt-1">
                {stats.cache.table_exists ? (
                  <span className="text-green-600">✓ {t('settings_exists')}</span>
                ) : (
                  <span className="text-red-600">✗ {t('settings_missing')}</span>
                )}
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-600">{t('settings_row_count')}</p>
              <p className="text-sm font-semibold text-gray-900 mt-1">
                {(stats.cache.row_count || 0).toLocaleString(locale)}
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-600">{t('settings_table_size')}</p>
              <p className="text-sm font-semibold text-gray-900 mt-1">
                {(stats.cache.table_size_mb || 0).toFixed(2)} MB
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-600">{t('settings_indexes')}</p>
              <p className="text-sm font-semibold text-gray-900 mt-1">
                {stats.cache.index_count || 0}
              </p>
            </div>
          </div>

          <div className="mt-3 pt-3 border-t border-gray-200">
            <div className="flex items-center gap-2 text-xs text-gray-600">
              <Clock className="w-3 h-3" />
              <span>
                {t('settings_last_sync')}: {stats.cache.last_sync || t('settings_never_synced')}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Health Status Card */}
      <div className="bg-white rounded-lg border border-gray-200 shadow-sm">
        <div className="px-4 py-3 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <AlertCircle className="w-4 h-4 text-blue-600" />
              <h3 className="text-base font-semibold text-gray-900">{t('settings_health_check')}</h3>
            </div>
            <div className={`flex items-center gap-1.5 px-2 py-0.5 rounded-full border text-xs ${getHealthColor(stats.health.status)}`}>
              {getHealthIcon(stats.health.status)}
              <span className="font-semibold">{stats.health.status}</span>
            </div>
          </div>
        </div>
        <div className="p-4">
          <div className="grid grid-cols-2 gap-3">
            <div>
              <p className="text-xs text-gray-600">{t('settings_cache_variations')}</p>
              <p className="text-sm font-semibold text-gray-900 mt-1">
                {(stats.health.cache_count || 0).toLocaleString(locale)}
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-600">{t('settings_woo_variations')}</p>
              <p className="text-sm font-semibold text-gray-900 mt-1">
                {(stats.health.actual_count || 0).toLocaleString(locale)}
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-600">{t('settings_missing_cache')}</p>
              <p className={`text-sm font-semibold mt-1 ${stats.health.missing_count > 0 ? 'text-yellow-600' : 'text-green-600'}`}>
                {stats.health.missing_count || 0}
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-600">{t('settings_orphaned_cache')}</p>
              <p className={`text-sm font-semibold mt-1 ${stats.health.orphaned_count > 0 ? 'text-yellow-600' : 'text-green-600'}`}>
                {stats.health.orphaned_count || 0}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Performance Metrics Card */}
      <div className="bg-white rounded-lg border border-gray-200 shadow-sm">
        <div className="px-4 py-3 border-b border-gray-200">
          <div className="flex items-center gap-2">
            <Zap className="w-4 h-4 text-yellow-600" />
            <h3 className="text-base font-semibold text-gray-900">{t('settings_performance_metrics')}</h3>
          </div>
        </div>
        <div className="p-4">
          <div className="grid grid-cols-3 gap-2">
            <div className="text-center p-2 bg-gradient-to-br from-blue-50 to-blue-100 rounded border border-blue-200">
              <p className="text-xs text-blue-700 font-medium">{t('settings_avg_query')}</p>
              <p className="text-xl font-bold text-blue-900 mt-1">
                {(stats.performance.avg_query_time_ms || 0).toFixed(1)}
                <span className="text-sm ml-0.5">ms</span>
              </p>
            </div>
            <div className="text-center p-2 bg-gradient-to-br from-green-50 to-green-100 rounded border border-green-200">
              <p className="text-xs text-green-700 font-medium">{t('settings_cache_hit')}</p>
              <p className="text-xl font-bold text-green-900 mt-1">
                {(stats.performance.cache_hit_rate || 0).toFixed(1)}
                <span className="text-sm ml-0.5">%</span>
              </p>
            </div>
            <div className="text-center p-2 bg-gradient-to-br from-purple-50 to-purple-100 rounded border border-purple-200">
              <p className="text-xs text-purple-700 font-medium">{t('settings_throughput')}</p>
              <p className="text-xl font-bold text-purple-900 mt-1">
                {((stats.performance.variations_per_second || 0) / 1000).toFixed(0)}
                <span className="text-sm ml-0.5">k/s</span>
              </p>
            </div>
          </div>

          {/* Performance Indicator Progress Bar */}
          <div className="mt-4">
            <PerformanceIndicator
              responseTime={stats.performance.avg_query_time_ms || 0}
              throughput={(stats.performance.variations_per_second || 0) / 1000}
            />
          </div>
        </div>
      </div>

      {/* System Information Card */}
      <div className="bg-white rounded-lg border border-gray-200 shadow-sm">
        <div className="px-4 py-3 border-b border-gray-200">
          <div className="flex items-center gap-2">
            <Info className="w-4 h-4 text-blue-600" />
            <h3 className="text-base font-semibold text-gray-900">{t('settings_system_info')}</h3>
          </div>
        </div>
        <div className="p-4">
          <div className="grid grid-cols-2 gap-3 text-xs">
            <div>
              <p className="text-gray-600">{t('settings_wordpress_version')}</p>
              <p className="font-semibold text-gray-900 mt-1">{stats.system.wordpress_version}</p>
            </div>
            <div>
              <p className="text-gray-600">{t('settings_woocommerce_version')}</p>
              <p className="font-semibold text-gray-900 mt-1">{stats.system.woocommerce_version}</p>
            </div>
            <div>
              <p className="text-gray-600">{t('settings_php_version')}</p>
              <p className="font-semibold text-gray-900 mt-1">{stats.system.php_version}</p>
            </div>
            <div>
              <p className="text-gray-600">{t('settings_php_memory_limit')}</p>
              <p className="font-semibold text-gray-900 mt-1">{stats.system.php_memory_limit || 'N/A'}</p>
            </div>
            <div>
              <p className="text-gray-600">{t('settings_mysql_version')}</p>
              <p className="font-semibold text-gray-900 mt-1">{stats.system.mysql_version}</p>
            </div>
            <div>
              <p className="text-gray-600">{t('settings_table_engine')}</p>
              <p className="font-semibold text-gray-900 mt-1">{stats.system.table_engine}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Last Error (if any) - moved inside left column */}
      {stats.sync.last_error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <div className="flex items-start gap-3">
            <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0 mt-0.5" />
            <div>
              <p className="font-semibold text-red-900">{t('settings_last_sync_error')}:</p>
              <p className="text-sm text-red-700 mt-1">{stats.sync.last_error}</p>
            </div>
          </div>
        </div>
      )}
      
        </div> {/* End of Left Column */}
        
        {/* RIGHT COLUMN (1/2): License Management */}
        <div className="lg:col-span-1">
          <LicenseManager />
        </div>
        
      </div> {/* End of Main Layout Grid */}
    </div>
  );
}
