'use client';

import { useEffect, useState } from 'react';

import { inviteEmployee, type GroupOption } from '@/services/workforce/workforce.client';

import DepartmentCombobox from './DepartmentCombobox';
import { isNetworkFailure, isSessionExpired, toastApiError } from '@/lib/api-error';

/**
 * Is this failure something the EMAIL FIELD should say?
 *
 * Only a server answer about that address — already invited, already an
 * employee, rejected domain. A session or network failure is about neither the
 * field nor its value, and belongs in a toast.
 */
function isAboutTheEmail(result: { status?: number; code?: string; message?: string }): result is { message: string } {
  if (isSessionExpired(result) || isNetworkFailure(result)) return false;
  return Boolean(result.message?.trim());
}


const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const MSG = {
  gender: 'Select a gender.',
  first: 'Enter a first name.',
  last: 'Enter a last name.',
  emailEmpty: 'Enter a work email.',
  emailInvalid: 'Enter a valid email address.',
  dept: 'Enter a department name.',
  tooLong: 'Names can be up to 50 characters.',
};

type Field = 'gender' | 'first' | 'last' | 'email' | 'department';

/** Invite via email (overlay), LEIS-948 — ported from the design's own markup
 *  and validation copy (workforce.php / workforce.js initInvite). Grid uses
 *  Tailwind, not Bootstrap's `.row`/`.col-*` — this app never loads full
 *  Bootstrap CSS on admin routes, only a trimmed modal-positioning subset. */
