'use client';

import Link from 'next/link';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  CustomFieldInput,
  toUiValue,
  type CustomUiValue,
} from '@/features/contacts/ui/actions/custom-fields';
import { useUserPrefs } from '@/features/contacts/ui/actions/shared';
import {
  isLockedField,
  listCustomProperties,
  lockedFieldTitle,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { listPropertyGroups, type PropertyGroup } from '@/features/data-model/api.client';
import { getMyMailbox } from '@/features/inbox/api.client';
import type { MyMailbox } from '@/features/inbox/types';
import { getMyCalendar } from '@/features/meetings/api.client';
import type { MyCalendar } from '@/features/meetings/types';
import { getMemberProfile, updateMember, updateMemberProfile } from '@/features/members/api.client';
import { errorText } from '@/lib/api/errors';
import {
  getProfile,
  removeProfilePhoto,
  updateProfile,
  uploadProfilePhoto,
} from '../../api.client';
import type { Profile } from '../../types';
import { useApplyProfile } from '../../UserPrefs';
import { changedUserValues, userFieldGroups } from '../../userFields';
import { ExtIcon, SubNav } from './parts';
import type { PanelProps } from './types';
import { TIME_ZONES, WorkingHoursPanel } from './WorkingHoursPanel';

const SUBS = [
  ['profile', 'Profile'],
  ['working-hours', 'Working hours'],
  ['connected-accounts', 'Connected accounts'],
  ['custom-properties', 'Custom user properties'],
] as const;
export type PreferencesSub = (typeof SUBS)[number][0];
export const isPreferencesSub = (value: string | null): value is PreferencesSub =>
  SUBS.some(([id]) => id === value);

function initials(name: string): string {
  return name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() ?? '')
    .join('');
}

/**
 * Profile sub-tab. The signed-in user edits their own profile and photo. An admin can edit another
 * member's name, phone, time zone and job title (their photo stays with them).
 */
