'use client';

import { useEffect, useState } from 'react';
import type { PropertyType, RollupConfig } from '@/features/custom-properties/api.client';
import { getFilterFields, type FilterFieldInfo } from '@/features/filters/api.client';
import { cn } from '@/lib/utils/cn';
import { byText, type DataModel, type DmObject } from '../model';
import {
  CALCULATION_RESULT_CHOICES,
  excludedSourcesNote,
  ROLLUP_CHOICES,
  sourceFits,
  STAGE_TYPE_CHOICES,
  SYNC_CHOICES,
} from '../worked-out';
import { SelectMenu } from './primitives';

const EVERY = '__every__';

/**
 * The objects a record links to and the fields of the chosen one (GET /filters/fields), for a
 * rollup or property sync. null while loading or when it failed.
 */
export function useRollupFields(objectKey: string, linkedObject: string, enabled: boolean) {
  const [linked, setLinked] = useState<string[] | null>(null);
  const [fields, setFields] = useState<FilterFieldInfo[] | null>(null);
  const [failed, setFailed] = useState(false);
  useEffect(() => {
    if (!enabled) return;
    let alive = true;
    getFilterFields(objectKey).then(
      (r) => alive && setLinked(r.linked),
      () => alive && setFailed(true),
    );
    return () => {
      alive = false;
    };
  }, [objectKey, enabled]);
  useEffect(() => {
    setFields(null);
    if (!enabled || !linkedObject) return;
    let alive = true;
    getFilterFields(linkedObject).then(
      (r) => alive && setFields(r.fields),
      () => alive && setFailed(true),
    );
    return () => {
      alive = false;
    };
  }, [linkedObject, enabled]);
  return { linked, fields, failed };
}

/** Field type section of a calculation: the result type and the formula. */
export function CalculationFields({
  expression,
  resultType,
  typeFixed,
  disabled,
  error,
  onChange,
}: {
  expression: string;
  resultType: PropertyType;
  /** A saved calculation keeps its result type; only the formula changes. */
  typeFixed: boolean;
  disabled: boolean;
  /** Why the API refused the formula on the last save (unknown field, syntax…). */
  error: string | null;
  onChange: (patch: { formula?: string; resultType?: PropertyType }) => void;
}) {
  return (
    <>
      <div className="dm-field">
        <span className="dm-field__label">Result type *</span>
        <SelectMenu
          value={resultType}
          options={CALCULATION_RESULT_CHOICES}
          onChange={(v) => onChange({ resultType: v })}
          ariaLabel="Result type"
          disabled={disabled || typeFixed}
        />
      </div>
      <label className="dm-field">
        <span className="dm-field__label">Formula *</span>
        <span className="dm-field__hint">
          Use the internal names of this object&apos;s properties, numbers and functions such as if,
          round, min, max, concat, days_between and is_known. For example:{' '}
          <code>round(amount * 0.2, 2)</code>
        </span>
        <textarea
          className={cn('dm-textarea', error && 'is-invalid')}
          rows={4}
          maxLength={2000}
          value={expression}
          disabled={disabled}
          spellCheck={false}
          aria-label="Formula"
          aria-invalid={Boolean(error)}
          onChange={(e) => onChange({ formula: e.target.value })}
        />
        {error && (
          <span className="dm-field__error" role="alert">
            {error}
          </span>
        )}
      </label>
    </>
  );
}

/**
 * Field type section of a rollup or property sync: the linked records, how they are worked out
 * and the property used, plus deal stage types for rollups of deals.
 */
