'use client';

/**
 * The design's "Generate content" (#mAI) and "Insert video" (#mVideo) dialogs.
 *
 * Insert video: Sign In and Sign up open Vidyard, where the video is recorded; its share link is
 * pasted back here and goes into the template as a thumbnail linked to the video, which needs no
 * Vidyard key.
 *
 * Generate content asks the API for a draft (POST /email-templates/ai/draft). While no AI service
 * is connected on the server it says so, and nothing typed there leaves the page.
 */
import { useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { getAiDraftStatus, writeAiDraft, type AiDraftRequest } from '../api.client';
import { MtIcon, MtModal, MtModalHead, MtSelect } from '@/features/snippets/ui/mt';
import { VIDYARD_SIGN_IN, VIDYARD_SIGN_UP, vidyardVideoId } from '../model';

const AI_TYPES = [
  {
    value: 'intro',
    label: 'Introduction email',
    help: 'Content intended for your inbound leads. Make a connection with leads that have reached out or shown interest right away.',
  },
  {
    value: 'cold',
    label: 'Cold outreach email',
    help: 'Content intended for prospects who have not heard from you yet. Start a conversation and earn a reply.',
  },
  {
    value: 'followup',
    label: 'Follow up email',
    help: 'Content intended for prospects you have already contacted. Keep the conversation moving toward a next step.',
  },
];
const TONES = ['Professional', 'Helpful', 'Witty', 'Formal', 'Optimistic'];

export const AI_NOT_CONNECTED =
  'Generate with AI is not connected yet: no AI service is set up for this CRM.';
const AI_NOTICE =
  'What you type here is sent to OpenAI, our AI provider, to write the draft, so leave out sensitive information. Read and check the draft before you use it.';

export function GenerateContentModal({
  onClose,
  onGenerated,
}: {
  onClose: () => void;
  onGenerated: (draft: { subject: string; bodyHtml: string }) => void;
}) {
  const toast = useToast();
  /** null until the API has said whether AI is connected. */
  const [available, setAvailable] = useState<boolean | null>(null);
  const [writing, setWriting] = useState(false);
  /** A draft that arrives after the dialog was closed is dropped. */
  const open = useRef(true);
  useEffect(() => {
    open.current = true;
    getAiDraftStatus().then(
      (res) => open.current && setAvailable(res.available),
      () => open.current && setAvailable(false),
    );
    return () => {
      open.current = false;
    };
  }, []);
  const [type, setType] = useState(AI_TYPES[0]!.value);
  const [selling, setSelling] = useState('');
  const [audience, setAudience] = useState('');
  const [message, setMessage] = useState('');
  const [tones, setTones] = useState<string[]>([]);
  const valid = !!selling.trim() && !!audience.trim();
  const generate = async () => {
    if (!available) {
      toast(AI_NOT_CONNECTED, 'info');
      return;
    }
    setWriting(true);
    try {
      const draft = await writeAiDraft({
        emailType: type as AiDraftRequest['emailType'],
        selling: selling.trim(),
        audience: audience.trim(),
        ...(message.trim() ? { message: message.trim() } : {}),
        tones,
      });
      if (open.current) onGenerated(draft);
    } catch (err) {
      if (!open.current) return;
      toast(errorText(err), 'danger');
      setWriting(false);
    }
  };
  const text = (
    id: string,
    label: string,
    value: string,
    set: (v: string) => void,
    placeholder: string,
    required: boolean,
  ) => (
    <div className="field">
      <label className="field__label" htmlFor={id}>
        {label} {required ? <span aria-hidden="true">*</span> : null}
      </label>
      <input
        className="input"
        type="text"
        id={id}
        maxLength={300}
        autoComplete="off"
        placeholder={placeholder}
        value={value}
        onChange={(e) => set(e.target.value)}
      />
    </div>
  );
  return (
    <MtModal
      id="mAI"
      onClose={onClose}
      labelledBy="mAIT"
      className="mt-modal--ai"
      focus="#aiSelling"
    >
      <MtModalHead id="mAIT" title="Generate content" onClose={onClose} />
      <div className="mt-modal__body mt-ai">
        <div className="mt-ai__badge">
          <MtIcon name="sparkle" size={14} />
          AI
        </div>
        <div className="field">
          <span className="field__label" id="aiTypeLbl">
            Email type <span aria-hidden="true">*</span>
          </span>
          <MtSelect
            value={type}
            options={AI_TYPES.map((t) => ({ value: t.value, label: t.label }))}
            onChange={setType}
          />
          <p className="mt-text mt-text--muted mt-text--sm" id="aiTypeHelp">
            {AI_TYPES.find((t) => t.value === type)?.help}
          </p>
        </div>
        {text(
          'aiSelling',
          'What are you selling?',
          selling,
          setSelling,
          'Ex: Sales software that increases rep productivity and drives revenue',
          true,
        )}
        {text(
          'aiAudience',
          'Who are you selling to?',
          audience,
          setAudience,
          'Ex: the Chief Sales Officer of Acme, Inc.',
          true,
        )}
        <div className="field">
          <label className="field__label" htmlFor="aiMessage">
            In a few words describe what you want to communicate in this email
          </label>
          <textarea
            className="input mt-textarea"
            id="aiMessage"
            maxLength={1000}
            placeholder={
              'Describe why your product is a great fit for the prospect and include any benefits.\nMention any personal connections or points you want to make.'
            }
            value={message}
            onChange={(e) => setMessage(e.target.value)}
          />
        </div>
        <fieldset className="mt-tones">
          <legend className="field__label">Select the tone of your email</legend>
          <div className="mt-tones__row" id="aiTones">
            {TONES.map((t) => (
              <label key={t} className="check">
                <input
                  type="checkbox"
                  checked={tones.includes(t)}
                  onChange={(e) =>
                    setTones((cur) => (e.target.checked ? [...cur, t] : cur.filter((x) => x !== t)))
                  }
                />
                <span className="check__box" />
                {t}
              </label>
            ))}
          </div>
        </fieldset>
        <p className="mt-text mt-text--muted mt-text--sm" id="aiNotice">
          {available === null
            ? ''
            : available
              ? AI_NOTICE
              : `${AI_NOT_CONNECTED} Nothing you type here is sent anywhere.`}
        </p>
      </div>
      <div className="mt-modal__foot">
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', writing && 'is-loading')}
          id="aiGo"
          disabled={!valid || available === null || writing}
          aria-busy={writing}
          onClick={() => void generate()}
        >
          {writing ? 'Generating…' : 'Generate'}
          <span className="btn-crm__spinner" aria-hidden="true" />
        </button>
      </div>
    </MtModal>
  );
}

export function InsertVideoModal({
  onClose,
  onInsert,
}: {
  onClose: () => void;
  onInsert: (videoId: string, title: string) => void;
}) {
  const [link, setLink] = useState('');
  const [title, setTitle] = useState('');
  const [invalid, setInvalid] = useState(false);
  const openVidyard = (url: string) => window.open(url, '_blank', 'noopener,noreferrer');
  const insert = () => {
    const id = vidyardVideoId(link);
    if (!id) {
      setInvalid(true);
      document.getElementById('vidLink')?.focus();
      return;
    }
    onInsert(id, title.trim() || 'Watch the video');
  };
  return (
    <MtModal
      id="mVideo"
      onClose={onClose}
      labelledBy="mVideoT"
      className="mt-modal--video"
      focus="#vidSignIn"
    >
      <MtModalHead id="mVideoT" title="Insert video" onClose={onClose} />
      <div className="mt-modal__body">
        <div className="mt-vid">
          <div className="mt-vid__logo" aria-label="Vidyard">
            <span className="mt-vid__mark" />
            <span className="mt-vid__word">vidyard</span>
          </div>
          <h3 className="mt-vid__title">Win More With Video</h3>
          <p className="mt-vid__text">
            Add engaging video messages to your emails to capture buyers&apos; attention and close
            deals faster.
          </p>
          <button
            type="button"
            className="btn-crm btn-crm--primary btn-crm--block"
            id="vidSignIn"
            onClick={() => openVidyard(VIDYARD_SIGN_IN)}
          >
            Sign In
          </button>
          <p className="mt-vid__alt">
            Don&apos;t have an account?{' '}
            <button
              type="button"
              className="mt-link-btn"
              id="vidSignUp"
              onClick={() => openVidyard(VIDYARD_SIGN_UP)}
            >
              Sign up
            </button>
          </p>
        </div>
        <div className={cn('field', invalid && 'is-invalid')}>
          <label className="field__label" htmlFor="vidLink">
            Recorded your video? Paste its Vidyard share link
          </label>
          <input
            className="input"
            type="url"
            id="vidLink"
            autoComplete="off"
            placeholder="https://share.vidyard.com/watch/..."
            value={link}
            onChange={(e) => {
              setLink(e.target.value);
              setInvalid(false);
            }}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.preventDefault();
                insert();
              }
            }}
          />
          <p className="field__error">
            Paste a Vidyard video link, like https://share.vidyard.com/watch/…
          </p>
        </div>
        <div className="field">
          <label className="field__label" htmlFor="vidTitle">
            Link text
          </label>
          <input
            className="input"
            type="text"
            id="vidTitle"
            maxLength={200}
            autoComplete="off"
            placeholder="Watch the video"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
        </div>
      </div>
      <div className="mt-modal__foot">
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="vidInsert"
          disabled={!link.trim()}
          onClick={insert}
        >
          Insert video
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
    </MtModal>
  );
}