function ProfileSub({
  member,
  self,
  canManage,
  onMember,
}: Pick<PanelProps, 'member' | 'self' | 'canManage' | 'onMember'>) {
  const toast = useToast();
  const applyProfile = useApplyProfile();
  const fileRef = useRef<HTMLInputElement>(null);
  const [profile, setProfile] = useState<Profile | null>(null);
  const [form, setForm] = useState({
    firstName: '',
    lastName: '',
    phone: '',
    mobilePhone: '',
    timezone: '',
    jobTitle: '',
  });
  const [dirty, setDirty] = useState(false);
  const [saving, setSaving] = useState(false);

  const fill = (next: Profile) => {
    setProfile(next);
    setForm({
      firstName: next.firstName ?? '',
      lastName: next.lastName ?? '',
      phone: next.phone ?? '',
      mobilePhone: next.mobilePhone ?? '',
      timezone: next.timezone ?? '',
      jobTitle: next.jobTitle ?? '',
    });
    setDirty(false);
  };

  useEffect(() => {
    (self ? getProfile() : getMemberProfile(member.userId)).then(fill, (err) =>
      toast(errorText(err), 'danger'),
    );
  }, [self, member.userId, toast]);

  const set = (key: keyof typeof form, value: string) => {
    setForm((current) => ({ ...current, [key]: value }));
    setDirty(true);
  };

  const save = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!profile || saving) return;
    setSaving(true);
    try {
      // Names go only when they changed: a user with no first/last split (name only) must not be
      // refused for a phone or time-zone save.
      const namesChanged =
        form.firstName.trim() !== (profile.firstName ?? '') ||
        form.lastName.trim() !== (profile.lastName ?? '');
      const body = {
        ...(namesChanged
          ? { firstName: form.firstName.trim() || null, lastName: form.lastName.trim() || null }
          : {}),
        phone: form.phone.trim() || null,
        mobilePhone: form.mobilePhone.trim() || null,
        timezone: form.timezone || null,
        jobTitle: form.jobTitle.trim() || null,
        updatedAt: profile.updatedAt,
      };
      if (self) {
        const next = await updateProfile(body);
        fill(next);
        applyProfile(next);
      } else {
        const next = await updateMemberProfile(member.userId, body);
        fill(next);
        onMember({ ...member, name: next.name });
      }
      toast('Profile saved', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSaving(false);
    }
  };

  const photo = async (work: () => Promise<Profile>) => {
    try {
      const next = await work();
      setProfile(next);
      applyProfile(next);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  if (!profile) return <p className="up-muted">Loading profile…</p>;

  // A deactivated member's details are read-only here; an admin can edit everyone else's.
  const locked = !self && !canManage;
  const tip = locked ? "Deactivated users can't be edited. Reactivate them first." : undefined;

  return (
    <form
      className="up-form"
      onSubmit={(e) => void save(e)}
      onReset={() => profile && fill(profile)}
    >
      <h2>Profile</h2>
      <p className="up-muted">
        Details about this user. To see changes made to this user&apos;s information, check their{' '}
        <Link href="/settings/audit-log" className="up-link">
          property history
        </Link>
        .
      </p>
      <div className="up-field">
        <label>Profile image</label>
        <div className="up-photo">
          <span className="up-photo__img">
            {self && profile?.hasAvatar ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={`/api/v1/me/profile/avatar?v=${encodeURIComponent(profile.updatedAt)}`}
                alt=""
              />
            ) : (
              initials(member.name)
            )}
          </span>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            disabled={!self}
            title={self ? undefined : 'Only this user can change their photo.'}
            onClick={() => fileRef.current?.click()}
          >
            Upload
          </button>
          {self && profile?.hasAvatar ? (
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              onClick={() => void photo(removeProfilePhoto)}
            >
              Remove
            </button>
          ) : null}
          <input
            ref={fileRef}
            type="file"
            accept="image/*"
            hidden
            onChange={(e) => {
              const file = e.target.files?.[0];
              e.target.value = '';
              if (file) void photo(() => uploadProfilePhoto(file));
            }}
          />
        </div>
      </div>
      <div className="up-field">
        <label htmlFor="up-first">First name</label>
        <input
          className="up-input"
          id="up-first"
          value={form.firstName}
          disabled={locked}
          title={tip}
          onChange={(e) => set('firstName', e.target.value)}
        />
      </div>
      <div className="up-field">
        <label htmlFor="up-last">Last name</label>
        <input
          className="up-input"
          id="up-last"
          value={form.lastName}
          disabled={locked}
          title={tip}
          onChange={(e) => set('lastName', e.target.value)}
        />
      </div>
      <div className="up-field">
        <label htmlFor="up-phone">Main phone</label>
        <small>
          This phone number may be used to contact them about security events, sending workflow SMS,
          and for owner property values.
        </small>
        <input
          className="up-input"
          id="up-phone"
          type="tel"
          placeholder="Phone number"
          value={form.phone}
          disabled={locked}
          title={tip}
          onChange={(e) => set('phone', e.target.value)}
        />
      </div>
      <div className="up-field">
        <label htmlFor="up-phone2">Additional phone</label>
        <input
          className="up-input"
          id="up-phone2"
          type="tel"
          placeholder="Phone number"
          value={form.mobilePhone}
          disabled={locked}
          title={tip}
          onChange={(e) => set('mobilePhone', e.target.value)}
        />
      </div>
      <div className="up-field">
        <label htmlFor="up-tz">Time zone</label>
        <select
          className="up-select"
          id="up-tz"
          value={form.timezone}
          disabled={locked}
          title={tip}
          onChange={(e) => set('timezone', e.target.value)}
        >
          {TIME_ZONES.map(([value, label]) => (
            <option key={value || 'default'} value={value}>
              {label}
            </option>
          ))}
          {form.timezone && !TIME_ZONES.some(([value]) => value === form.timezone) ? (
            <option value={form.timezone}>{form.timezone}</option>
          ) : null}
        </select>
      </div>
      <div className="up-field">
        <label htmlFor="up-job">Job title</label>
        <input
          className="up-input"
          id="up-job"
          value={form.jobTitle}
          disabled={locked}
          title={tip}
          onChange={(e) => set('jobTitle', e.target.value)}
        />
      </div>
      {locked ? (
        <p className="up-note">
          This user is deactivated, so their details can&apos;t be changed here. Reactivate them to
          edit.
        </p>
      ) : null}
      {dirty ? (
        <div className="up-savebar">
          <span>You have unsaved changes</span>
          <button type="submit" className="btn-crm btn-crm--primary btn-crm--sm" disabled={saving}>
            {saving ? 'Saving…' : 'Save'}
          </button>
          <button type="reset" className="btn-crm btn-crm--outline btn-crm--sm">
            Cancel
          </button>
        </div>
      ) : null}
    </form>
  );
}

