'use client';

import { useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { updateContact } from '@/features/contacts/api.client';
import type { ContactWrite } from '@/features/contacts/types';
import { errorText } from '@/lib/api/errors';
import { emailValue, filterCountries, parsePhone, phoneValue, type PhoneCountry } from '../preview';
import { SegModal } from './primitives';

/** Focuses the field shortly after the modal opens (JS:3634, JS:3777). */
function useFocusOnOpen(open: boolean) {
  const ref = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (!open) return;
    const t = window.setTimeout(() => ref.current?.focus(), 80);
    return () => window.clearTimeout(t);
  }, [open]);
  return ref;
}

/** `#vcsEditEmailModal` (PHP:3537-3570, JS:3624-3678): Save PATCHes the primary email. */
export function EditEmailModal({
  open,
  onClose,
  contactId,
  email,
  onSaved,
}: {
  open: boolean;
  onClose: () => void;
  contactId: string;
  email: string | null;
  onSaved: (contact: ContactWrite) => void;
}) {
  const toast = useToast();
  const [value, setValue] = useState(email ?? '');
  const [saving, setSaving] = useState(false);
  const inputRef = useFocusOnOpen(open);

  useEffect(() => {
    if (open) setValue(email ?? '');
  }, [open, email]);

  const save = async () => {
    setSaving(true);
    try {
      const updated = await updateContact(contactId, { email: emailValue(value) });
      onClose();
      toast('Email updated', 'success');
      onSaved(updated);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSaving(false);
    }
  };

  return (
    <SegModal
      open={open}
      onClose={onClose}
      labelledBy="vcsEditEmailTitle"
      id="vcsEditEmailModal"
      overlayClassName="vcs-edit-modal-ov"
      style={{ width: 'min(480px, 100%)' }}
    >
      <header className="lp-modal__head">
        <h2 id="vcsEditEmailTitle">Edit email</h2>
        <button
          type="button"
          className="lp-icon-btn"
          data-vcs-modal-close=""
          id="vcsEditEmailClose"
          aria-label="Close"
          onClick={onClose}
        >
          <CrmIcon name="x" className="iconSize-18" />
        </button>
      </header>
      <div className="lp-modal__body">
        <div className="lp-field">
          <label htmlFor="vcsEditEmailInput">Primary email</label>
          <div className="crm-d-flex crm-gap-2">
            <input
              ref={inputRef}
              type="email"
              className="lp-input"
              id="vcsEditEmailInput"
              value={value}
              onChange={(e) => setValue(e.target.value)}
            />
            <button
              type="button"
              className="lp-btn lp-btn--outline"
              id="vcsDeleteEmailBtn"
              onClick={() => {
                // Only the input empties; nothing is saved until Save, so no status toast.
                setValue('');
                inputRef.current?.focus();
              }}
            >
              Delete
            </button>
          </div>
        </div>
      </div>
      <footer className="lp-modal__foot">
        <div className="lp-modal__acts">
          <button
            type="button"
            className="lp-btn lp-btn--outline"
            data-vcs-modal-close=""
            id="vcsCancelEmailBtn"
            onClick={onClose}
          >
            Cancel
          </button>
          <button
            type="button"
            className="lp-btn lp-btn--primary"
            id="vcsSaveEmailBtn"
            disabled={saving}
            onClick={() => void save()}
          >
            Save
          </button>
        </div>
      </footer>
    </SegModal>
  );
}

const FORMAT_HELP = 'Select a country code and enter a phone number.';
const RAW_HELP = 'Enter the phone number exactly as it should appear.';

