'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import {
  CustomFieldInput,
  formatCustomValue,
  fromUiValue,
  sameUiValue,
  toUiValue,
  type CustomUiValue,
} from '@/features/contacts/ui/actions/custom-fields';
import type { CustomProperties } from '@/types/api';
import { isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { getObjectRecord, updateObjectRecord } from '../api.client';
import { saveErrorText } from '../errors';
import { objectRecordPath } from '../paths';
import { EMPTY, formatDateTime, linkTypes, recordsLabel } from '../columns';
import { fieldUsers, isMultiUserField, ownerIdsOf } from '@/features/custom-properties/crm-user';
import { hasTeamLimit, useTeamOptions } from '@/features/custom-properties/useTeamOptions';
import { isOwnerField, ownerFieldText } from '../fields';
import type { ObjectSchema } from '../useObjectSchema';
import type { CustomValues, ObjectRecord } from '../types';
import { uiValuesChanged } from '../unsaved';
import { useUnsavedGuard } from '../useUnsavedGuard';
import { formatUserDate } from '@/features/activities/readable';
import { useUserPrefs } from '@/features/contacts/ui/actions/shared';
import { isLockedField } from '@/features/custom-properties/api.client';

/**
 * "<Object> preview": the record's owner, pipeline, dates, linked record counts and every
 * property, editable in place (Edit / Save). Saving sends the `updatedAt` it loaded, so a record
 * someone changed meanwhile is not overwritten (409).
 */
export function PreviewDrawer({
  record,
  startEditing,
  onClose,
  schema,
  timeZone,
  onSaved,
}: {
  record: ObjectRecord | null;
  startEditing: boolean;
  onClose: () => void;
  schema: ObjectSchema;
  timeZone: string;
  onSaved: (record: ObjectRecord) => void;
}) {
  const { definition, defs, pipelines, owners } = schema;
  // DMG9: who is on the teams of CRM user fields limited to some.
  const teams = useTeamOptions(hasTeamLimit(defs));
  const datePrefs = { region: useUserPrefs().regionFormat, timeZone };
  const [current, setCurrent] = useState<ObjectRecord | null>(record);
  const [editing, setEditing] = useState(false);
  const [values, setValues] = useState<Record<string, CustomUiValue>>({});
  const [ownerId, setOwnerId] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [query, setQuery] = useState('');
  /** The record the edit started from: what is compared and whose updatedAt is sent. */
  const [base, setBase] = useState<ObjectRecord | null>(null);
  /** The values the edit started with (HUB-728: what counts as a change). */
  const [initial, setInitial] = useState<Record<string, CustomUiValue>>({});

  const startEdit = (r: ObjectRecord) => {
    const ui: Record<string, CustomUiValue> = {};
    for (const def of defs) {
      ui[def.name] = toUiValue(
        def,
        r.customProperties[def.name] as CustomProperties[string] | undefined,
        timeZone,
      );
    }
    setValues(ui);
    setInitial(ui);
    setOwnerId(r.owner?.id ?? '');
    setBase(r);
    setEditing(true);
  };

  useEffect(() => {
    setCurrent(record);
    setError(null);
    setQuery('');
    if (!record) return;
    if (startEditing) startEdit(record);
    else setEditing(false);
    // Fresh copy: the list row may be older than the record (and edits need its updatedAt).
    let alive = true;
    getObjectRecord(definition.key, record.id).then(
      (fresh) => {
        if (!alive) return;
        const next = { ...fresh, linkCounts: record.linkCounts };
        setCurrent(next);
        // The edit started from the list row: send the fresh copy's updatedAt instead.
        setBase((cur) => (cur && cur.id === next.id ? next : cur));
      },
      () => {},
    );
    return () => {
      alive = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps -- reload when another record opens
  }, [record?.id, startEditing]);

  const open = record !== null;
  // HUB-728: closing the preview with unsaved edits asks first (Cancel still discards them).
  const dirty =
    open && editing && (uiValuesChanged(initial, values) || ownerId !== (base?.owner?.id ?? ''));
  const { guard, dialog } = useUnsavedGuard(dirty);
  const close = () => guard(onClose);
  const r = current ?? record;
  const pipeline = pipelines.find((p) => p.id === r?.pipelineId);
  const stage = pipeline?.stages.find((s) => s.id === r?.stageId);
  const q = query.trim().toLowerCase();
  const shownDefs = q ? defs.filter((d) => d.label.toLowerCase().includes(q)) : defs;

  const save = async () => {
    const from = base;
    if (!from) return;
    const changed: CustomValues = {};
    for (const def of defs) {
      if (isLockedField(def)) continue;
      const before = toUiValue(
        def,
        from.customProperties[def.name] as CustomProperties[string] | undefined,
        timeZone,
      );
      const after = values[def.name] ?? before;
      if (sameUiValue(before, after)) continue;
      const parsed = fromUiValue(def, after, timeZone);
      if ('error' in parsed) {
        setError(parsed.error);
        return;
      }
      if (parsed.value === null && def.name === definition.displayProperty) {
        setError(`${def.label} can't be empty.`);
        return;
      }
      changed[def.name] = parsed.value;
    }
    const ownerChanged = (from.owner?.id ?? '') !== ownerId;
    if (Object.keys(changed).length === 0 && !ownerChanged) {
      setEditing(false);
      return;
    }
    setBusy(true);
    setError(null);
    try {
      const saved = await updateObjectRecord(definition.key, from.id, {
        ...(Object.keys(changed).length ? { customProperties: changed } : {}),
        ...(ownerChanged ? { ownerId: ownerId || null } : {}),
        updatedAt: from.updatedAt,
      });
      const next = { ...saved, linkCounts: from.linkCounts };
      setCurrent(next);
      setEditing(false);
      onSaved(next);
    } catch (err) {
      setError(saveErrorText(err, defs));
      // Someone else saved first: load their copy, so the next attempt isn't stale too.
      if (isApiError(err) && err.isConflict) {
        const fresh = await getObjectRecord(definition.key, from.id).catch(() => null);
        if (fresh) {
          const next = { ...fresh, linkCounts: from.linkCounts };
          setCurrent(next);
          setBase(next);
        }
      }
    } finally {
      setBusy(false);
    }
  };

  const ownerName = r?.owner?.name ?? EMPTY;

  return (
    <>
      <CrmModal id="evPreview" open={open} onClose={close} drawer>
        <ModalHeader id="evPreview" title={`${definition.singularLabel} preview`} onClose={close} />
        <div className="modal__body ev-preview">
          {r ? (
            <>
              <div className="ev-preview__head">
                <h3 className="ev-preview__name">{r.displayName || 'Untitled'}</h3>
                <dl className="ev-preview__meta">
                  <div>
                    <dt>Owner</dt>
                    <dd>
                      {editing ? (
                        <select
                          className="input"
                          aria-label="Owner"
                          value={ownerId}
                          onChange={(e) => setOwnerId(e.target.value)}
                        >
                          <option value="">No owner</option>
                          {owners
                            .filter((o) => o.active || o.userId === r.owner?.id)
                            .map((o) => (
                              <option key={o.userId} value={o.userId}>
                                {o.name}
                              </option>
                            ))}
                        </select>
                      ) : (
                        ownerName
                      )}
                    </dd>
                  </div>
                  {definition.hasPipeline ? (
                    <div>
                      <dt>Pipeline</dt>
                      <dd>
                        {pipeline ? `${pipeline.name}${stage ? ` · ${stage.name}` : ''}` : EMPTY}
                      </dd>
                    </div>
                  ) : null}
                  <div>
                    <dt>Object create date/time</dt>
                    <dd>{formatDateTime(r.createdAt, datePrefs)}</dd>
                  </div>
                  <div>
                    <dt>Object last modified date/time</dt>
                    <dd>{formatDateTime(r.updatedAt, datePrefs)}</dd>
                  </div>
                </dl>
              </div>

              {r.linkCounts ? (
                <div className="ev-preview__links">
                  {linkTypes(schema)
                    .filter((t) => r.linkCounts?.[t.type] !== undefined)
                    .map((t) => (
                      <span key={t.type} className="ev-chip">
                        {t.plural}: {recordsLabel(r.linkCounts?.[t.type])}
                      </span>
                    ))}
                </div>
              ) : null}

              {error ? <Alert tone="danger">{error}</Alert> : null}

              <div className="ev-preview__props">
                <div className="ev-preview__bar">
                  <h4>Properties</h4>
                  <div className="ev-search">
                    <input
                      type="search"
                      className="input"
                      placeholder="Search properties"
                      aria-label="Search properties"
                      value={query}
                      onChange={(e) => setQuery(e.target.value)}
                    />
                  </div>
                </div>
                <dl className="ev-props">
                  {shownDefs.map((def) => (
                    <div key={def.id} className={cn('ev-props__row', editing && 'is-editing')}>
                      <dt>
                        {editing && !isLockedField(def) ? (
                          <label htmlFor={`evPrev-${def.name}`}>{def.label}</label>
                        ) : (
                          def.label
                        )}
                      </dt>
                      <dd>
                        {editing && !isLockedField(def) ? (
                          // DMG9: a multiple users field picks in CustomFieldInput.
                          isOwnerField(def) && !isMultiUserField(def) ? (
                            <select
                              className="input"
                              id={`evPrev-${def.name}`}
                              value={(values[def.name] as string | undefined) ?? ''}
                              onChange={(e) =>
                                setValues((cur) => ({ ...cur, [def.name]: e.target.value }))
                              }
                            >
                              <option value="">No owner</option>
                              {/* DMG9: users of the field's teams, plus the one it holds. */}
                              {fieldUsers(
                                owners,
                                def,
                                teams,
                                ownerIdsOf(r.customProperties[def.name]),
                              ).map((o) => (
                                <option key={o.userId} value={o.userId}>
                                  {o.name}
                                </option>
                              ))}
                            </select>
                          ) : (
                            <CustomFieldInput
                              def={def}
                              id={`evPrev-${def.name}`}
                              value={values[def.name] ?? (def.type === 'multiselect' ? [] : '')}
                              onChange={(v) => setValues((cur) => ({ ...cur, [def.name]: v }))}
                            />
                          )
                        ) : isOwnerField(def) ? (
                          ownerFieldText(r.customProperties[def.name], owners)
                        ) : (
                          formatCustomValue(
                            def,
                            r.customProperties[def.name] as CustomProperties[string] | undefined,
                            undefined,
                            (iso) => formatUserDate(iso, { ...datePrefs, time: true }),
                          )
                        )}
                      </dd>
                    </div>
                  ))}
                  {shownDefs.length === 0 ? <p className="ev-help">No properties match.</p> : null}
                </dl>
              </div>
            </>
          ) : null}
        </div>
        <div className="modal__footer">
          {editing ? (
            <>
              <button
                type="button"
                className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
                disabled={busy}
                onClick={() => void save()}
              >
                Save
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                disabled={busy}
                onClick={() => {
                  setEditing(false);
                  setError(null);
                }}
              >
                Cancel
              </button>
            </>
          ) : (
            <>
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                disabled={!r}
                onClick={() => r && startEdit(r)}
              >
                Edit
              </button>
              <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
                Close
              </button>
              {r ? (
                <Link
                  className="btn-crm btn-crm--outline"
                  href={objectRecordPath(definition.key, r.id)}
                >
                  View record
                </Link>
              ) : null}
            </>
          )}
        </div>
      </CrmModal>
      {dialog}
    </>
  );
}
