import { useState } from 'react';
import { SetList } from '../components/sets/SetList';
import { SetForm } from '../components/sets/SetForm';
import { ConfirmDialog } from '../components/layout/ConfirmDialog';
import { useSetStore } from '../stores/setStore';
import { useConfirm } from '../hooks/useConfirm';
import type { TrainingSet } from '../types';

export function SetsPage() {
  const { createSet, updateSet, deleteSet } = useSetStore();
  const [showForm, setShowForm] = useState(false);
  const [editingSet, setEditingSet] = useState<TrainingSet | null>(null);
  const { isOpen, title, message, confirm, handleConfirm, handleCancel } = useConfirm();

  const handleCreate = async (name: string, exerciseIds: number[]) => {
    const result = await createSet({ name, exercise_ids: exerciseIds });
    if (result) {
      setShowForm(false);
    }
  };

  const handleUpdate = async (name: string, exerciseIds: number[]) => {
    if (!editingSet) return;
    const result = await updateSet(editingSet.id, {
      name,
      exercise_ids: exerciseIds,
    });
    if (result) {
      setEditingSet(null);
      setShowForm(false);
    }
  };

  const handleEdit = (set: TrainingSet) => {
    setEditingSet(set);
    setShowForm(true);
  };

  const handleDelete = async (set: TrainingSet) => {
    const ok = await confirm(
      'Set löschen',
      `Möchtest du "${set.name}" wirklich löschen?`,
    );
    if (ok) {
      await deleteSet(set.id);
    }
  };

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

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

      {showForm && (
        <SetForm
          trainingSet={editingSet}
          onSubmit={editingSet ? handleUpdate : handleCreate}
          onCancel={handleCancelForm}
        />
      )}

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

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