/** `#vcsEditPhoneModal` (PHP:3573-3612, JS:3681-3823): Save PATCHes "{prefix} {num} ext. X". */
export function EditPhoneModal({
  open,
  onClose,
  contactId,
  phone,
  onSaved,
}: {
  open: boolean;
  onClose: () => void;
  contactId: string;
  phone: string | null;
  onSaved: (contact: ContactWrite) => void;
}) {
  const toast = useToast();
  const initial = parsePhone(phone);
  const [country, setCountry] = useState<PhoneCountry>(initial.country);
  const [num, setNum] = useState(initial.num);
  const [ext, setExt] = useState(initial.ext);
  const [listOpen, setListOpen] = useState(false);
  const [search, setSearch] = useState('');
  const [formatted, setFormatted] = useState(true);
  const [saving, setSaving] = useState(false);
  const inputRef = useFocusOnOpen(open);
  const searchRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const ccRef = useRef<HTMLButtonElement>(null);

  // Each open starts from the saved phone with the country list closed (JS:3765-3784).
  useEffect(() => {
    if (!open) return;
    const p = parsePhone(phone);
    setCountry(p.country);
    setNum(p.num);
    setExt(p.ext);
    setListOpen(false);
  }, [open, phone]);

  // A mousedown outside the list and its button closes the list (JS:4101-4104).
  useEffect(() => {
    if (!listOpen) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (!listRef.current?.contains(t) && !ccRef.current?.contains(t)) setListOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [listOpen]);

  const close = () => {
    setListOpen(false);
    onClose();
  };

  const save = async () => {
    setSaving(true);
    try {
      const updated = await updateContact(contactId, { phone: phoneValue(country, num, ext) });
      close();
      toast('Phone number updated', 'success');
      onSaved(updated);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSaving(false);
    }
  };

  const countries = filterCountries(search);

  return (
    <SegModal
      open={open}
      onClose={close}
      labelledBy="vcsEditPhoneTitle"
      id="vcsEditPhoneModal"
      overlayClassName="vcs-edit-modal-ov"
      style={{ width: 'min(500px, calc(100vw - 32px))' }}
    >
      <header className="lp-modal__head">
        <h2 id="vcsEditPhoneTitle">Edit Phone Number</h2>
        <button
          type="button"
          className="lp-icon-btn"
          data-vcs-modal-close=""
          id="vcsEditPhoneClose"
          aria-label="Close"
          onClick={close}
        >
          <CrmIcon name="x" className="iconSize-18" />
        </button>
      </header>
      <div className="lp-modal__body">
        <div className="lp-ce-ph__box">
          <div className="lp-ce-ph__row">
            <button
              ref={ccRef}
              type="button"
              className="lp-ce-ph__cc"
              id="vcsPhoneCcBtn"
              aria-haspopup="listbox"
              aria-expanded={listOpen}
              title="Select country code"
              onClick={() => {
                const next = !listOpen;
                setListOpen(next);
                if (next) {
                  setSearch('');
                  window.setTimeout(() => searchRef.current?.focus(), 50);
                }
              }}
            >
              <span className="lp-ce-ph__flag" id="vcsPhoneFlag">
                {country.flag}
              </span>
              <span id="vcsPhonePrefixVal" className="crm-fs-8 crm-fw-600">
                {country.prefix}
              </span>
              <svg className="lp-ce-ph__caret" viewBox="0 0 24 24" aria-hidden="true">
                <path d="M6 9h12l-6 7z" fill="currentColor" />
              </svg>
            </button>
            <input
              ref={inputRef}
              className="lp-ce-ph__num"
              id="vcsEditPhoneInput"
              type="tel"
              autoComplete="off"
              placeholder="(415) 555-0111"
              aria-label="Phone number"
              value={num}
              onChange={(e) => setNum(e.target.value)}
            />
            <input
              className="lp-ce-ph__ext"
              id="vcsEditPhoneExt"
              inputMode="numeric"
              autoComplete="off"
              placeholder="Extension"
              aria-label="Extension"
              value={ext}
              onChange={(e) => setExt(e.target.value)}
            />
          </div>
          <div className="lp-ce-ph__list" id="vcsPhoneCcList" hidden={!listOpen} ref={listRef}>
            <input
              ref={searchRef}
              className="lp-input"
              type="search"
              id="vcsPhoneCcSearch"
              placeholder="Search countries"
              aria-label="Search countries"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
            <div
              className="lp-ce-ph__opts"
              role="listbox"
              id="vcsPhoneCcOpts"
              aria-label="Country code"
            >
              {countries.length ? (
                countries.map((c) => (
                  <button
                    key={c.code}
                    type="button"
                    role="option"
                    aria-selected={c.code === country.code}
                    className={`lp-ce-opt ${c.code === country.code ? 'is-on' : ''}`}
                    data-cc-code={c.code}
                    onClick={() => {
                      setCountry(c);
                      setListOpen(false);
                      inputRef.current?.focus();
                    }}
                  >
                    <span className="lp-ce-ph__f" style={{ fontSize: 16, marginRight: 6 }}>
                      {c.flag}
                    </span>
                    <span style={{ flex: 1 }}>{c.name}</span>
                    <small className="crm-text-muted">{c.prefix}</small>
                  </button>
                ))
              ) : (
                <p className="lp-opt__empty">No countries found</p>
              )}
            </div>
          </div>
          <p className="lp-ce-ph__help" id="vcsPhoneHelp" aria-live="polite">
            {formatted ? FORMAT_HELP : RAW_HELP}
          </p>
        </div>
        <div className="lp-ce-ph__fmt">
          <button
            type="button"
            className="lp-ce-ph__lnk"
            id="vcsTogglePhoneFmt"
            onClick={() => setFormatted((v) => !v)}
          >
            {formatted ? 'Remove number formatting' : 'Apply number formatting'}
          </button>
          <span
            className="lp-ce-ph__info"
            tabIndex={0}
            role="img"
            aria-label="Phone numbers are formatted to match the selected country code."
            data-tip="Phone numbers are formatted to match the selected country code."
          >
            <CrmIcon name="info" className="iconSize-14" />
          </span>
        </div>
      </div>
      <footer className="lp-modal__foot">
        <div className="lp-modal__acts">
          <button
            type="button"
            className="lp-btn lp-btn--outline"
            data-vcs-modal-close=""
            id="vcsCancelPhoneBtn"
            onClick={close}
          >
            Cancel
          </button>
          <button
            type="button"
            className="lp-btn lp-btn--primary"
            id="vcsSavePhoneBtn"
            disabled={saving}
            onClick={() => void save()}
          >
            Save
          </button>
        </div>
      </footer>
    </SegModal>
  );
}
