import React, { useState } from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

const AddOrderModal = ({ show, onHide, onSubmit }) => {
  const [deadline, setDeadline] = useState(new Date());
  const [robotsCount, setRobotsCount] = useState(2000);
  const [formError, setFormError] = useState("");

  const handleSubmit = () => {
    if (!deadline || robotsCount <= 0) {
      setFormError("Пожалуйста, заполните все поля корректно.");
      return;
    }
    setFormError("");
    onSubmit({ deadline, robotsCount });
  };

  if (!show) {
    return null;
  }

  return (
    <div
      className="modal fade show d-block"
      tabIndex="-1"
      role="dialog"
      style={{ backgroundColor: "rgba(0, 0, 0, 0.5)" }}
    >
      <div className="modal-dialog modal-dialog-centered" role="document">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">Добавить новый заказ</h5>
            <button
              type="button"
              className="btn-close"
              aria-label="Close"
              onClick={onHide}
            >
              <span>&times;</span>
            </button>
          </div>
          <div className="modal-body">
            {formError && <p className="text-danger">{formError}</p>}
            <div className="mb-3">
              <label htmlFor="robotsCount" className="form-label">
                Количество роботов:
              </label>
              <input
                type="number"
                className="form-control"
                id="robotsCount"
                value={robotsCount}
                onChange={(e) => setRobotsCount(Number(e.target.value))}
                min="1"
                placeholder="Введите количество роботов"
              />
            </div>
            <div className="mb-3">
              <label htmlFor="deadline" className="form-label">
                Дедлайн:
              </label>
              <DatePicker
                selected={deadline}
                onChange={(date) => setDeadline(date)}
                className="form-control"
                dateFormat="P"
                placeholderText="Выберите дату дедлайна"
              />
            </div>
          </div>
          <div className="modal-footer">
            <button
              type="button"
              className="btn btn-secondary"
              onClick={onHide}
            >
              Отмена
            </button>
            <button
              type="button"
              className="btn btn-primary"
              onClick={handleSubmit}
            >
              Подтвердить
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AddOrderModal;
