'use client';

// Custom objects (HUB-270): the naming helpers the data model's "Create object" panel uses, and
// the edit and archive actions of Settings > Objects. Objects are created and restored in the
// Data Model.
import { useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { setObjectDefinitionArchived, updateObjectDefinition } from '@/features/objects/api.client';
import type { ObjectDefinition } from '@/features/objects/types';
import { errorText } from '@/lib/api/errors';
import { DrawerForm } from './settings-ui';

/** Icons an object can show (names of `CrmIcon`). */
export const OBJECT_ICONS = [
  { value: 'briefcase', label: 'Briefcase' },
  { value: 'calendar', label: 'Calendar' },
  { value: 'users', label: 'People' },
  { value: 'user', label: 'Person' },
  { value: 'inbox', label: 'Inbox' },
  { value: 'mail', label: 'Mail' },
  { value: 'map-pin', label: 'Location' },
  { value: 'video', label: 'Video' },
  { value: 'check-square', label: 'Checklist' },
  { value: 'clock', label: 'Clock' },
] as const;

/** Keys the API refuses (built-in objects and words it uses), from `@crm/shared`. */
const RESERVED_KEYS = new Set([
  'contact',
  'company',
  'deal',
  'activity',
  'email',
  'call',
  'meeting',
  'note',
  'task',
  'communication',
  'user',
  'owner',
  'team',
  'member',
  'pipeline',
  'stage',
  'list',
  'view',
  'form',
  'workflow',
  'sequence',
  'object',
  'record',
]);

const KEY_PATTERN = /^[a-z][a-z0-9_]{1,31}$/;

/** "Event" → "event"; "Job Application" → "job_application" (the API's key format). */
export function toObjectKey(label: string): string {
  const slug = label
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '_')
    .replace(/^_+|_+$/g, '');
  const key = /^[a-z]/.test(slug) ? slug : `obj_${slug}`;
  return key.slice(0, 32).replace(/_+$/, '');
}

/** "Event name" → "event_name" (a custom field name). */
export function toFieldName(label: string): string {
  const slug = label
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '_')
    .replace(/^_+|_+$/g, '')
    .slice(0, 64);
  return /^[a-z]/.test(slug) ? slug : `field_${slug}`.slice(0, 64);
}

/** Field names the API keeps for standard fields (`RESERVED_NAMES` in custom-properties). */
export const RESERVED_FIELD_NAMES = new Set([
  'id',
  'business_id',
  'owner',
  'owner_id',
  'source',
  'hubspot_id',
  'external_ids',
  'custom_properties',
  'created_at',
  'updated_at',
  'created_by',
  'updated_by',
  'deleted_at',
  'name',
  'first_name',
  'last_name',
  'email',
  'phone',
  'job_title',
  'lifecycle_stage',
  'lead_status',
  'domain',
  'website',
  'industry',
  'city',
  'state',
  'country',
  'pipeline',
  'pipeline_id',
  'stage',
  'stage_id',
  'amount',
  'currency',
  'close_date',
  'priority',
  'probability',
  'deal_type',
]);

/** The record name field's name; a reserved one ("Name") gets the object key in front. */
export function recordNameField(label: string, objectKey: string): string {
  const name = toFieldName(label);
  return RESERVED_FIELD_NAMES.has(name) ? `${objectKey}_${name}`.slice(0, 64) : name;
}

export function keyError(key: string, taken: Set<string>): string | null {
  if (!KEY_PATTERN.test(key)) {
    return 'Use lowercase letters, numbers and _ (start with a letter; 2 to 32 characters).';
  }
  if (RESERVED_KEYS.has(key)) return 'This key is reserved.';
  if (taken.has(key)) return 'An object with this key already exists (archived ones keep theirs).';
  return null;
}