function connectionStatus(
  connected: boolean,
  status: MyMailbox['status'] | MyCalendar['status'],
): string {
  if (!connected) return 'Not connected';
  if (status === 'syncing') return 'Syncing';
  if (status === 'needs_reauth') return 'Reconnect needed';
  if (status === 'error') return 'Error, check the connection';
  if (status === 'disconnected') return 'Disconnected';
  return 'Connected';
}

/**
 * Connected accounts. A person's Gmail and calendar belong to them alone (AGENTS.md "user-private
 * data"), so an admin sees only that they exist for their own page, not for anyone else.
 */
function ConnectedSub({ self }: { self: boolean }) {
  const [mailbox, setMailbox] = useState<MyMailbox | null>(null);
  const [calendar, setCalendar] = useState<MyCalendar | null>(null);

  useEffect(() => {
    if (!self) return;
    getMyMailbox().then(setMailbox, () =>
      setMailbox({
        connected: false,
        emailAddress: null,
        status: null,
        lastSyncedAt: null,
        lastError: null,
      }),
    );
    getMyCalendar().then(setCalendar, () =>
      setCalendar({
        connected: false,
        emailAddress: null,
        status: null,
        lastSyncedAt: null,
        lastError: null,
      }),
    );
  }, [self]);

  if (!self) {
    return (
      <div>
        <h2>Connected accounts</h2>
        <p className="up-note">
          Each person connects their own Gmail and Google Calendar, and only they can see them. They
          are not shown to admins.
        </p>
      </div>
    );
  }

  return (
    <div>
      <h2>Connected accounts</h2>
      <h3>Email</h3>
      <p className="up-muted">
        Personal email accounts connected to log, track, send, and receive emails.
      </p>
      <table className="up-table">
        <thead>
          <tr>
            <th>Email</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>{mailbox?.emailAddress ?? (mailbox ? 'None' : 'Loading…')}</td>
            <td>{mailbox ? connectionStatus(mailbox.connected, mailbox.status) : '…'}</td>
          </tr>
        </tbody>
      </table>
      <h3>Calendar</h3>
      <p className="up-muted">
        Personal calendar connected to use Meetings, calendar sync and scheduling pages.
      </p>
      <table className="up-table">
        <thead>
          <tr>
            <th>Account</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>{calendar?.emailAddress ?? (calendar ? 'None' : 'Loading…')}</td>
            <td>{calendar ? connectionStatus(calendar.connected, calendar.status) : '…'}</td>
          </tr>
        </tbody>
      </table>
      <Link href="/settings/profile" className="up-link">
        Connect or change accounts in your profile <ExtIcon />
      </Link>
    </div>
  );
}