export function RollupFields({
  object,
  model,
  sync,
  value,
  linked,
  fields,
  failed,
  problem,
  disabled,
  onChange,
}: {
  object: DmObject;
  model: DataModel;
  sync: boolean;
  value: RollupConfig;
  linked: string[] | null;
  fields: FilterFieldInfo[] | null;
  failed: boolean;
  /** What still needs choosing (rollupProblem). */
  problem: string | null;
  disabled: boolean;
  onChange: (next: RollupConfig) => void;
}) {
  const defs = model.properties[value.linkedObject] ?? [];
  const nameOf = (key: string) => model.objects.find((o) => o.key === key)?.name ?? key;
  const objects = (linked ?? (value.linkedObject ? [value.linkedObject] : []))
    .map((key) => ({ value: key, label: nameOf(key) }))
    .sort((a, b) => byText(a.label, b.label));
  const functions = (sync ? SYNC_CHOICES : ROLLUP_CHOICES).filter(
    (c) => c.value !== 'primary' || (value.linkedObject === 'company' && object.key !== 'company'),
  );
  const sources = (fields ?? [])
    .filter((f) => sourceFits(value.function, f, defs) || f.field === value.sourceProperty)
    .map((f) => ({ value: f.field, label: f.label }))
    .sort((a, b) => byText(a.label, b.label));
  const set = (patch: Partial<RollupConfig>) => onChange({ ...value, ...patch });

  return (
    <>
      {failed && (
        <p className="dm-pe__msg">
          The linked records and their properties couldn&apos;t be loaded. Reload the page to try
          again.
        </p>
      )}
      <div className="dm-field">
        <span className="dm-field__label">{sync ? 'Sync from' : 'Linked records'} *</span>
        <SelectMenu
          value={value.linkedObject}
          options={objects}
          placeholder={linked === null && !failed ? 'Loading…' : 'Select an object'}
          onChange={(linkedObject) =>
            onChange({
              linkedObject,
              // A different object has different fields; primary is companies only.
              function:
                value.function === 'primary' && linkedObject !== 'company'
                  ? 'first_created'
                  : value.function,
            })
          }
          search={objects.length > 8}
          ariaLabel={sync ? 'Sync from' : 'Linked records'}
          disabled={disabled}
        />
      </div>
      <div className="dm-field">
        <span className="dm-field__label">{sync ? 'Which record' : 'Rollup type'} *</span>
        <SelectMenu
          value={value.function}
          options={functions}
          onChange={(fn) => {
            const source = fields?.find((f) => f.field === value.sourceProperty);
            set({
              function: fn,
              // Keep the property while it still fits.
              sourceProperty: source && sourceFits(fn, source, defs) ? source.field : undefined,
            });
          }}
          ariaLabel={sync ? 'Which record' : 'Rollup type'}
          disabled={disabled}
        />
        {sync && (
          <span className="dm-field__hint">
            {value.function === 'primary'
              ? "Copies the property of the record's primary company."
              : value.function === 'first_created'
                ? 'Copies the property of the linked record created first.'
                : 'Copies the property of the linked record created most recently.'}
          </span>
        )}
      </div>
      <div className="dm-field">
        <span className="dm-field__label">Property{value.function === 'count' ? '' : ' *'}</span>
        <SelectMenu
          value={value.sourceProperty ?? (value.function === 'count' ? EVERY : '')}
          options={[
            ...(value.function === 'count' ? [{ value: EVERY, label: 'Every linked record' }] : []),
            ...sources,
          ]}
          placeholder={
            value.linkedObject && fields === null && !failed ? 'Loading…' : 'Select a property'
          }
          onChange={(v) => set({ sourceProperty: v === EVERY ? undefined : v })}
          search
          ariaLabel="Property"
          disabled={disabled || !value.linkedObject}
        />
        <span className="dm-field__hint">
          {value.function === 'count'
            ? 'Counts the linked records, or only those with a value for the property.'
            : value.function === 'sum' || value.function === 'average'
              ? 'Number properties only.'
              : value.function === 'min' || value.function === 'max'
                ? 'Number, date and date and time properties only.'
                : 'The new property gets the type of the property it copies.'}
        </span>
        {!disabled && <span className="dm-field__hint">{excludedSourcesNote(value.function)}</span>}
      </div>
      {value.linkedObject === 'deal' && (
        <div className="dm-field">
          <span className="dm-field__label">Deal stages</span>
          <span className="dm-field__hint">
            Only use deals in these kinds of stage, in any pipeline. None ticked: every deal.
          </span>
          {STAGE_TYPE_CHOICES.map((c) => {
            const on = value.stageTypes?.includes(c.value) ?? false;
            return (
              <label key={c.value} className="dm-check dm-check--plain">
                <input
                  type="checkbox"
                  checked={on}
                  disabled={disabled}
                  onChange={() => {
                    const next = on
                      ? (value.stageTypes ?? []).filter((s) => s !== c.value)
                      : [...(value.stageTypes ?? []), c.value];
                    set({ stageTypes: next.length ? next : undefined });
                  }}
                />
                <span>{c.label}</span>
              </label>
            );
          })}
        </div>
      )}
      {problem && !disabled && <p className="dm-field__hint">{problem}</p>}
    </>
  );
}
