import React, { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Shield, AlertTriangle, Lock, Clock, Zap, Puzzle, X } from 'lucide-react';
import { useConfirm } from '../hooks/useConfirm';
import { useHistory } from '../hooks/useHistory';
import { useHardening } from '../hooks/useHardening';
import StatCard from '../components/StatCard';
import GeoTrafficChart from '../components/GeoTrafficChart';
import OriginTrafficChart from '../components/OriginTrafficChart';
import PremiumFeatureBanner from '../components/PremiumFeatureBanner';

const PRO_FEATURE_LABEL = 'Available in Pro';

const DashboardPage = ({ onNavigate, onboardingStep }) => {
  const { t } = useTranslation();
  const { ConfirmDialog } = useConfirm();
  const { loadHistory, loadInfectedFiles, scanTotal, infectedTotal, scanMeta } = useHistory();
  const { rules: hardeningRules, preset: hardeningPreset, isLoading: hardeningLoading } = useHardening();
  const [cacheHitRate, setCacheHitRate] = useState(null);
  const [nextScanInfo, setNextScanInfo] = useState({ value: PRO_FEATURE_LABEL, enabled: false });
  const [vulnerablePluginsModalOpen, setVulnerablePluginsModalOpen] = useState(false);
  const [vulnerablePlugins, setVulnerablePlugins] = useState([]);
  const [vulnerablePluginsLoading, setVulnerablePluginsLoading] = useState(true);
  const [vulnerablePluginsError, setVulnerablePluginsError] = useState(false);
  const [expandedChart, setExpandedChart] = useState(null);
  const mapContainerRef = React.useRef(null);
  const trafficContainerRef = React.useRef(null);
  const isTransitioningRef = React.useRef(false);
  const pendingResizeRef = React.useRef(false);
  const transitionTimeoutRef = React.useRef(null);

  const pluginsAdminUrl = useMemo(() => {
    const ajaxUrl =
      typeof window !== 'undefined' && window.phguardData && window.phguardData.ajaxUrl
        ? window.phguardData.ajaxUrl
        : '';
    if (!ajaxUrl || typeof ajaxUrl !== 'string') {
      return '';
    }
    return ajaxUrl.replace(/\/admin-ajax\.php(\?.*)?$/i, '/plugins.php');
  }, []);

  const vulnerablePluginStats = useMemo(() => {
    if (vulnerablePluginsLoading) {
      return {
        vulnerableCount: 0,
        severityLabel: t('dashboard.loading', { defaultValue: 'Loading...' }),
        tone: 'default',
        state: '',
      };
    }
    if (vulnerablePluginsError) {
      return {
        vulnerableCount: 0,
        severityLabel: t('dashboard.vulnerablePluginsUnavailable', { defaultValue: 'Unavailable' }),
        tone: 'default',
        state: '',
      };
    }
    const vulnerableCount = vulnerablePlugins.filter((p) => p.vulnerable).length;
    if (vulnerableCount >= 3) {
      return {
        vulnerableCount,
        severityLabel: t('dashboard.severityHigh', { defaultValue: 'High' }),
        tone: 'danger',
        state: 'critical',
      };
    }
    if (vulnerableCount >= 1) {
      return {
        vulnerableCount,
        severityLabel: t('dashboard.severityMedium', { defaultValue: 'Medium' }),
        tone: 'warning',
        state: 'detected',
      };
    }
    return {
      vulnerableCount,
      severityLabel: t('dashboard.severityLow', { defaultValue: 'Great' }),
      tone: 'success',
      state: 'good',
    };
  }, [t, vulnerablePlugins, vulnerablePluginsLoading, vulnerablePluginsError]);

  React.useEffect(() => {
    const ajaxUrl =
      typeof window !== 'undefined' && window.phguardData && window.phguardData.ajaxUrl
        ? window.phguardData.ajaxUrl
        : null;
    const nonce =
      typeof window !== 'undefined' && window.phguardData && window.phguardData.historyNonce
        ? window.phguardData.historyNonce
        : '';
    if (!ajaxUrl) {
      setVulnerablePluginsLoading(false);
      setVulnerablePluginsError(true);
      return;
    }

    let cancelled = false;
    setVulnerablePluginsLoading(true);
    setVulnerablePluginsError(false);

    const params = new URLSearchParams();
    params.append('action', 'phguard_get_vulnerable_plugins');
    params.append('nonce', nonce);

    fetch(ajaxUrl, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
      body: params.toString(),
    })
      .then((res) => res.json())
      .then((json) => {
        if (cancelled) {
          return;
        }
        if (json.success && json.data && Array.isArray(json.data.plugins)) {
          setVulnerablePlugins(json.data.plugins);
          setVulnerablePluginsError(false);
        } else {
          setVulnerablePlugins([]);
          setVulnerablePluginsError(true);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setVulnerablePlugins([]);
          setVulnerablePluginsError(true);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setVulnerablePluginsLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
   }, []);

  React.useEffect(() => {
    loadHistory(1, 10);
    loadInfectedFiles(1, 6);
  }, [loadHistory, loadInfectedFiles]);

  const resizeCharts = () => {
    requestAnimationFrame(() => {
      window.dispatchEvent(new Event('resize'));
    });
  };

  const completeTransition = () => {
    isTransitioningRef.current = false;
    if (transitionTimeoutRef.current) {
      clearTimeout(transitionTimeoutRef.current);
      transitionTimeoutRef.current = null;
    }
    if (pendingResizeRef.current) {
      pendingResizeRef.current = false;
      resizeCharts();
    }
  };

  const handleToggleMapExpand = () => setExpandedChart(expandedChart === 'map' ? null : 'map');
  const handleToggleTrafficExpand = () => setExpandedChart(expandedChart === 'traffic' ? null : 'traffic');

  React.useEffect(() => {
    isTransitioningRef.current = true;
    pendingResizeRef.current = false;
    if (transitionTimeoutRef.current) clearTimeout(transitionTimeoutRef.current);
    transitionTimeoutRef.current = setTimeout(completeTransition, 200);
  }, [expandedChart]);

  React.useEffect(() => {
    if (!mapContainerRef.current || !trafficContainerRef.current) return;
    const triggerResize = () => {
      if (isTransitioningRef.current) {
        pendingResizeRef.current = true;
        return;
      }
      resizeCharts();
    };
    const handleTransitionEnd = (e) => {
      if (['flex', 'flex-basis', 'width', 'max-width'].includes(e.propertyName)) completeTransition();
    };
    const resizeObserver = new ResizeObserver(triggerResize);
    const containers = [mapContainerRef.current, trafficContainerRef.current];
    containers.forEach(c => {
      c.addEventListener('transitionend', handleTransitionEnd);
      resizeObserver.observe(c);
    });
    return () => {
      resizeObserver.disconnect();
      if (transitionTimeoutRef.current) clearTimeout(transitionTimeoutRef.current);
      containers.forEach(c => c.removeEventListener('transitionend', handleTransitionEnd));
    };
  }, []);

  const totalScans = scanTotal || scanMeta?.total || 0;
  const totalMalware = infectedTotal || 0;

  const hardeningStatus = useMemo(() => {
    if (hardeningLoading || !hardeningPreset || !hardeningRules) {
      return {
        presetName: null,
        enabledCount: 0,
        totalCount: 0,
        subtitle: t('dashboard.loading', { defaultValue: 'Loading...' }),
        value: '--',
        tone: 'default',
        state: '',
      };
    }
    const currentPreset = hardeningPreset.current || 'default';
    const presetLabel = hardeningPreset.available?.[currentPreset] || currentPreset;
    const enabledRules = hardeningRules.filter(rule => rule.enabled);
    const enabledCount = enabledRules.length;
    const totalCount = hardeningRules.length;
    let subtitle = '';
    let value = '';
    if (currentPreset === 'advanced') {
      subtitle = t('dashboard.hardening.advanced', { defaultValue: 'Maximum security enabled' });
      value = presetLabel;
    } else if (currentPreset === 'recommended') {
      subtitle = t('dashboard.hardening.recommended', { defaultValue: 'Enhanced protection active' });
      value = presetLabel;
    } else if (currentPreset === 'default') {
      subtitle = t('dashboard.hardening.basic', { defaultValue: 'Basic security enabled' });
      value = presetLabel;
    } else {
      subtitle = t('dashboard.hardening.custom', { defaultValue: 'Custom configuration' });
      value = `${enabledCount}/${totalCount} ${t('dashboard.hardening.rules', { defaultValue: 'rules' })}`;
    }
    let tone = 'default';
    let state = '';
    if (currentPreset === 'advanced') { tone = 'success'; state = 'excellent'; }
    else if (currentPreset === 'recommended') { tone = 'success'; state = 'good'; }
    else if (currentPreset === 'default') { tone = 'warning'; state = 'basic'; }
    else {
      const basicRulesCount = hardeningRules.filter(r => r.type === 'basic').length;
      tone = enabledCount >= basicRulesCount ? 'success' : 'warning';
      state = enabledCount >= basicRulesCount ? 'good' : 'basic';
    }
    return { presetName: presetLabel, enabledCount, totalCount, subtitle, value, tone, state };
  }, [hardeningPreset, hardeningRules, hardeningLoading, t]);

  return (
    <div className="space-y-6">
      {ConfirmDialog}
      <PremiumFeatureBanner
        description={t('dashboard.premiumDescription', { defaultValue: 'Dashboard analytics and statistics are available in PhantomGuard Pro.' })}
      />
      <div className="flex flex-wrap md:flex-nowrap gap-4 items-stretch" data-onboarding="dashboard-stats">
        <div className="flex-1 min-w-[200px] flex">
            <StatCard
              title={t('dashboard.wpHardening')}
              subtitle={hardeningStatus.subtitle}
              value={hardeningStatus.value}
              icon={Lock}
              tone={hardeningStatus.tone}
              state={hardeningStatus.state}
              isLocked={true}
            />
        </div>

        <div className="flex-1 min-w-[200px] flex">
          <StatCard
            title={t('dashboard.cacheHitRate') || 'Cache Hit Rate'}
            subtitle={PRO_FEATURE_LABEL}
            value={cacheHitRate !== null ? `${cacheHitRate.toFixed(1)}%` : '--'}
            icon={Shield}
            tone="default"
            state=""
            isLocked={true}
          />
        </div>

        <div className="flex-1 min-w-[200px] flex">
          <button
            type="button"
            onClick={() => setVulnerablePluginsModalOpen(true)}
            className="w-full text-left transition-all duration-200 hover:scale-[1.02] active:scale-[0.98] focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 rounded-2xl flex"
            aria-label={t('dashboard.openVulnerablePluginsModal', {
              defaultValue: 'View vulnerable plugins details',
            })}
          >
            <StatCard
              title={t('dashboard.foundVulnerablePlugins', { defaultValue: 'Found Vulnerable Plugins' })}
              subtitle={t('dashboard.vulnerablePluginsCardSubtitle', {
                count: vulnerablePluginStats.vulnerableCount,
                defaultValue: '{{count}} vulnerable',
              })}
              value={vulnerablePluginStats.severityLabel}
              icon={Puzzle}
              tone={vulnerablePluginStats.tone}
              state={vulnerablePluginStats.state}
              isLocked={false}
            />
          </button>
        </div>

        <div className="flex-1 min-w-[200px] flex">
            <StatCard
              title={t('dashboard.foundTotalMalwares')}
              subtitle={PRO_FEATURE_LABEL}
              value={totalMalware}
              icon={AlertTriangle}
              tone={totalMalware === 0 ? 'success' : 'danger'}
              state={totalMalware === 0 ? 'clean' : totalMalware <= 2 ? 'detected' : 'critical'}
              isLocked={true}
            />
        </div>

        <div className="flex-1 min-w-[200px] flex">
          <StatCard
            title="Next scan in:"
            /* subtitle={PRO_FEATURE_LABEL} */
            value={nextScanInfo.value}
            icon={Clock}
            tone="default"
            state=""
            isLocked={true}
          />
        </div>

        <div className="flex-1 min-w-[200px] flex">
            <StatCard
              title={t('dashboard.purgeCache', { defaultValue: 'Purge Cache' }) || 'Purge Cache'}
              subtitle={PRO_FEATURE_LABEL}
              value={t('dashboard.clickToPurge', { defaultValue: 'Click to purge' })}
              icon={Zap}
              tone="default"
              state=""
              isLocked={true}
            />
        </div>
      </div>

      {vulnerablePluginsModalOpen && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 dark:bg-black/70 p-4"
          role="dialog"
          aria-modal="true"
          aria-labelledby="vulnerable-plugins-modal-title"
          onClick={() => setVulnerablePluginsModalOpen(false)}
        >
          <div
            className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-lg w-full max-h-[85vh] flex flex-col ring-1 ring-slate-200 dark:ring-slate-600"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-start justify-between gap-3 p-4 border-b border-slate-200 dark:border-slate-600 shrink-0">
              <h2
                id="vulnerable-plugins-modal-title"
                className="text-lg font-semibold text-slate-900 dark:text-slate-100 pr-2"
              >
                {t('dashboard.vulnerablePluginsModalTitle', { defaultValue: 'Vulnerable plugins' })}
              </h2>
              <button
                type="button"
                onClick={() => setVulnerablePluginsModalOpen(false)}
                className="rounded-lg p-1 text-slate-400 hover:text-slate-600 hover:bg-slate-100 dark:hover:text-slate-300 dark:hover:bg-slate-700 shrink-0"
                aria-label={t('common.close', { defaultValue: 'Close' })}
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="overflow-y-auto flex-1 px-4 py-2">
              {vulnerablePluginsLoading ? (
                <p className="text-sm text-slate-500 dark:text-slate-400 py-4">
                  {t('dashboard.loadingVulnerablePlugins', { defaultValue: 'Checking plugins…' })}
                </p>
              ) : vulnerablePluginsError ? (
                <p className="text-sm text-slate-500 dark:text-slate-400 py-4">
                  {t('dashboard.vulnerablePluginsLoadError', {
                    defaultValue: 'Could not load vulnerability data. Try again later.',
                  })}
                </p>
              ) : vulnerablePlugins.length === 0 ? (
                <p className="text-sm text-slate-500 dark:text-slate-400 py-4">
                  {t('dashboard.noPluginsFound', { defaultValue: 'No plugins found.' })}
                </p>
              ) : (
                <ul className="divide-y divide-slate-100 dark:divide-slate-700">
                  {vulnerablePlugins.map((plugin) => (
                    <li
                      key={plugin.file || plugin.name}
                      className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 py-3"
                    >
                      <span className="text-sm font-medium text-slate-800 dark:text-slate-200">
                        {plugin.name}
                      </span>
                      <div className="flex items-center gap-2 flex-wrap shrink-0">
                        <span
                          className={`text-xs font-semibold uppercase tracking-wide ${
                            plugin.vulnerable
                              ? 'text-red-600 dark:text-red-400'
                              : 'text-emerald-600 dark:text-emerald-400'
                          }`}
                        >
                          {plugin.vulnerable
                            ? t('dashboard.statusVulnerable', { defaultValue: 'Vulnerable' })
                            : t('dashboard.statusSafe', { defaultValue: 'Safe' })}
                        </span>
                        {plugin.vulnerable ? (
                          plugin.update_url ? (
                            <a
                              href={plugin.update_url}
                              className="text-xs font-medium px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white transition-colors"
                            >
                              {t('dashboard.updatePlugin', { defaultValue: 'Update' })}
                            </a>
                          ) : pluginsAdminUrl ? (
                            <a
                              href={pluginsAdminUrl}
                              className="text-xs font-medium px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white transition-colors"
                            >
                              {t('dashboard.updatePlugin', { defaultValue: 'Update' })}
                            </a>
                          ) : (
                            <button
                              type="button"
                              onClick={() =>
                                window.alert(
                                  t('dashboard.openPluginsAdmin', {
                                    defaultValue: 'Open Plugins in WordPress admin to update.',
                                  })
                                )
                              }
                              className="text-xs font-medium px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white transition-colors"
                            >
                              {t('dashboard.updatePlugin', { defaultValue: 'Update' })}
                            </button>
                          )
                        ) : (
                          <span className="text-xs text-slate-400 dark:text-slate-500 tabular-nums">
                            {t('dashboard.pluginUpToDate', { defaultValue: 'Up to date' })}
                          </span>
                        )}
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </div>
            <div className="p-4 border-t border-slate-200 dark:border-slate-600 flex justify-end shrink-0">
              <button
                type="button"
                onClick={() => setVulnerablePluginsModalOpen(false)}
                className="px-4 py-2 text-sm font-medium text-slate-700 dark:text-slate-200 bg-white dark:bg-gray-700 border border-slate-300 dark:border-slate-600 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-600"
              >
                {t('common.close', { defaultValue: 'Close' })}
              </button>
            </div>
          </div>
        </div>
      )}

      <div className="flex flex-wrap gap-6">
        <GeoTrafficChart
          containerRef={mapContainerRef}
          expandedChart={expandedChart}
          onToggleExpand={handleToggleMapExpand}
        />

        <OriginTrafficChart
          containerRef={trafficContainerRef}
          expandedChart={expandedChart}
          onToggleExpand={handleToggleTrafficExpand}
        />
      </div>
    </div>
  );
};

export default DashboardPage;
