import React, { useEffect, useState } from 'react';

import { languageLabel } from './helpers';
import LanguageMultiSelect from './LanguageMultiSelect';
import Modal from './Modal';

/** Most additional languages a merchant may add on top of the primary one. */
const MAX_ADDITIONAL_LANGUAGES = 2;

/** Props for {@link GenerateLanguagesDialog}. */
interface GenerateLanguagesDialogProps {
  open: boolean;
  onOpenChange: (next: boolean) => void;
  /** The article's primary language (brand / suggestion). Always generated. */
  primaryLanguage: string;
  /** Disable controls while the dispatch is in flight. */
  busy?: boolean;
  /**
   * Fired with the full language list (primary first, then the chosen extras)
   * when the merchant confirms. The caller dispatches generation with it.
   */
  onConfirm: (languages: string[]) => void;
}

/**
 * Asked right before an article is generated: keep the primary language and
 * optionally add up to two more so the same topic is written in several
 * languages at once (the rows are linked for the in-article language-version
 * switcher). Adding none generates a single-language article as before.
 *
 * @param props {GenerateLanguagesDialogProps} Dialog props.
 * @returns {JSX.Element} The dialog.
 */
const GenerateLanguagesDialog = ({
  open,
  onOpenChange,
  primaryLanguage,
  busy = false,
  onConfirm,
}: GenerateLanguagesDialogProps): JSX.Element => {
  const primary = (primaryLanguage || 'en').toLowerCase();
  const [additional, setAdditional] = useState<string[]>([]);

  // Reset the extra-language picks each time the dialog opens so a previous
  // article's choice never leaks into the next generation.
  useEffect(() => {
    if (open) setAdditional([]);
  }, [open]);

  const handleConfirm = (): void => {
    onConfirm([primary, ...additional]);
  };

  const primaryLabel = languageLabel(primary);

  return (
    <Modal
      open={open}
      onClose={() => onOpenChange(false)}
      title="Generate content"
      size="sm"
      footer={
        <>
          <button
            type="button"
            onClick={() => onOpenChange(false)}
            disabled={busy}
            className="rounded-md border border-gray-300 bg-white px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-60"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleConfirm}
            disabled={busy}
            className="rounded-md bg-black px-3 py-1.5 text-sm font-medium text-white hover:bg-gray-800 disabled:opacity-60"
          >
            {busy
              ? 'Starting…'
              : additional.length
                ? `Generate in ${additional.length + 1} languages`
                : 'Generate'}
          </button>
        </>
      }
    >
      <div className="flex flex-col gap-3">
        <p className="text-sm text-gray-600">
          Also generate this content in other languages? Optional, up to{' '}
          {MAX_ADDITIONAL_LANGUAGES} more. Each version is linked so you can
          switch between them from the content.
        </p>

        <div className="flex flex-col gap-1.5">
          <span className="text-sm font-medium text-gray-900">
            Primary language
          </span>
          <div>
            <span className="inline-flex items-center rounded-full border border-gray-300 bg-gray-50 px-2.5 py-1 text-xs text-gray-900">
              {primaryLabel}
            </span>
          </div>
        </div>

        <div className="flex flex-col gap-1.5">
          <span className="text-sm font-medium text-gray-900">
            Additional languages (optional)
          </span>
          <LanguageMultiSelect
            value={additional}
            onChange={setAdditional}
            max={MAX_ADDITIONAL_LANGUAGES}
            exclude={[primary]}
            disabled={busy}
          />
        </div>
      </div>
    </Modal>
  );
};

export default GenerateLanguagesDialog;
