import React, { useEffect, useMemo } from 'react';
import { Activity, AlertTriangle, Brain, Target } from 'lucide-react';
import { buildAnalysis } from '../../utils/analysisEngine';
import { useTrainingPlans } from '../../hooks/useTrainingPlans';
import { useTranslation } from '../../i18n/LanguageContext';
import GapBarChart from './GapBarChart';
import RadarChart from './RadarChart';
import StrengthList from './StrengthList';
import TrainingPlanPanel from './TrainingPlanPanel';
import TrendChart from './TrendChart';
import WeaknessPriorityList from './WeaknessPriorityList';

export default function AnalysisTab({
  assessments,
  selectedPatType,
  onPatTypeChange,
  patTypes,
  user
}) {
  const t = useTranslation();
  const patTypeOptions = Object.keys(patTypes || {});

  useEffect(() => {
    if (!selectedPatType && patTypeOptions.length) {
      onPatTypeChange(patTypeOptions[0]);
    }
  }, [onPatTypeChange, patTypeOptions, selectedPatType]);

  const analysis = useMemo(
    () =>
      buildAnalysis(assessments, selectedPatType, {
        windowSize: 5,
        missingStrategy: 'zero'
      }),
    [assessments, selectedPatType]
  );

  const selectedPatAssessments = assessments.filter((assessment) => assessment.patType === selectedPatType);
  const hasAssessments = assessments.length > 0;

  const {
    activePlan,
    historyPlans,
    loading,
    saving,
    error,
    saveGeneratedPlan,
    updateSessionState,
    updateSessionPartial,
    loadPlans
  } = useTrainingPlans({
    user,
    patType: selectedPatType
  });

  const handleSavePlan = ({ durationWeeks, sessionsPerWeek, sessions }) =>
    saveGeneratedPlan({
      analysis,
      durationWeeks,
      sessionsPerWeek,
      sessions
    });

  return (
    <div className="min-h-screen bg-gradient-to-br from-cyan-50 via-white to-emerald-50 dark:from-gray-950 dark:via-gray-950 dark:to-gray-900 p-6 text-gray-900 dark:text-gray-100">
      <div className="max-w-7xl mx-auto space-y-6">
        <section className="rounded-2xl border border-gray-200 dark:border-gray-800 bg-white/90 dark:bg-gray-900/80 backdrop-blur p-5 shadow-sm">
          <div className="flex items-start justify-between gap-4 flex-wrap">
            <div>
              <p className="text-xs uppercase tracking-[0.2em] text-cyan-700 dark:text-cyan-300">{t('analysis.title')}</p>
              <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">{t('analysis.priority_title')}</h1>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                {t('analysis.priority_desc')}
              </p>
            </div>
          </div>

          <div className="mt-4 flex flex-wrap gap-2">
            {patTypeOptions.map((patType) => {
              const isActive = patType === selectedPatType;
              return (
                <button
                  key={patType}
                  type="button"
                  onClick={() => onPatTypeChange(patType)}
                  className={`px-4 py-2 rounded-lg border text-sm font-semibold transition ${
                    isActive
                      ? 'bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900 border-gray-900 dark:border-gray-100'
                      : 'bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-200 border-gray-300 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800'
                  }`}
                >
                  {patType}
                </button>
              );
            })}
          </div>

          <div className="mt-4 flex flex-wrap gap-2 text-xs">
            <span className="px-3 py-1 rounded-full border border-cyan-200 dark:border-cyan-800 bg-cyan-50 dark:bg-cyan-900/30 text-cyan-700 dark:text-cyan-200 font-semibold">
              <Activity className="w-3 h-3 inline-block mr-1" />
              {t('analysis.assessments_count', { count: selectedPatAssessments.length })}
            </span>

            <span className="px-3 py-1 rounded-full border border-indigo-200 dark:border-indigo-800 bg-indigo-50 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-200 font-semibold">
              <Target className="w-3 h-3 inline-block mr-1" />
              {t('analysis.window', { count: analysis.windowedAssessments.length })}
            </span>

            {analysis.isLimitedData && (
              <span className="px-3 py-1 rounded-full border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-200 font-semibold">
                <AlertTriangle className="w-3 h-3 inline-block mr-1" />
                {t('analysis.limited_data')}
              </span>
            )}
          </div>
        </section>

        {!hasAssessments ? (
          <section className="rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 bg-white/80 dark:bg-gray-900/70 p-6 text-center">
            <Brain className="w-10 h-10 mx-auto mb-3 text-gray-400 dark:text-gray-500" />
            <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-1">{t('analysis.no_data')}</h2>
            <p className="text-sm text-gray-600 dark:text-gray-300">{t('analysis.no_data_hint')}</p>
          </section>
        ) : selectedPatAssessments.length === 0 ? (
          <section className="rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 bg-white/80 dark:bg-gray-900/70 p-6 text-center">
            <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-1">{t('analysis.no_type_data', { patType: selectedPatType })}</h2>
            <p className="text-sm text-gray-600 dark:text-gray-300">{t('analysis.no_type_hint')}</p>
          </section>
        ) : (
          <>
            <section className="grid lg:grid-cols-2 gap-4">
              <div className="h-full">
                <GapBarChart metrics={analysis.exerciseMetrics} />
              </div>
              <div className="h-full">
                <RadarChart radarSeries={analysis.radarSeries} />
              </div>
              <div className="lg:col-span-2">
                <TrendChart trendSeries={analysis.trendSeries} />
              </div>
            </section>

            <section className="grid lg:grid-cols-2 gap-4">
              <WeaknessPriorityList weaknesses={analysis.topWeaknesses} />
              <StrengthList strengths={analysis.topStrengths} />
            </section>

            <TrainingPlanPanel
              patType={selectedPatType}
              analysis={analysis}
              activePlan={activePlan}
              historyPlans={historyPlans}
              loading={loading}
              saving={saving}
              error={error}
              onSavePlan={handleSavePlan}
              onUpdateSessionState={updateSessionState}
              onUpdateSessionPartial={updateSessionPartial}
              onReload={loadPlans}
            />
          </>
        )}
      </div>
    </div>
  );
}
