import { useEffect, useState } from "react";

import ModalPortal from "../../components/ui/ModalPortal";
import OmsorgButton from "../../components/ui/OmsorgButton";
import { useValueListItems } from "../../app/useValueListItems";

export default function FollowUpDaysDialog({ onCancel, onConfirm }) {
  const { items } = useValueListItems("FollowUpPeriods");
  const [selectedDays, setSelectedDays] = useState(null);

  useEffect(() => {
    if (selectedDays === null && items.length > 0) {
      const defaultItem = items.find((item) => item.isDefault) ?? items[0];
      setSelectedDays(defaultItem.value);
    }
  }, [items, selectedDays]);

  function handleConfirm(event) {
    event.preventDefault();
    if (selectedDays !== null) {
      onConfirm(Number(selectedDays));
    }
  }

  return (
    <ModalPortal>
      <div className="modal-overlay" role="dialog" aria-modal="true" aria-label="Wiedervorlage-Frist wählen">
        <div className="modal-panel">
          <h2>Wiedervorlage-Frist wählen</h2>
          <p>In wie vielen Tagen soll diese Einrichtung erneut vorgelegt werden?</p>

          <form onSubmit={handleConfirm}>
            <div className="form-grid">
              {items.map((item) => (
                <label key={item.id} className="form-field form-field--radio">
                  <input
                    type="radio"
                    name="followUpDays"
                    value={item.value}
                    checked={selectedDays === item.value}
                    onChange={() => setSelectedDays(item.value)}
                  />
                  <span>{item.value} Tage</span>
                </label>
              ))}
            </div>

            <div className="form-actions">
              <OmsorgButton variant="secondary" type="button" onClick={onCancel}>
                Abbrechen
              </OmsorgButton>
              <OmsorgButton type="submit" disabled={selectedDays === null}>
                Bestätigen
              </OmsorgButton>
            </div>
          </form>
        </div>
      </div>
    </ModalPortal>
  );
}