/** Edits an object's names, record name field and icon (the key and pipeline are fixed). */
export function EditObjectDrawer({
  definition,
  open,
  onClose,
  onSaved,
}: {
  definition: ObjectDefinition | null;
  open: boolean;
  onClose: () => void;
  onSaved: (definition: ObjectDefinition) => void;
}) {
  const toast = useToast();
  const [textFields, setTextFields] = useState<CustomPropertyDefinition[]>([]);

  useEffect(() => {
    if (!open || !definition) return;
    let alive = true;
    listCustomProperties({ objectType: definition.key }).then(
      (fields) =>
        alive &&
        setTextFields(
          fields.filter((f) => !f.archived && (f.type === 'text' || f.type === 'number')),
        ),
      () => alive && setTextFields([]),
    );
    return () => {
      alive = false;
    };
  }, [open, definition]);

  const nameOptions = textFields.some((f) => f.name === definition?.displayProperty)
    ? textFields
    : definition
      ? [{ name: definition.displayProperty, label: definition.displayProperty }, ...textFields]
      : textFields;

  return (
    <DrawerForm
      key={definition?.id ?? 'no-object-edit'}
      id="edit-object"
      title={definition ? `Edit ${definition.pluralLabel}` : 'Edit object'}
      open={open}
      onClose={onClose}
      keep
      onSave={async (formData) => {
        if (!definition) return false;
        const singularLabel = String(formData.get('singularLabel') ?? '').trim();
        const pluralLabel = String(formData.get('pluralLabel') ?? '').trim();
        const displayProperty = String(formData.get('displayProperty') ?? '').trim();
        const icon = String(formData.get('icon') ?? '').trim();
        if (!singularLabel || !pluralLabel) {
          toast('Singular and plural names are required.', 'danger');
          return false;
        }
        try {
          const saved = await updateObjectDefinition(definition.id, {
            singularLabel,
            pluralLabel,
            ...(displayProperty && { displayProperty }),
            icon: icon || null,
          });
          onSaved(saved);
          return `${saved.pluralLabel} updated`;
        } catch (err) {
          toast(errorText(err), 'danger');
          return false;
        }
      }}
    >
      <div className="field field--full">
        <label className="field__label" htmlFor="eobj-singular">
          Singular name
        </label>
        <input
          className="input"
          id="eobj-singular"
          name="singularLabel"
          required
          maxLength={100}
          defaultValue={definition?.singularLabel ?? ''}
        />
      </div>

      <div className="field field--full">
        <label className="field__label" htmlFor="eobj-plural">
          Plural name
        </label>
        <input
          className="input"
          id="eobj-plural"
          name="pluralLabel"
          required
          maxLength={100}
          defaultValue={definition?.pluralLabel ?? ''}
        />
      </div>

      <div className="field field--full">
        <label className="field__label" htmlFor="eobj-key">
          Key
        </label>
        <input className="input" id="eobj-key" value={definition?.key ?? ''} readOnly disabled />
      </div>

      <div className="field field--full">
        <label className="field__label" htmlFor="eobj-name-field">
          Record name field
        </label>
        <select
          className="input"
          id="eobj-name-field"
          name="displayProperty"
          defaultValue={definition?.displayProperty ?? ''}
          key={`${definition?.id ?? ''}-${nameOptions.length}`}
        >
          {nameOptions.map((field) => (
            <option key={field.name} value={field.name}>
              {field.label}
            </option>
          ))}
        </select>
        <p className="field__help">A text or number field of this object.</p>
      </div>

      <div className="field field--full">
        <label className="field__label" htmlFor="eobj-icon">
          Icon
        </label>
        <select className="input" id="eobj-icon" name="icon" defaultValue={definition?.icon ?? ''}>
          <option value="">None</option>
          {OBJECT_ICONS.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </div>

      <div className="field field--full">
        <span className="field__label">Pipeline</span>
        <p className="crm-text-body-secondary">
          {definition?.hasPipeline ? 'Records move through a pipeline.' : 'No pipeline.'} This
          can&apos;t be changed.
        </p>
      </div>
    </DrawerForm>
  );
}

/** Archives or restores an object after asking; the caller reloads the list. */
export async function toggleObjectArchived(
  definition: ObjectDefinition,
  archive: boolean,
): Promise<ObjectDefinition | null> {
  const question = archive
    ? `Archive ${definition.pluralLabel}? It disappears from the navigation; its records and fields are kept and it can be restored.`
    : `Restore ${definition.pluralLabel}?`;
  if (!window.confirm(question)) return null;
  return setObjectDefinitionArchived(definition.id, archive);
}