function PropertiesSub({ member, canManage, onMember }: PanelProps) {
  const toast = useToast();
  const prefs = useUserPrefs();
  const [defs, setDefs] = useState<CustomPropertyDefinition[] | null>([]);
  const [groups, setGroups] = useState<PropertyGroup[]>([]);
  const [edits, setEdits] = useState<Record<string, CustomUiValue>>({});
  const [query, setQuery] = useState('');
  const [hideBlank, setHideBlank] = useState(false);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    listCustomProperties({ objectType: 'user' }).then(
      (list) => setDefs(list.filter((d) => !d.archived)),
      () => setDefs(null),
    );
    listPropertyGroups({ objectType: 'user' }).then(setGroups, () => setGroups([]));
  }, []);

  const value = (def: CustomPropertyDefinition) =>
    edits[def.name] ?? toUiValue(def, member.customProperties?.[def.name], prefs.timeZone);

  const fields = useMemo(() => {
    const needle = query.trim().toLowerCase();
    return userFieldGroups(defs ?? [], groups).flatMap((group) =>
      group.fields.filter((def) => {
        if (needle && !def.label.toLowerCase().includes(needle)) return false;
        if (hideBlank) {
          const raw = member.customProperties?.[def.name];
          if (raw === undefined || raw === null || raw === '') return false;
        }
        return true;
      }),
    );
  }, [defs, groups, hideBlank, member.customProperties, query]);

  const save = async () => {
    const changed = changedUserValues(defs ?? [], edits, member, prefs.timeZone);
    if ('error' in changed) {
      toast(changed.error, 'danger');
      return;
    }
    if (!Object.keys(changed.values).length) return;
    setSaving(true);
    try {
      onMember(await updateMember(member.userId, { customProperties: changed.values }));
      setEdits({});
      toast('Properties saved', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div>
      <h2>Custom user properties</h2>
      <p className="up-muted">
        Properties are used to collect and store information about users. You can use properties to
        create custom automation or reports. To create additional user properties, go to{' '}
        <Link href="/settings/properties?object=user" className="up-link">
          Properties
        </Link>
        . To see changes made to this user&apos;s information, check their{' '}
        <Link href="/settings/audit-log" className="up-link">
          property history
        </Link>
        .
      </p>
      <div className="up-filterbar">
        <label className="up-search up-search--wide">
          <input
            type="search"
            placeholder="Search properties"
            aria-label="Search properties"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </label>
        <label className="up-check">
          <input
            type="checkbox"
            checked={hideBlank}
            onChange={(e) => setHideBlank(e.target.checked)}
          />{' '}
          Hide blank properties
        </label>
      </div>
      {defs === null ? (
        <p className="up-note" role="alert">
          User properties could not be loaded.
        </p>
      ) : fields.length === 0 ? (
        <div className="up-empty">
          <strong>
            {query || hideBlank
              ? 'No custom user properties match your search.'
              : 'No custom user properties yet.'}
          </strong>
        </div>
      ) : (
        <div className="up-props">
          {fields.map((def) => {
            const id = `up-prop-${def.name}`;
            const locked = isLockedField(def) || !canManage;
            return (
              <div className="up-field" key={def.id}>
                <label htmlFor={id}>{def.label}</label>
                <fieldset className="up-fieldset" disabled={locked}>
                  <CustomFieldInput
                    def={def}
                    id={id}
                    value={value(def)}
                    onChange={(next) => setEdits((current) => ({ ...current, [def.name]: next }))}
                  />
                </fieldset>
                {isLockedField(def) ? <small>{lockedFieldTitle(def) ?? 'Read-only'}</small> : null}
              </div>
            );
          })}
        </div>
      )}
      {canManage && Object.keys(edits).length > 0 ? (
        <div className="up-savebar">
          <span>You have unsaved changes</span>
          <button
            type="button"
            className="btn-crm btn-crm--primary btn-crm--sm"
            disabled={saving}
            onClick={() => void save()}
          >
            {saving ? 'Saving…' : 'Save'}
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => setEdits({})}
          >
            Cancel
          </button>
        </div>
      ) : null}
      <Link href="/settings/properties?object=user" className="up-link">
        Manage user properties <ExtIcon />
      </Link>
    </div>
  );
}

/** Preferences tab (design user-details.php `data-up-panel="preferences"`). */
export function PreferencesPanel({
  sub,
  onSub,
  onHours,
  ...panel
}: PanelProps & {
  sub: PreferencesSub;
  onSub: (sub: PreferencesSub) => void;
  onHours: (rows: import('../../types').WorkingHourRow[]) => void;
}) {
  return (
    <section className="up-panel">
      <div className="up-split">
        <SubNav items={SUBS} value={sub} onChange={onSub} />
        <div className="up-subpanels">
          {sub === 'profile' ? (
            <ProfileSub
              member={panel.member}
              self={panel.self}
              canManage={panel.canManage}
              onMember={panel.onMember}
            />
          ) : null}
          {sub === 'working-hours' ? (
            <WorkingHoursPanel
              self={panel.self}
              userId={panel.member.userId}
              editable={panel.self || panel.canManage}
              onSaved={onHours}
            />
          ) : null}
          {sub === 'connected-accounts' ? <ConnectedSub self={panel.self} /> : null}
          {sub === 'custom-properties' ? <PropertiesSub {...panel} /> : null}
        </div>
      </div>
    </section>
  );
}
