'use client';

import { useEffect, useState } from 'react';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import type { CrmList } from '@/features/lists/api.client';
import { errorText } from '@/lib/api/errors';
import { LIST_NAME_MAX, cloneName, cloneSegment } from '../actions';

/**
 * QA #628: Clone (the segment page's header and the Segments index row menu) asks for the copy's
 * name first, "Copy of <name>" to start with, then makes the copy (`cloneSegment`). Open while
 * `source` is set; a failure toasts and keeps the dialog open.
 */
export function CloneSegmentModal({
  source,
  onClose,
  onCloned,
}: {
  source: CrmList | null;
  onClose: () => void;
  onCloned: (result: { list: CrmList; copied: number }, source: CrmList) => void;
}) {
  const toast = useToast();
  const [name, setName] = useState('');
  const [busy, setBusy] = useState(false);
  // The design's clone builder (segments.php `.seg-clone-name-error`): shown on Clone, not a
  // disabled button.
  const [nameError, setNameError] = useState(false);

  useEffect(() => {
    if (source) {
      setName(cloneName(source.name));
      setNameError(false);
    }
  }, [source]);

  const close = () => {
    if (!busy) onClose();
  };

  const submit = async () => {
    if (!source || busy) return;
    if (!name.trim()) {
      setNameError(true);
      return;
    }
    setBusy(true);
    try {
      onCloned(await cloneSegment(source, name), source);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  return (
    <CrmModal id="segCloneModal" open={source !== null} onClose={close}>
      <ModalHeader id="segCloneModal" title="Clone segment" onClose={close} />
      <form
        onSubmit={(e) => {
          e.preventDefault();
          void submit();
        }}
      >
        <div className="modal__body">
          {/* base.css `.field` / `.input`: the segment page doesn't load the index's `.crm-input`. */}
          <div className="field">
            <label className="field__label" htmlFor="segCloneNameInput">
              Segment name
            </label>
            <input
              type="text"
              className="input"
              id="segCloneNameInput"
              maxLength={LIST_NAME_MAX}
              placeholder="Name your new segment"
              value={name}
              aria-invalid={nameError || undefined}
              aria-describedby={nameError ? 'segCloneNameError' : undefined}
              onChange={(e) => {
                setName(e.target.value);
                if (e.target.value.trim()) setNameError(false);
              }}
            />
            {nameError ? (
              <div className="seg-clone-name-error" id="segCloneNameError">
                Please name this segment before saving it.
              </div>
            ) : null}
          </div>
          <p className="lp-muted crm-fs-8">
            {source?.listType === 'static'
              ? 'The copy gets the members of this segment you can see.'
              : 'The copy keeps the filters of this segment.'}
          </p>
        </div>
        <div className="modal__footer">
          <button type="submit" className="lp-btn lp-btn--primary" disabled={busy}>
            {busy ? 'Cloning…' : 'Clone'}
          </button>
          <button type="button" className="lp-btn lp-btn--outline" disabled={busy} onClick={close}>
            Cancel
          </button>
        </div>
      </form>
    </CrmModal>
  );
}