export default function InviteModal({
  token,
  departments,
  groups,
  onClose,
  onInvited,
}: {
  token: string;
  departments: string[];
  /** The company's policy groups, default first (LEIS-975). */
  groups: GroupOption[];
  onClose: () => void;
  onInvited: (email: string) => void;
}) {
  const [gender, setGender] = useState('');
  const [first, setFirst] = useState('');
  const [last, setLast] = useState('');
  const [email, setEmail] = useState('');
  const [department, setDepartment] = useState('');
  // PRD §8.4: "Group (required), pre-selected to All employees".
  //
  // Held as "" meaning "whatever the default is", and RESOLVED at render
  // rather than seeded by an effect — the groups load alongside the page and
  // can arrive after this modal mounts, and `setState` in an effect to catch
  // that is the cascading-render shape the React Compiler lint rejects.
  const [groupId, setGroupId] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [errors, setErrors] = useState<Partial<Record<Field, string>>>({});

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  const clear = (f: Field) => setErrors((e) => (e[f] ? { ...e, [f]: undefined } : e));

  // The pre-selection, derived: the default group, else the first one. Never
  // empty once the list has loaded, so Group needs no validation of its own.
  const selectedGroupId = groupId || (groups.find((g) => g.isDefault) ?? groups[0])?.id || '';

  const validate = (): Partial<Record<Field, string>> => {
    const e: Partial<Record<Field, string>> = {};
    if (!gender) e.gender = MSG.gender;
    if (!first.trim()) e.first = MSG.first;
    else if (first.trim().length > 50) e.first = MSG.tooLong;
    if (!last.trim()) e.last = MSG.last;
    else if (last.trim().length > 50) e.last = MSG.tooLong;
    if (!email.trim()) e.email = MSG.emailEmpty;
    else if (!EMAIL_PATTERN.test(email.trim())) e.email = MSG.emailInvalid;
    if (!department.trim()) e.department = MSG.dept;
    return e;
  };

  const submit = async () => {
    if (submitting) return;
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length > 0) return;

    setSubmitting(true);
    const normalizedEmail = email.trim().toLowerCase();
    const res = await inviteEmployee(token, {
      gender,
      firstName: first.trim(),
      lastName: last.trim(),
      workEmail: normalizedEmail,
      department: department.trim(),
      // Omitted rather than sent empty: the server then falls back to the
      // default group, which is the right answer if the list never loaded.
      ...(selectedGroupId ? { groupId: selectedGroupId } : {}),
    });
    setSubmitting(false);
    if (!res.success) {
      // An "already invited / already registered" answer is ABOUT the email, so
      // it belongs on that field — the same spot the form's own duplicate check
      // uses. Anything else is not: putting "We could not reach the server" or
      // "Your session has expired" under the email box blames a value that is
      // perfectly fine and hides what actually went wrong.
      if (isAboutTheEmail(res)) {
        setErrors({ email: res.message });
        return;
      }
      toastApiError(res, {
        fallback: 'We could not send that invite. Please try again.',
        id: 'workforce-invite',
      });
      return;
    }
    onInvited(normalizedEmail);
  };

  return (
    <>
      <div className="modal-backdrop fade show" onClick={onClose} />
      <div className="modal fade show fra-ui fra-modal" id="wfInviteModal" role="dialog" aria-modal="true" style={{ display: 'block' }}>
        <div className="modal-dialog modal-dialog-centered modal-dialog-scrollable">
          <form
            className="modal-content"
            noValidate
            onSubmit={(e) => {
              e.preventDefault();
              submit();
            }}
          >
            <div className="fra-modal-head">
              <span className="fra-head-icon">
                <i className="bi bi-envelope-plus" />
              </span>
              <div className="flex-grow-1">
                <h5 className="fra-modal-title">Invite via email</h5>
                <small className="fra-muted">They&apos;ll get an email with a link to set up their account.</small>
              </div>
              <button type="button" className="fra-close" onClick={onClose} aria-label="Close">
                <i className="bi bi-x-lg" />
              </button>
            </div>
            <div className="modal-body">
              <div className="fra-form-section">
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                  <div>
                    <label className="fra-label" htmlFor="wfFirst">
                      First name <em>*</em>
                    </label>
                    <input
                      type="text"
                      className={`fra-input${errors.first ? ' is-invalid' : ''}`}
                      id="wfFirst"
                      maxLength={50}
                      placeholder="e.g. Emily"
                      autoComplete="off"
                      value={first}
                      onChange={(e) => {
                        setFirst(e.target.value);
                        clear('first');
                      }}
                    />
                    {errors.first && <div className="wf-error show">{errors.first}</div>}
                  </div>
                  <div>
                    <label className="fra-label" htmlFor="wfLast">
                      Last name <em>*</em>
                    </label>
                    <input
                      type="text"
                      className={`fra-input${errors.last ? ' is-invalid' : ''}`}
                      id="wfLast"
                      maxLength={50}
                      placeholder="e.g. Carter"
                      autoComplete="off"
                      value={last}
                      onChange={(e) => {
                        setLast(e.target.value);
                        clear('last');
                      }}
                    />
                    {errors.last && <div className="wf-error show">{errors.last}</div>}
                  </div>
                  <div className="sm:col-span-2">
                    <label className="fra-label" htmlFor="wfEmail">
                      Work email <em>*</em>
                    </label>
                    <div className="fra-input-icon">
                      <i className="bi bi-envelope" />
                      <input
                        type="email"
                        className={`fra-input${errors.email ? ' is-invalid' : ''}`}
                        id="wfEmail"
                        placeholder="name@company.com"
                        autoComplete="off"
                        value={email}
                        onChange={(e) => {
                          setEmail(e.target.value);
                          clear('email');
                        }}
                      />
                    </div>
                    {errors.email && <div className="wf-error show">{errors.email}</div>}
                  </div>
                  <div>
                    <label className="fra-label" htmlFor="wfGender">
                      Gender <em>*</em>
                    </label>
                    <div className="fra-select-wrap">
                      <select
                        className={`fra-input fra-select${errors.gender ? ' is-invalid' : ''}`}
                        id="wfGender"
                        value={gender}
                        onChange={(e) => {
                          setGender(e.target.value);
                          clear('gender');
                        }}
                      >
                        <option value="">Select gender</option>
                        <option>Male</option>
                        <option>Female</option>
                      </select>
                      <i className="bi bi-chevron-down" />
                    </div>
                    {errors.gender && <div className="wf-error show">{errors.gender}</div>}
                  </div>
                  <div>
                    <label className="fra-label" htmlFor="wfDeptInput">
                      Department name <em>*</em>
                    </label>
                    <DepartmentCombobox
                      id="wfDeptInput"
                      value={department}
                      onChange={(v) => {
                        setDepartment(v);
                        clear('department');
                      }}
                      departments={departments}
                      invalid={Boolean(errors.department)}
                    />
                    {errors.department && <div className="wf-error show">{errors.department}</div>}
                  </div>
                  <div>
                    <label className="fra-label" htmlFor="wfGroup">
                      Policy group <em>*</em>
                    </label>
                    <div className="fra-select-wrap">
                      <select
                        className="fra-input fra-select"
                        id="wfGroup"
                        value={selectedGroupId}
                        onChange={(e) => setGroupId(e.target.value)}
                      >
                        {groups.map((g) => (
                          <option value={g.id} key={g.id}>
                            {g.name}
                            {g.isDefault ? ' (default)' : ''}
                          </option>
                        ))}
                      </select>
                      <i className="bi bi-chevron-down" />
                    </div>
                    {/* `.wf-note` is the design's own helper-text class; there is no `wf-hint`. */}
                    <div className="wf-note">
                      <span>Decides which travel rules apply to them. You can change it later.</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div className="fra-modal-foot">
              <button type="button" className="fra-btn fra-btn-ghost fra-btn-fixed" onClick={onClose}>
                Cancel
              </button>
              <button type="submit" className="fra-btn fra-btn-primary fra-btn-fixed" disabled={submitting}>
                <i className="bi bi-send" />
                <span>{submitting ? 'Sending…' : 'Send invite'}</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </>
  );
}
