'use client';

import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, Field, ModalHeader } from '@/components/crm/FormDrawer';
import { updateSequence } from '@/features/sequences/api.client';
import type {
  Sequence,
  SequenceProblem,
  SequenceSettings,
  SequenceVisibility,
} from '@/features/sequences/types';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { problemLabel, problemsFromError } from './shared';

type Weekday = SequenceSettings['sendWindow']['days'][number];

const WEEKDAYS: Array<{ value: Weekday; label: string }> = [
  { value: 'mon', label: 'Mon' },
  { value: 'tue', label: 'Tue' },
  { value: 'wed', label: 'Wed' },
  { value: 'thu', label: 'Thu' },
  { value: 'fri', label: 'Fri' },
  { value: 'sat', label: 'Sat' },
  { value: 'sun', label: 'Sun' },
];

const minutesOf = (time: string) => {
  const [h, m] = time.split(':').map(Number);
  return (h ?? 0) * 60 + (m ?? 0);
};

const TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/;

/**
 * Sequence settings (design: sequences.php "seqSettingsModal"): name, who can use it, the sending
 * window (days, hours, timezone, holidays), unsubscribe link and who gets the tasks (no daily
 * limit of its own: Sequences, as HubSpot).
 * Saved with PATCH /sequences/:id `{ name?, visibility?, settings, updatedAt }`.
 */
