'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useToast } from '@/components/crm/ToastProvider';
import { formatUserDate, type ReadableContext } from '@/features/activities/readable';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { recordRights } from '@/features/auth/record-access';
import { createContact, deleteContact, getContact } from '@/features/contacts/api.client';
import { cloneContactBody } from '@/features/contacts/clone';
import type { Contact, ContactListItem } from '@/features/contacts/types';
import { ContactPreviewActions } from '@/features/contacts/ui/ContactPreviewActions';
import { ContactPreviewCards } from '@/features/contacts/ui/ContactPreviewCards';
import type { CellEditor } from '@/features/list-page/ui/CellEdit';
import { DeleteRecordsDialog, recordsText } from '@/features/list-page/ui/DeleteRecordsDialog';
import { PreviewValue } from '@/features/list-page/ui/PreviewValue';
import { LpIcon, type LpIconName } from '@/features/list-page/ui/LpIcon';
import { LpMenu, LpPopover } from '@/features/list-page/ui/LpPopover';
import { Avatar } from '@/features/list-page/ui/RecordAvatar';
import { overlayOpen } from '@/features/list-page/ui/RecordPreviewView';
import { canOpenPropertySettings } from '@/features/permission-sets/property-settings';
import type { DescribeField } from '@/features/property-history/describe';
import { follow, getFollow, unfollow } from '@/features/record-tools/api.client';
import type { RegionFormat } from '@/features/settings/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

/** The record page's drawers that `?action=` opens (useOpenRecordAction). */
const QUICK: Array<[string, string, LpIconName]> = [
  ['note', 'Note', 'note'],
  ['email', 'Email', 'email'],
  ['call', 'Call', 'call'],
  ['task', 'Task', 'task'],
  ['meeting', 'Meeting', 'meeting'],
];

function contactName(c: Pick<Contact, 'firstName' | 'lastName' | 'email'>): string {
  return [c.firstName, c.lastName].filter(Boolean).join(' ').trim() || c.email || 'Untitled';
}

/** A drawer or confirm dialog is open over the panel: Escape is theirs (shared with Companies, B4). */
export { overlayOpen };

/**
 * "Contact preview" (design list-page `openPreview`): a side panel opened from a row's Preview
 * button with the contact's name, email, quick actions (they open the record with that drawer),
 * "About this contact" and the primary company, then the record page's cards. View record and
 * Actions ▾ at the top.
 */
