import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useSetStore } from '../stores/setStore';
import { useActiveSessionStore } from '../stores/activeSessionStore';
import { useNavigationGuard } from '../hooks/useNavigationGuard';
import { ActiveSession } from '../components/training/ActiveSession';
import { ConfirmDialog } from '../components/layout/ConfirmDialog';

export function TrainingPage() {
  const navigate = useNavigate();
  const { sets, fetchSets, loading } = useSetStore();
  const { session, startSession } = useActiveSessionStore();
  const [starting, setStarting] = useState(false);
  const blocker = useNavigationGuard();

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

  const handleStart = async (setId: number) => {
    const trainingSet = sets.find((s) => s.id === setId);
    if (!trainingSet) return;

    setStarting(true);
    const success = await startSession(setId, trainingSet.exercises || []);
    setStarting(false);

    if (!success) return;
  };

  const handleEnd = () => {
    navigate('/history');
  };

  // Aktive Session anzeigen
  if (session) {
    return (
      <div className="space-y-4">
        <ActiveSession onEnd={handleEnd} />

        {/* Navigation Blocker Dialog */}
        {blocker.state === 'blocked' && (
          <ConfirmDialog
            isOpen={true}
            title="Training verlassen?"
            message="Du hast ein aktives Training. Wenn du die Seite verlässt, kannst du später fortfahren. Möchtest du trotzdem navigieren?"
            onConfirm={() => blocker.proceed?.()}
            onCancel={() => blocker.reset?.()}
          />
        )}
      </div>
    );
  }

  // Set-Auswahl
  return (
    <div className="space-y-4">
      <h1 className="text-2xl font-bold text-gray-100">Training starten</h1>

      {loading ? (
        <div className="text-center text-gray-500 py-8">Laden...</div>
      ) : sets.length === 0 ? (
        <div className="text-center text-gray-500 py-12">
          <p className="text-lg">Keine Sets vorhanden</p>
          <p className="text-sm mt-1">Erstelle zuerst ein Set unter "Sets".</p>
        </div>
      ) : (
        <div className="grid gap-3">
          {sets.map((set) => (
            <div
              key={set.id}
              className="bg-gray-900 border border-gray-800 rounded-xl p-4"
            >
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="font-semibold text-gray-100">{set.name}</h3>
                  <p className="text-sm text-gray-400 mt-0.5">
                    {set.exercises?.length || 0} Übungen
                  </p>
                </div>
                <button
                  onClick={() => handleStart(set.id)}
                  disabled={starting}
                  className="px-4 py-2 bg-green-600 hover:bg-green-500 text-white rounded-lg min-h-[44px] font-medium disabled:opacity-50"
                >
                  Starten
                </button>
              </div>
              {set.exercises && set.exercises.length > 0 && (
                <div className="flex flex-wrap gap-1 mt-3">
                  {set.exercises.map((ex) => (
                    <span
                      key={ex.id}
                      className="text-xs bg-gray-800 text-gray-400 px-2 py-1 rounded"
                    >
                      {ex.name}
                    </span>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
