'use client';

import { useEffect, useState } from 'react';
import type { ServiceKey } from '@/features/integrations/api.client';
import { errorText } from '@/lib/api/errors';
import { dateTimeInputValue, OVERLAP_CHOICES, rotationTimeError } from './data';

/**
 * Schedule rotation (the shared theme modal's look): the time is checked as it is typed, so Save
 * stays off until it is in the future; the API checks it again and its answer shows here too.
 */
export function ScheduleRotation({
  serviceKey,
  onSchedule,
  onClose,
}: {
  serviceKey: ServiceKey;
  /** Resolves when scheduled (the parent then closes this); a rejection is shown inline. */
  onSchedule: (at: string, overlapHours: number) => Promise<void>;
  onClose: () => void;
}) {
  const [value, setValue] = useState(() => {
    const tomorrow = new Date(Date.now() + 86_400_000);
    tomorrow.setMinutes(0, 0, 0);
    return dateTimeInputValue(serviceKey.rotateAt ? new Date(serviceKey.rotateAt) : tomorrow);
  });
  const [hours, setHours] = useState<number>(
    serviceKey.rotateOverlapHours ?? OVERLAP_CHOICES[1].hours,
  );
  const [touched, setTouched] = useState(false);
  const [saving, setSaving] = useState(false);
  const [serverError, setServerError] = useState<string | null>(null);
  // Checked on each render, so a time that passes while the dialog is open turns invalid too.
  const timeError = rotationTimeError(value);
  const shownError = touched ? timeError : null;

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !saving) onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose, saving]);

  const save = async () => {
    setTouched(true);
    if (rotationTimeError(value)) return;
    setSaving(true);
    setServerError(null);
    try {
      await onSchedule(new Date(value).toISOString(), hours);
    } catch (err) {
      setServerError(errorText(err));
      setSaving(false);
    }
  };

  return (
    <div
      className="sk-modal-backdrop"
      onClick={(e) => {
        if (e.target === e.currentTarget && !saving) onClose();
      }}
    >
      <section
        className="sk-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="sk-schedule-title"
      >
        <header className="sk-modal-head">
          <h2 id="sk-schedule-title">Schedule rotation</h2>
          <button
            type="button"
            className="sk-icon-btn"
            aria-label="Close"
            disabled={saving}
            onClick={onClose}
          >
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <path d="m6 6 12 12M18 6 6 18" />
            </svg>
          </button>
        </header>
        <div className="sk-modal-body">
          <p>
            <strong>{serviceKey.name}</strong> gets a new key at the time you choose. You can show
            the new key on this page after it rotates.
          </p>
          <label className="sk-modal-label crm-mt-3">
            Rotate on
            <input
              type="datetime-local"
              min={dateTimeInputValue(new Date())}
              value={value}
              aria-invalid={shownError ? true : undefined}
              aria-describedby={shownError ? 'sk-schedule-error' : undefined}
              onChange={(e) => {
                setValue(e.target.value);
                setTouched(true);
                setServerError(null);
              }}
            />
          </label>
          {shownError || serverError ? (
            <p id="sk-schedule-error" className="sk-form-error crm-mt-2 crm-mb-0" role="alert">
              {shownError ?? serverError}
            </p>
          ) : null}
          <label className="sk-modal-label crm-mt-3">
            Then keep the old key working for
            <select
              className="input"
              value={String(hours)}
              onChange={(e) => setHours(Number(e.target.value))}
            >
              <option value="0">No time: it stops at once</option>
              {OVERLAP_CHOICES.map((c) => (
                <option key={c.hours} value={c.hours}>
                  {c.label}
                </option>
              ))}
            </select>
          </label>
        </div>
        <footer className="sk-modal-foot">
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            disabled={saving}
            onClick={onClose}
          >
            Cancel
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={saving || Boolean(timeError)}
            onClick={() => void save()}
          >
            {saving ? 'Scheduling…' : 'Schedule rotation'}
          </button>
        </footer>
      </section>
    </div>
  );
}