export function ContactPreviewPanel({
  contactId,
  singular,
  labelOf,
  canDelete,
  onClose,
  onDeleted,
  onChanged,
  onExport,
  editorFor,
  describeHistory,
  region,
  timeZone,
}: {
  contactId: string | null;
  /** "Contact", or the business's name for it. */
  singular: string;
  /** Display labels of picklist values (lifecycle stage, lead status). */
  labelOf: (field: 'lifecycleStage' | 'leadStatus', value: string | null) => string;
  canDelete: boolean;
  onClose: () => void;
  onDeleted: () => void;
  /** The contact changed from here (a tool or a card): the list shows it too. */
  onChanged: () => void;
  /** Actions > Export: the list's Export view dialog with this contact selected. */
  onExport?: (id: string) => void;
  /** The table's cell editors: each About value is edited in place (design `editPv`). */
  editorFor?: (row: ContactListItem, columnId: string) => CellEditor | null;
  /** Field labels and value texts, for the property history and the activity cards. */
  describeHistory: DescribeField;
  /** The user's date format and time zone: the dates read as on the record and the list. */
  region: RegionFormat;
  timeZone: string;
}) {
  // The day of a date in the user's time zone (the browser's could be a day off).
  const formatDate = (iso: string | null | undefined) => formatUserDate(iso, { region, timeZone });
  const toast = useToast();
  const router = useRouter();
  const me = useCurrentUser();
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [contact, setContact] = useState<Contact | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [shown, setShown] = useState(false);
  const [aboutOpen, setAboutOpen] = useState(true);
  const [assocOpen, setAssocOpen] = useState(true);
  const [moreOpen, setMoreOpen] = useState(false);
  const [following, setFollowing] = useState(false);
  const [reloadKey, setReloadKey] = useState(0);
  const [cardsKey, setCardsKey] = useState(0);
  const moreRef = useRef<HTMLButtonElement>(null);
  const panelRef = useRef<HTMLElement>(null);
  const closeRef = useRef(onClose);
  // A reload that lands after the panel moved to another contact is dropped.
  const shownIdRef = useRef(contactId);
  shownIdRef.current = contactId;
  // Escape closes the delete dialog first, not the panel behind it.
  closeRef.current = deleteOpen ? () => {} : onClose;

  useEffect(() => {
    if (!contactId) return;
    let live = true;
    setError(null);
    setFollowing(false);
    getFollow('contact', contactId).then(
      (f) => {
        if (live) setFollowing(f.following);
      },
      () => {},
    );
    getContact(contactId).then(
      (c) => {
        if (live) setContact(c);
      },
      (err: unknown) => {
        if (live) setError(errorText(err));
      },
    );
    return () => {
      live = false;
    };
  }, [contactId, reloadKey]);
  // A different contact starts from Loading; a reload after an edit keeps the panel on screen.
  useEffect(() => {
    setContact(null);
  }, [contactId]);

  // Slide in, lock the page behind it, Escape closes, focus goes back to the Preview button.
  useEffect(() => {
    if (!contactId) {
      setShown(false);
      return;
    }
    const opener = document.activeElement as HTMLElement | null;
    document.documentElement.classList.add('lp-lock');
    const t = window.setTimeout(() => {
      setShown(true);
      panelRef.current
        ?.querySelector<HTMLElement>('[data-autofocus]')
        ?.focus({ preventScroll: true });
    }, 10);
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !overlayOpen(document)) closeRef.current();
    };
    window.addEventListener('keydown', onKey);
    return () => {
      window.clearTimeout(t);
      window.removeEventListener('keydown', onKey);
      document.documentElement.classList.remove('lp-lock');
      if (opener?.isConnected) opener.focus({ preventScroll: true });
    };
  }, [contactId]);

  const contactLabel = contact ? contactName(contact) : '';
  const readableCtx: ReadableContext = useMemo(
    () => ({
      recordName: contactLabel,
      describe: describeHistory,
      region,
      timeZone,
      objectLabel: singular,
    }),
    [contactLabel, describeHistory, region, timeZone, singular],
  );

  if (!contactId || typeof document === 'undefined') return null;
  const href = `/contacts/${contactId}`;
  const name = contactLabel;
  // P2a: Delete and Merge follow their own scopes on this contact (`recordRights`).
  const rights = recordRights(
    me.permissionSet.rules.objects.contact,
    contact?.owner?.id,
    me,
    contact?.sharedWithMe,
    contact?.ownerFieldMatch,
  );
  const canEdit = Boolean(contact) && rights.edit;
  const primary = contact?.companies.find((c) => c.isPrimary) ?? contact?.companies[0];
  const sub = contact ? [contact.jobTitle, primary?.name].filter(Boolean).join(' at ') : '';

  // The design's "About this contact": the list's fields in its order.
  const custom = (contact?.customProperties ?? {}) as Record<string, unknown>;
  const lastActivity =
    typeof custom.notes_last_updated === 'string' ? custom.notes_last_updated : null;
  const city = typeof custom.city === 'string' ? custom.city : '';
  // [label, value, the table column that edits it]
  const fields: Array<[string, string, string | null]> = contact
    ? [
        ['Email', contact.email || '--', 'email'],
        ['Phone number', contact.phone || '--', 'phone'],
        ['Contact owner', contact.owner?.name ?? 'No owner', 'ownerId'],
        ['Primary company', primary?.name ?? '--', 'company'],
        ['Last activity date', formatDate(lastActivity), 'custom.notes_last_updated'],
        ['Lead status', labelOf('leadStatus', contact.leadStatus), 'leadStatus'],
        ['Create date', formatDate(contact.createdAt), null],
        ['Lifecycle stage', labelOf('lifecycleStage', contact.lifecycleStage), 'lifecycleStage'],
        ['Job title', contact.jobTitle || '--', 'jobTitle'],
        ['Company name', contact.companyName || '--', 'companyName'],
        ['City', city || '--', 'custom.city'],
      ]
    : [];
  /** The contact as a table row, for the table's cell editors. */
  const row: ContactListItem | null = contact
    ? {
        id: contact.id,
        firstName: contact.firstName,
        lastName: contact.lastName,
        email: contact.email,
        phone: contact.phone,
        owner: contact.owner ? { id: contact.owner.id, name: contact.owner.name } : null,
        lifecycleStage: contact.lifecycleStage,
        leadStatus: contact.leadStatus,
        company: primary ? { id: primary.id, name: primary.name } : null,
        jobTitle: contact.jobTitle,
        companyName: contact.companyName ?? null,
        customProperties: contact.customProperties,
        createdAt: contact.createdAt,
        updatedAt: contact.updatedAt,
      }
    : null;

  const toggleFollow = async () => {
    if (!contact) return;
    try {
      const next = following
        ? await unfollow('contact', contact.id)
        : await follow('contact', contact.id);
      setFollowing(next.following);
      toast(next.following ? `You’re now following ${name}` : `You stopped following ${name}`);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    }
  };

  const onDelete = async () => {
    if (!contact) return;
    await deleteContact(contact.id);
    setDeleteOpen(false);
    toast(`${recordsText(1)} deleted`);
    onDeleted();
    onClose();
  };

  /** A tool or a card changed the contact: the list and the panel read it again. */
  const afterChange = async () => {
    if (!contact) return;
    onChanged();
    try {
      const fresh = await getContact(contact.id);
      if (shownIdRef.current === fresh.id) setContact(fresh);
      setCardsKey((k) => k + 1);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    }
  };

  const cloneContact = async () => {
    if (!contact) return;
    try {
      const copy = await createContact(cloneContactBody(contact));
      toast(`${singular} cloned`);
      onClose();
      router.push(`/contacts/${copy.id}`);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    }
  };

  const copyEmail = (email: string) => {
    void navigator.clipboard?.writeText(email).then(
      () => toast('Email copied'),
      () => toast('Copy failed', 'danger'),
    );
  };

  return createPortal(
    <>
      <div
        className={cn('lp-side-ov lp-side-ov--contact', shown && 'is-open')}
        onMouseDown={onClose}
      />
      <aside
        ref={panelRef}
        className={cn('lp-side lp-side--preview lp-side--contact', shown && 'is-open')}
        role="dialog"
        aria-modal="true"
        aria-label={name ? `${name} preview` : `${singular} preview`}
      >
        <header className="lp-side__head">
          <span className="lp-side__kicker">{singular} preview</span>
          <div className="lp-side__tools">
            <Link className="lp-btn lp-btn--outline lp-btn--sm" href={href} data-autofocus>
              View record
            </Link>
            <ContactPreviewActions
              key={contactId}
              contactId={contactId}
              contact={contact}
              name={name}
              following={following}
              onToggleFollow={() => void toggleFollow()}
              href={href}
              canEdit={canEdit}
              canDelete={canDelete && Boolean(contact) && rights.delete}
              canMerge={Boolean(contact) && rights.merge}
              canLog={me.role !== 'read_only'}
              timeZone={timeZone}
              describeHistory={describeHistory}
              canManageProperties={canOpenPropertySettings(me)}
              onExport={
                onExport
                  ? () => {
                      onClose();
                      onExport(contactId);
                    }
                  : undefined
              }
              onDelete={() => setDeleteOpen(true)}
              onClone={() => void cloneContact()}
              onChanged={() => void afterChange()}
            />
            <button
              type="button"
              className="lp-icon-btn"
              aria-label="Close preview"
              onClick={onClose}
            >
              <LpIcon name="x" />
            </button>
          </div>
        </header>

        <div className="lp-side__body">
          {error ? <p className="crm-text-danger">{error}</p> : null}
          {!contact && !error ? <p className="lp-muted">Loading…</p> : null}
          {contact ? (
            <>
              <div className="lp-pv__id">
                <Avatar name={name} size="lg" />
                <div className="lp-pv__copy">
                  <h2 className="lp-pv__name">{name}</h2>
                  {sub ? <p className="lp-pv__sub">{sub}</p> : null}
                  {contact.email ? (
                    <p className="lp-pv__mail">
                      <a href={`mailto:${contact.email}`}>{contact.email}</a>
                      <button
                        type="button"
                        className="lp-icon-btn lp-icon-btn--sm"
                        aria-label="Copy email address"
                        title="Copy"
                        onClick={() => copyEmail(contact.email!)}
                      >
                        <LpIcon name="copy" />
                      </button>
                    </p>
                  ) : null}
                </div>
              </div>
              <div className="lp-pv__quick">
                {QUICK.map(([action, label, icon]) => (
                  <Link key={action} className="lp-pv__qa" href={`${href}?action=${action}`}>
                    <span className="lp-pv__qi">
                      <LpIcon name={icon} />
                    </span>
                    {label}
                  </Link>
                ))}
                <button
                  ref={moreRef}
                  type="button"
                  className="lp-pv__qa"
                  aria-haspopup="menu"
                  aria-expanded={moreOpen}
                  onClick={() => setMoreOpen((v) => !v)}
                >
                  <span className="lp-pv__qi">
                    <LpIcon name="moreH" />
                  </span>
                  More
                </button>
              </div>
              <LpPopover
                pop="menu"
                open={moreOpen}
                anchorRef={moreRef}
                onClose={() => setMoreOpen(false)}
                label="More"
                className="lp-pop--menu"
                align="end"
              >
                <LpMenu
                  label="More"
                  onClose={() => setMoreOpen(false)}
                  items={[
                    {
                      key: 'log',
                      label: 'Log activity',
                      icon: 'note',
                      href: `${href}?action=note`,
                    },
                    { key: 'all', label: 'View all properties', icon: 'columns', href },
                    {
                      key: 'follow',
                      label: following ? 'Unfollow' : 'Follow',
                      icon: 'eye',
                      onSelect: () => void toggleFollow(),
                    },
                  ]}
                />
              </LpPopover>
              <section className="lp-pv__sec">
                <h3>
                  <button
                    type="button"
                    className="lp-pv__sh"
                    aria-expanded={aboutOpen}
                    onClick={() => setAboutOpen((v) => !v)}
                  >
                    <LpIcon name="caret" />
                    About this {singular.toLowerCase()}
                  </button>
                </h3>
                {aboutOpen ? (
                  <div className="lp-pv__fields">
                    {fields.map(([label, value, col]) => (
                      <div key={label} className="lp-pv__field">
                        <span className="lp-pv__label">{label}</span>
                        <PreviewValue
                          editor={row && col && editorFor ? editorFor(row, col) : null}
                          display={value}
                          onSaved={() => setReloadKey((k) => k + 1)}
                        />
                      </div>
                    ))}
                  </div>
                ) : null}
              </section>
              {primary ? (
                <section className="lp-pv__sec">
                  <h3>
                    <button
                      type="button"
                      className="lp-pv__sh"
                      aria-expanded={assocOpen}
                      onClick={() => setAssocOpen((v) => !v)}
                    >
                      <LpIcon name="caret" />
                      Associations
                    </button>
                  </h3>
                  {assocOpen ? (
                    <div className="lp-pv__fields">
                      <Link className="lp-pv__assoc" href={`/companies/${primary.id}`}>
                        <Avatar name={primary.name} size="sm" />
                        <span>
                          <strong>{primary.name}</strong>
                          <small>Primary company</small>
                        </span>
                      </Link>
                    </div>
                  ) : null}
                </section>
              ) : null}
              <ContactPreviewCards
                key={contact.id}
                contact={contact}
                name={name}
                canEdit={canEdit}
                ctx={readableCtx}
                refreshKey={cardsKey}
                onChanged={afterChange}
              />
            </>
          ) : null}
        </div>
      </aside>
      <DeleteRecordsDialog
        open={deleteOpen}
        count={1}
        onClose={() => setDeleteOpen(false)}
        onConfirm={onDelete}
      />
    </>,
    document.body,
  );
}
