'use client';

import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import {
  CustomFieldInput,
  fromUiValue,
  type CustomUiValue,
} from '@/features/contacts/ui/actions/custom-fields';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import type { Owner } from '@/features/owners/api.client';
import { ownerOptionLabel } from '@/features/owners/labels';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { bulkObjectRecords } from '../api.client';
import type { BulkObjectRecordsBody, BulkObjectRecordsResult, CustomValues } from '../types';
import { nameInText } from '@/features/objects/paths';

/** Records one bulk request may name (the API's limit). */
const BULK_CHUNK = 100;

/** Sends a bulk change in chunks of 100 and adds up what changed and what was skipped. */
export async function runBulk(
  key: string,
  ids: string[],
  body: (ids: string[]) => BulkObjectRecordsBody,
): Promise<BulkObjectRecordsResult> {
  const total: BulkObjectRecordsResult = { changed: 0, skipped: [] };
  for (let i = 0; i < ids.length; i += BULK_CHUNK) {
    const result = await bulkObjectRecords(key, body(ids.slice(i, i + BULK_CHUNK)));
    total.changed += result.changed;
    total.skipped.push(...result.skipped);
  }
  return total;
}

export type BulkKind = 'edit' | 'assign' | 'delete';

type Props = {
  kind: BulkKind | null;
  onClose: () => void;
  objectKey: string;
  singular: string;
  plural: string;
  ids: string[];
  /** Custom fields that can be changed in bulk. */
  defs: CustomPropertyDefinition[];
  owners: Owner[];
  timeZone: string;
  onDone: (kind: BulkKind, result: BulkObjectRecordsResult) => void;
};

const OWNER_FIELD = '__owner__';

/** Edit (one property for every selected record), Assign (owner) and Delete. */
export function BulkDialogs(props: Props) {
  const { kind, onClose, objectKey, singular, plural, ids, defs, owners, timeZone, onDone } = props;
  const [prop, setProp] = useState('');
  const [value, setValue] = useState<CustomUiValue>('');
  const [ownerId, setOwnerId] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const noun = ids.length === 1 ? nameInText(singular) : nameInText(plural);
  const countText = `${ids.length.toLocaleString()} ${noun}`;

  useEffect(() => {
    if (!kind) return;
    setProp(OWNER_FIELD);
    setValue('');
    setOwnerId('');
    setError(null);
    setBusy(false);
  }, [kind]);

  const def = defs.find((d) => d.name === prop);
  const activeOwners = owners.filter((o) => o.active);

  const submit = async () => {
    if (!kind) return;
    let body: (chunk: string[]) => BulkObjectRecordsBody;
    if (kind === 'delete') {
      body = (chunk) => ({ action: 'delete', ids: chunk });
    } else if (kind === 'assign' || prop === OWNER_FIELD) {
      const owner = ownerId === '' ? null : ownerId;
      body = (chunk) => ({ action: 'assign', ids: chunk, ownerId: owner });
    } else {
      if (!def) return;
      const parsed = fromUiValue(def, value, timeZone);
      if ('error' in parsed) {
        setError(parsed.error);
        return;
      }
      const customProperties: CustomValues = { [def.name]: parsed.value };
      body = (chunk) => ({ action: 'update', ids: chunk, customProperties });
    }
    setBusy(true);
    setError(null);
    try {
      const result = await runBulk(objectKey, ids, body);
      onDone(kind, result);
      onClose();
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };

  const ownerSelect = (
    <select
      className="input"
      id="evBulkOwner"
      value={ownerId}
      onChange={(e) => setOwnerId(e.target.value)}
    >
      <option value="">No owner</option>
      {activeOwners.map((o) => (
        <option key={o.userId} value={o.userId}>
          {ownerOptionLabel(o, activeOwners)}
        </option>
      ))}
    </select>
  );

  const titles: Record<BulkKind, string> = {
    edit: `Edit ${countText}`,
    assign: `Assign ${countText}`,
    delete: `Delete ${nameInText(plural)}?`,
  };

  return (
    <CrmModal id="evBulkModal" open={kind !== null} onClose={onClose}>
      <form
        noValidate
        className="ev-dialog"
        onSubmit={(e) => {
          e.preventDefault();
          void submit();
        }}
      >
        <ModalHeader id="evBulkModal" title={kind ? titles[kind] : ''} onClose={onClose} />
        <div className="modal__body">
          {error ? <Alert tone="danger">{error}</Alert> : null}
          {kind === 'edit' ? (
            <>
              <p className="ev-help">
                The value you set replaces the current one on every selected {nameInText(singular)}.
                Leave it empty to clear it.
              </p>
              <div className="field">
                <label className="field__label" htmlFor="evBulkProp">
                  Property to update
                </label>
                <select
                  className="input"
                  id="evBulkProp"
                  value={prop}
                  onChange={(e) => {
                    setProp(e.target.value);
                    setValue('');
                  }}
                >
                  <option value={OWNER_FIELD}>Owner</option>
                  {defs.map((d) => (
                    <option key={d.name} value={d.name}>
                      {d.label}
                    </option>
                  ))}
                </select>
              </div>
              <div className="field">
                <label
                  className="field__label"
                  htmlFor={prop === OWNER_FIELD ? 'evBulkOwner' : 'evBulkValue'}
                >
                  New value
                </label>
                {prop === OWNER_FIELD ? (
                  ownerSelect
                ) : def ? (
                  <CustomFieldInput
                    def={{ ...def, required: false }}
                    id="evBulkValue"
                    value={value}
                    onChange={setValue}
                  />
                ) : null}
              </div>
            </>
          ) : null}
          {kind === 'assign' ? (
            <div className="field">
              <label className="field__label" htmlFor="evBulkOwner">
                Owner
              </label>
              {ownerSelect}
            </div>
          ) : null}
          {kind === 'delete' ? (
            <>
              <p>
                Delete {countText}? Their associations and activities stay linked if you restore
                them.
              </p>
              <p className="ev-help">
                Deleted {nameInText(plural)} can be brought back from{' '}
                <strong>Restore records</strong> in the ⋮ menu for 90 days.
              </p>
            </>
          ) : null}
        </div>
        <div className="modal__footer">
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="submit"
            className={cn(
              'btn-crm',
              kind === 'delete' ? 'btn-crm--danger' : 'btn-crm--primary',
              busy && 'is-loading',
            )}
            disabled={busy}
          >
            {kind === 'delete' ? 'Delete' : kind === 'assign' ? 'Assign' : 'Update'}
          </button>
        </div>
      </form>
    </CrmModal>
  );
}