export function SequenceSettingsDrawer({
  open,
  sequence,
  onClose,
  onSaved,
}: {
  open: boolean;
  sequence: Sequence;
  onClose: () => void;
  onSaved: (updated: Sequence) => void;
}) {
  const [name, setName] = useState(sequence.name);
  const [visibility, setVisibility] = useState<SequenceVisibility>(sequence.visibility);
  const [settings, setSettings] = useState<SequenceSettings>(sequence.settings);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [problems, setProblems] = useState<SequenceProblem[]>([]);

  // Start from the saved values each time the drawer opens.
  useEffect(() => {
    if (!open) return;
    setName(sequence.name);
    setVisibility(sequence.visibility);
    setSettings(sequence.settings);
    setError(null);
    setProblems([]);
  }, [open, sequence]);

  const window_ = settings.sendWindow;
  const setWindow = (patch: Partial<SequenceSettings['sendWindow']>) =>
    setSettings((s) => ({ ...s, sendWindow: { ...s.sendWindow, ...patch } }));

  const toggleDay = (day: Weekday, on: boolean) => {
    const next = on ? [...window_.days, day] : window_.days.filter((d) => d !== day);
    // Keep the week order the API echoes back.
    setWindow({ days: WEEKDAYS.map((d) => d.value).filter((d) => next.includes(d)) });
  };

  const nameBad = !name.trim();
  const daysBad = window_.days.length === 0;
  const timeBad =
    !TIME_RE.test(window_.startTime) ||
    !TIME_RE.test(window_.endTime) ||
    minutesOf(window_.endTime) <= minutesOf(window_.startTime);
  const canEdit = sequence.canEdit;

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    if (busy || !canEdit) return;
    if (nameBad || daysBad || timeBad) {
      setError('Fix the highlighted fields first.');
      return;
    }
    setBusy(true);
    setError(null);
    setProblems([]);
    try {
      const updated = await updateSequence(sequence.id, {
        updatedAt: sequence.updatedAt,
        ...(name.trim() !== sequence.name && { name: name.trim() }),
        ...(visibility !== sequence.visibility && { visibility }),
        settings,
      });
      onSaved(updated);
      onClose();
    } catch (err) {
      if (isApiError(err) && err.isConflict) {
        setError('This sequence changed since you loaded it. Reload the page and try again.');
      } else {
        setError(errorText(err));
        setProblems(problemsFromError(err) ?? []);
      }
    } finally {
      setBusy(false);
    }
  };

  return (
    <CrmModal id="seqSettingsModal" open={open} onClose={busy ? () => {} : onClose} drawer>
      <form noValidate onSubmit={save}>
        <ModalHeader id="seqSettingsModal" title="Sequence settings" onClose={onClose} />
        <div className="modal__body">
          {!canEdit ? (
            <Alert tone="warning">Only the owner or a sequence manager can change these.</Alert>
          ) : null}
          {error ? (
            <Alert tone="danger">
              {error}
              {problems.length ? (
                <ul className="crm-mb-0 crm-mt-1 crm-ps-3">
                  {problems.map((p, i) => (
                    <li key={`${p.field}-${i}`}>
                      {problemLabel(p.field, sequence.steps)}: {p.message}
                    </li>
                  ))}
                </ul>
              ) : null}
            </Alert>
          ) : null}

          <div className="form-grid">
            <Field
              label="Sequence name"
              htmlFor="seqSettingsName"
              className={cn('span-2', nameBad && 'is-invalid')}
            >
              <input
                id="seqSettingsName"
                className="input"
                value={name}
                maxLength={191}
                disabled={!canEdit}
                onChange={(e) => setName(e.target.value)}
              />
            </Field>

            <Field label="Who can use it" htmlFor="seqSettingsVisibility" className="span-2">
              <select
                id="seqSettingsVisibility"
                className="select"
                value={visibility}
                disabled={!canEdit}
                onChange={(e) => setVisibility(e.target.value as SequenceVisibility)}
              >
                <option value="personal">Only me (personal)</option>
                <option value="shared">Everyone in the team (shared)</option>
              </select>
            </Field>

            <Field
              label="Send on"
              className={cn('span-2', daysBad && 'is-invalid')}
              error="Pick at least one day."
            >
              <div className="crm-d-flex crm-flex-wrap crm-gap-3">
                {WEEKDAYS.map((day) => (
                  <label key={day.value} className="check">
                    <input
                      type="checkbox"
                      checked={window_.days.includes(day.value)}
                      disabled={!canEdit}
                      onChange={(e) => toggleDay(day.value, e.target.checked)}
                    />
                    <span className="check__box" aria-hidden />
                    <span>{day.label}</span>
                  </label>
                ))}
              </div>
            </Field>

            <Field
              label="From"
              htmlFor="seqSettingsStart"
              className={cn(timeBad && 'is-invalid')}
              error="Use HH:MM, before the end time."
            >
              <input
                id="seqSettingsStart"
                className="input"
                type="time"
                value={window_.startTime}
                disabled={!canEdit}
                onChange={(e) => setWindow({ startTime: e.target.value })}
              />
            </Field>
            <Field
              label="Until"
              htmlFor="seqSettingsEnd"
              className={cn(timeBad && 'is-invalid')}
              error="Must be after the start time."
            >
              <input
                id="seqSettingsEnd"
                className="input"
                type="time"
                value={window_.endTime}
                disabled={!canEdit}
                onChange={(e) => setWindow({ endTime: e.target.value })}
              />
            </Field>

            <Field label="In the time zone of" htmlFor="seqSettingsTz" className="span-2">
              <select
                id="seqSettingsTz"
                className="select"
                value={window_.timezone}
                disabled={!canEdit}
                onChange={(e) => setWindow({ timezone: e.target.value as 'contact' | 'owner' })}
              >
                <option value="owner">The sender (the person who enrolls)</option>
                <option value="contact">The contact (falls back to the sender&apos;s)</option>
              </select>
            </Field>

            <label className="check span-2">
              <input
                type="checkbox"
                checked={window_.skipHolidays}
                disabled={!canEdit}
                onChange={(e) => setWindow({ skipHolidays: e.target.checked })}
              />
              <span className="check__box" aria-hidden />
              <span>Skip holidays (company holidays and US federal holidays)</span>
            </label>

            <label className="check span-2">
              <input
                type="checkbox"
                checked={settings.unsubscribeLink}
                disabled={!canEdit}
                onChange={(e) => setSettings((s) => ({ ...s, unsubscribeLink: e.target.checked }))}
              />
              <span className="check__box" aria-hidden />
              <span>Add an unsubscribe link to automatic emails</span>
            </label>

            <Field label="Assign tasks to" htmlFor="seqSettingsTasks" className="span-2">
              <select
                id="seqSettingsTasks"
                className="select"
                value={settings.taskAssignment}
                disabled={!canEdit}
                onChange={(e) =>
                  setSettings((s) => ({
                    ...s,
                    taskAssignment: e.target.value as SequenceSettings['taskAssignment'],
                  }))
                }
              >
                <option value="sender">The person who enrolls the contact</option>
                <option value="contact_owner">The contact&apos;s owner</option>
              </select>
            </Field>
          </div>
        </div>
        <div className="modal__footer">
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="submit"
            className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
            aria-busy={busy}
            disabled={busy || !canEdit}
          >
            Save settings
          </button>
        </div>
      </form>
    </CrmModal>
  );
}
