'use client';

import { useEffect, useState } from 'react';

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

import DepartmentCombobox from './DepartmentCombobox';

const GENDER_OPTIONS = ['Male', 'Female'];

/**
 * Admin edit: name, gender, department — never the work email (PRD §8.4). The
 * design's kebab menu doesn't show an edit entry itself, but the ticket's own
 * acceptance criteria require it, so it's kept here, reachable from the row
 * menu as "Edit details".
 *
 * `employee.name` may be the traveler-profile name once the person has
 * completed setup, not raw first/last — so the name fields here start blank
 * rather than guessing a split that could silently overwrite the wrong half.
 */
export default function EditEmployeeModal({
  token,
  employee,
  departments,
  groups,
  onClose,
  onSaved,
}: {
  token: string;
  employee: EmployeeRow;
  departments: string[];
  /** The company's policy groups, default first (LEIS-975). */
  groups: GroupOption[];
  onClose: () => void;
  onSaved: () => void;
}) {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [gender, setGender] = useState('');
  const [department, setDepartment] = useState(employee.department ?? '');
  // Seeded from the row, which always carries a group — someone who merely
  // FOLLOWS the default still reports it, so this is never blank.
  const [groupId, setGroupId] = useState(employee.group?.id ?? '');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  const submit = async () => {
    if (submitting) return;
    setSubmitting(true);
    setError(null);
    const payload: {
      firstName?: string;
      lastName?: string;
      gender?: string;
      department?: string;
      groupId?: string;
    } = {};
    if (firstName.trim()) payload.firstName = firstName.trim();
    if (lastName.trim()) payload.lastName = lastName.trim();
    if (gender) payload.gender = gender;
    if (department.trim() && department.trim() !== employee.department) payload.department = department.trim();
    // Sent when it differs, OR when the group was only implicit: assigning
    // someone explicitly to the default they already follow is a real change,
    // because it pins them there if the default is ever re-pointed.
    if (groupId && (groupId !== employee.group?.id || employee.groupIsImplicit)) payload.groupId = groupId;

    const res = await updateEmployee(token, employee.id, payload);
    setSubmitting(false);
    if (!res.success) {
      setError(res.message ?? 'We could not save those changes. Please try again.');
      return;
    }
    onSaved();
  };

  return (
    <>
      <div className="modal-backdrop fade show" onClick={onClose} />
      <div className="modal fade show fra-ui fra-modal" role="dialog" aria-modal="true" style={{ display: 'block' }}>
        <div className="modal-dialog modal-dialog-centered">
          <div className="modal-content">
            <div className="fra-modal-head">
              <span className="fra-head-icon">
                <i className="bi bi-pencil" />
              </span>
              <div className="flex-grow-1">
                <h5 className="fra-modal-title">Edit employee</h5>
              </div>
              <button type="button" className="fra-close" onClick={onClose} aria-label="Close">
                <i className="bi bi-x-lg" />
              </button>
            </div>
            <div className="modal-body">
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  submit();
                }}
                noValidate
              >
                <div className="fra-form-section">
                  <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div className="sm:col-span-2">
                      <label className="fra-label" htmlFor="wfeEmail">
                        Work email
                      </label>
                      <input id="wfeEmail" className="fra-input" value={employee.email} disabled />
                    </div>
                    <div>
                      <label className="fra-label" htmlFor="wfeFirst">
                        First name
                      </label>
                      <input
                        id="wfeFirst"
                        className="fra-input"
                        value={firstName}
                        onChange={(e) => setFirstName(e.target.value)}
                        placeholder={employee.name}
                        maxLength={50}
                      />
                    </div>
                    <div>
                      <label className="fra-label" htmlFor="wfeLast">
                        Last name
                      </label>
                      <input
                        id="wfeLast"
                        className="fra-input"
                        value={lastName}
                        onChange={(e) => setLastName(e.target.value)}
                        placeholder="Leave blank to keep unchanged"
                        maxLength={50}
                      />
                    </div>
                    <div>
                      <label className="fra-label" htmlFor="wfeGender">
                        Gender
                      </label>
                      <div className="fra-select-wrap">
                        <select className="fra-input fra-select" id="wfeGender" value={gender} onChange={(e) => setGender(e.target.value)}>
                          <option value="">Leave unchanged</option>
                          {GENDER_OPTIONS.map((g) => (
                            <option key={g} value={g}>
                              {g}
                            </option>
                          ))}
                        </select>
                        <i className="bi bi-chevron-down" />
                      </div>
                    </div>
                    <div>
                      <label className="fra-label" htmlFor="wfeDept">
                        Department
                      </label>
                      <DepartmentCombobox id="wfeDept" value={department} onChange={setDepartment} departments={departments} />
                    </div>
                    <div>
                      <label className="fra-label" htmlFor="wfeGroup">
                        Policy group
                      </label>
                      <div className="fra-select-wrap">
                        <select className="fra-input fra-select" id="wfeGroup" value={groupId} 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>
                      <div className="wf-note">
                        <span>
                          Moving them applies the new rules from their next request. Requests already
                          submitted keep the policy they were judged with.
                        </span>
                      </div>
                    </div>
                  </div>
                </div>

                {error && (
                  <p role="alert" className="mt-1 rounded-[10px] bg-[var(--fra-rejected-bg)] px-3 py-2.5 text-[13px] text-[var(--fra-rejected)]">
                    {error}
                  </p>
                )}
              </form>
            </div>
            <div className="fra-modal-foot">
              <button type="button" className="fra-btn fra-btn-ghost" onClick={onClose}>
                Cancel
              </button>
              <button type="button" className="fra-btn fra-btn-primary" disabled={submitting} onClick={submit}>
                {submitting ? 'Saving…' : 'Save changes'}
              </button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
