import { useState } from 'react';
import { ExerciseList } from '../components/exercises/ExerciseList';
import { ExerciseForm } from '../components/exercises/ExerciseForm';
import { ConfirmDialog } from '../components/layout/ConfirmDialog';
import { useExerciseStore } from '../stores/exerciseStore';
import { useConfirm } from '../hooks/useConfirm';
import type { Exercise, CreateExerciseRequest } from '../types';

export function ExercisesPage() {
  const { createExercise, updateExercise, deleteExercise } = useExerciseStore();
  const [showForm, setShowForm] = useState(false);
  const [editingExercise, setEditingExercise] = useState<Exercise | null>(null);
  const { isOpen, title, message, confirm, handleConfirm, handleCancel } = useConfirm();

  const handleCreate = async (data: CreateExerciseRequest) => {
    const result = await createExercise(data);
    if (result) {
      setShowForm(false);
    }
  };

  const handleUpdate = async (data: CreateExerciseRequest) => {
    if (!editingExercise) return;
    const result = await updateExercise(editingExercise.id, data);
    if (result) {
      setEditingExercise(null);
      setShowForm(false);
    }
  };

  const handleEdit = (exercise: Exercise) => {
    setEditingExercise(exercise);
    setShowForm(true);
  };

  const handleDelete = async (exercise: Exercise) => {
    const ok = await confirm(
      'Übung löschen',
      `Möchtest du "${exercise.name}" wirklich löschen?`,
    );
    if (ok) {
      await deleteExercise(exercise.id);
    }
  };

  const handleCancelForm = () => {
    setShowForm(false);
    setEditingExercise(null);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-100">Übungen</h1>
        {!showForm && (
          <button
            onClick={() => {
              setEditingExercise(null);
              setShowForm(true);
            }}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg min-h-[44px] font-medium"
          >
            + Neue Übung
          </button>
        )}
      </div>

      {showForm && (
        <ExerciseForm
          exercise={editingExercise}
          onSubmit={editingExercise ? handleUpdate : handleCreate}
          onCancel={handleCancelForm}
        />
      )}

      <ExerciseList onEdit={handleEdit} onDelete={handleDelete} />

      <ConfirmDialog
        isOpen={isOpen}
        title={title}
        message={message}
        onConfirm={handleConfirm}
        onCancel={handleCancel}
      />
    </div>
  );
}
