import React, { useMemo, useState } from 'react';
import { generateTrainingPlan } from '../../utils/trainingPlanGenerator';
import { useTranslation } from '../../i18n/LanguageContext';

const formatDateTime = (value) => {
  if (!value) return '—';
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) return value;
  return new Intl.DateTimeFormat('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  }).format(parsed);
};

const taskWithUpdatedIntensity = (task, intensity) => {
  if (task.type !== 'main') return task;

  const repetitionsByIntensity = {
    hoch: 24,
    mittel: 18,
    leicht: 12
  };

  return {
    ...task,
    intensity,
    repetitions: repetitionsByIntensity[intensity] || 18
  };
};

const statusButtonClass = (active) =>
  active
    ? 'bg-indigo-600 text-white border-indigo-600'
    : 'bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-200 border-gray-300 dark:border-gray-700';

export default function TrainingPlanPanel({
  patType,
  analysis,
  activePlan,
  historyPlans,
  loading,
  saving,
  error,
  onSavePlan,
  onUpdateSessionState,
  onUpdateSessionPartial,
  onReload
}) {
  const t = useTranslation();
  const [durationWeeks, setDurationWeeks] = useState(4);
  const [sessionsPerWeek, setSessionsPerWeek] = useState(3);
  const [draftSessions, setDraftSessions] = useState([]);
  const [uiMessage, setUiMessage] = useState('');

  const draftSummary = useMemo(() => {
    const total = draftSessions.length;
    const high = draftSessions.filter((session) => session.intensity === 'hoch').length;
    const medium = draftSessions.filter((session) => session.intensity === 'mittel').length;
    const low = draftSessions.filter((session) => session.intensity === 'leicht').length;

    return { total, high, medium, low };
  }, [draftSessions]);

  const handleGenerateDraft = () => {
    const generated = generateTrainingPlan({
      topWeaknesses: analysis?.topWeaknesses || [],
      topStrengths: analysis?.topStrengths || [],
      durationWeeks,
      sessionsPerWeek,
      sessionMix: '1-main-2-secondary'
    });

    setDraftSessions(generated.sessions);
    setUiMessage(t('training.draft_created'));
  };

  const updateDraftSession = (index, patch) => {
    setDraftSessions((previous) =>
      previous.map((session, currentIndex) => {
        if (currentIndex !== index) return session;

        const next = {
          ...session,
          ...patch
        };

        if (Object.prototype.hasOwnProperty.call(patch, 'intensity')) {
          next.tasks = next.tasks.map((task) => taskWithUpdatedIntensity(task, patch.intensity));
        }

        return next;
      })
    );
  };

  const handleSaveDraft = async () => {
    if (!draftSessions.length) {
      setUiMessage(t('training.create_draft_first'));
      return;
    }

    const result = await onSavePlan({
      analysis,
      durationWeeks,
      sessionsPerWeek,
      sessions: draftSessions
    });

    if (!result?.ok) {
      setUiMessage(result?.error?.message || t('training.save_error'));
      return;
    }

    setUiMessage(t('training.save_success'));
    setDraftSessions([]);
  };

  const renderSessionEditor = (session, index) => {
    const secondaryAsText = session.secondaryExercises.join(', ');

    return (
      <div key={`draft-${index}`} className="rounded-xl border border-sky-100 dark:border-sky-900/60 bg-sky-50/60 dark:bg-sky-950/20 p-3">
        <div className="flex items-center justify-between mb-2">
          <p className="text-sm font-semibold text-sky-800 dark:text-sky-200">
            {t('training.week_session', { weekNo: session.weekNo, sessionNo: session.sessionNo })}
          </p>
          <span className="text-xs text-sky-700 dark:text-sky-300">{session.intensity}</span>
        </div>

        <div className="grid md:grid-cols-3 gap-2 text-sm">
          <input
            value={session.mainExercise}
            onChange={(event) => updateDraftSession(index, { mainExercise: event.target.value })}
            className="px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900"
            placeholder={t('training.main_exercise')}
          />

          <input
            value={secondaryAsText}
            onChange={(event) => {
              const secondaryExercises = event.target.value
                .split(',')
                .map((value) => value.trim())
                .filter(Boolean)
                .slice(0, 2);

              updateDraftSession(index, {
                secondaryExercises:
                  secondaryExercises.length === 2
                    ? secondaryExercises
                    : [...secondaryExercises, 'Positionsspiel Basis'].slice(0, 2)
              });
            }}
            className="px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900"
            placeholder={t('training.side_exercises')}
          />

          <select
            value={session.intensity}
            onChange={(event) => updateDraftSession(index, { intensity: event.target.value })}
            className="px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900"
          >
            <option value="hoch">{t('training.high')}</option>
            <option value="mittel">{t('training.medium')}</option>
            <option value="leicht">{t('training.easy')}</option>
          </select>
        </div>
      </div>
    );
  };

  return (
    <section className="rounded-2xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm">
      <div className="flex items-start justify-between flex-wrap gap-3 mb-4">
        <div>
          <h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100">{t('training.title', { patType })}</h3>
          <p className="text-sm text-gray-600 dark:text-gray-400">
            {t('training.hint')}
          </p>
        </div>

        <button
          onClick={onReload}
          type="button"
          className="px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800"
        >
          {t('training.reload')}
        </button>
      </div>

      {error && (
        <div className="mb-3 rounded-lg border border-red-300 dark:border-red-800 bg-red-50 dark:bg-red-900/30 p-3 text-sm text-red-700 dark:text-red-200">
          {error}
        </div>
      )}

      <div className="grid md:grid-cols-4 gap-3 mb-4">
        <label className="text-sm text-gray-700 dark:text-gray-200">
          {t('training.duration')}
          <select
            value={durationWeeks}
            onChange={(event) => setDurationWeeks(Number(event.target.value))}
            className="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900"
          >
            <option value={2}>{t('training.2weeks')}</option>
            <option value={4}>{t('training.4weeks')}</option>
            <option value={6}>{t('training.6weeks')}</option>
          </select>
        </label>

        <label className="text-sm text-gray-700 dark:text-gray-200">
          {t('training.sessions_per_week')}
          <select
            value={sessionsPerWeek}
            onChange={(event) => setSessionsPerWeek(Number(event.target.value))}
            className="mt-1 w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900"
          >
            <option value={2}>2</option>
            <option value={3}>3</option>
            <option value={4}>4</option>
          </select>
        </label>

        <button
          onClick={handleGenerateDraft}
          type="button"
          className="md:self-end px-4 py-2 rounded-lg bg-indigo-600 text-white hover:bg-indigo-700"
        >
          {t('training.generate')}
        </button>

        <button
          onClick={handleSaveDraft}
          type="button"
          disabled={saving || !draftSessions.length}
          className="md:self-end px-4 py-2 rounded-lg bg-emerald-600 text-white hover:bg-emerald-700 disabled:opacity-60"
        >
          {saving ? t('training.saving') : t('training.save_draft')}
        </button>
      </div>

      {uiMessage && (
        <div className="mb-4 rounded-lg border border-indigo-200 dark:border-indigo-800 bg-indigo-50 dark:bg-indigo-900/30 p-3 text-sm text-indigo-700 dark:text-indigo-200">
          {uiMessage}
        </div>
      )}

      {draftSessions.length > 0 && (
        <div className="mb-6">
          <div className="flex items-center justify-between mb-2">
            <h4 className="text-sm font-semibold text-gray-900 dark:text-gray-100">{t('training.draft_label')}</h4>
            <p className="text-xs text-gray-500 dark:text-gray-400">
              {t('training.sessions_info', { count: draftSummary.total, high: draftSummary.high, medium: draftSummary.medium, easy: draftSummary.low })}
            </p>
          </div>

          <div className="max-h-80 overflow-y-auto space-y-2 pr-1">{draftSessions.map(renderSessionEditor)}</div>
        </div>
      )}

      <div className="grid lg:grid-cols-2 gap-4">
        <div className="rounded-xl border border-emerald-100 dark:border-emerald-900/60 p-3 bg-emerald-50/50 dark:bg-emerald-950/20">
          <h4 className="font-semibold text-emerald-800 dark:text-emerald-200 mb-2">{t('training.active_plan')}</h4>

          {loading ? (
            <p className="text-sm text-gray-600 dark:text-gray-300">{t('training.loading')}</p>
          ) : !activePlan ? (
            <p className="text-sm text-gray-600 dark:text-gray-300">{t('training.no_active')}</p>
          ) : (
            <>
              <p className="text-xs text-gray-600 dark:text-gray-300 mb-2">
                {t('training.generated', { date: formatDateTime(activePlan.generatedAt), weeks: activePlan.durationWeeks, sessions: activePlan.sessionsPerWeek })}
              </p>

              <div className="max-h-80 overflow-y-auto space-y-2 pr-1">
                {activePlan.sessions.map((session) => (
                  <div key={session.id} className="rounded-lg border border-emerald-200/70 dark:border-emerald-800 bg-white dark:bg-gray-900 p-3">
                    <div className="flex items-center justify-between gap-2 mb-2">
                      <p className="text-sm font-semibold text-gray-900 dark:text-gray-100">
                        {t('training.week_short', { weekNo: session.weekNo, sessionNo: session.sessionNo })}
                      </p>
                      <div className="flex gap-1">
                        {['open', 'done', 'skipped'].map((state) => (
                          <button
                            key={state}
                            type="button"
                            onClick={() => onUpdateSessionState(session.id, state)}
                            className={`text-xs px-2 py-1 border rounded ${statusButtonClass(session.state === state)}`}
                          >
                            {state === 'open' ? t('training.status_open') : state === 'done' ? t('training.status_done') : t('training.status_skipped')}
                          </button>
                        ))}
                      </div>
                    </div>

                    <input
                      defaultValue={session.mainExercise}
                      onBlur={(event) =>
                        onUpdateSessionPartial(session.id, {
                          mainExercise: event.target.value
                        })
                      }
                      className="w-full mb-2 px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900"
                    />

                    <input
                      defaultValue={session.secondaryExercises.join(', ')}
                      onBlur={(event) =>
                        onUpdateSessionPartial(session.id, {
                          secondaryExercises: event.target.value
                            .split(',')
                            .map((value) => value.trim())
                            .filter(Boolean)
                            .slice(0, 2)
                        })
                      }
                      className="w-full mb-2 px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900"
                    />

                    <textarea
                      defaultValue={session.notes || ''}
                      onBlur={(event) => onUpdateSessionPartial(session.id, { notes: event.target.value })}
                      placeholder={t('training.note')}
                      className="w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900"
                      rows={2}
                    />
                  </div>
                ))}
              </div>
            </>
          )}
        </div>

        <div className="rounded-xl border border-gray-200 dark:border-gray-800 p-3 bg-gray-50 dark:bg-gray-950/40">
          <h4 className="font-semibold text-gray-900 dark:text-gray-100 mb-2">{t('training.history')}</h4>

          {!historyPlans.length ? (
            <p className="text-sm text-gray-600 dark:text-gray-300">{t('training.no_history')}</p>
          ) : (
            <div className="space-y-2 max-h-80 overflow-y-auto pr-1">
              {historyPlans.map((plan) => (
                <div key={plan.id} className="rounded-lg border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-3">
                  <p className="text-sm font-semibold text-gray-800 dark:text-gray-100">
                    {formatDateTime(plan.generatedAt)}
                  </p>
                  <p className="text-xs text-gray-600 dark:text-gray-300">
                    {plan.durationWeeks} Wochen · {plan.sessionsPerWeek} Einheiten/Woche · {plan.sessions.length} Sessions
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
