import React from "react";
import { connect } from "react-redux";

function TaskList(props) {
  const handleAddTask = () => {
    const text = prompt("Enter a new task:");
    if (text) {
      props.dispatch({ type: "ADD_TASK", text, id });
    }
  };

  const handleToggleTask = (id) => {
    props.dispatch({ type: "TOGGLE_TASK", id });
  };

  return (
    <div>
      <ul>
        {props.tasks.map((task) => (
          <li key={task.id}>
            <input
              type="checkbox"
              checked={task.completed}
              onChange={() => handleToggleTask(task.id)}
            />
            {task.text}
          </li>
        ))}
      </ul>
      <button onClick={handleAddTask}>Add Task</button>
    </div>
  );
}

function mapStateToProps(state) {
  return {
    tasks: state.tasksReducer.tasks,
  };
}

export default connect(mapStateToProps)(TaskList);
