'use client';

import Link from 'next/link';
import { useCallback, useEffect, useRef, useState } from 'react';
import { CrmModal, Field, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { listCompanies } from '@/features/companies/api.client';
import { listContacts } from '@/features/contacts/api.client';
import {
  CustomFieldsForm,
  customValuesForCreate,
  type CustomUiValue,
} from '@/features/contacts/ui/actions/custom-fields';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { listDeals } from '@/features/deals/api.client';
import { SameNameDealsWarning, useSameNameDeals } from '@/features/deals/ui/SameNameDeals';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import type { CustomProperties } from '@/types/api';
import type { AssociationLinkInput } from '../types';
import { associationErrorText, LabelChecklist, useAssociationLabels } from './shared';

export type DesignAddTarget = 'contact' | 'company' | 'deal';
type Sort = 'recent' | 'az' | 'za';

const ONE: Record<DesignAddTarget, string> = {
  contact: 'Contact',
  company: 'Company',
  deal: 'Deal',
};
const MANY: Record<DesignAddTarget, string> = {
  contact: 'Contacts',
  company: 'Companies',
  deal: 'Deals',
};
const PAGE = 50;

/** One record of the Add existing list: name, and "(domain)", "(email)" or "(stage)". */
export interface PickRow {
  id: string;
  name: string;
  sub: string;
}

/** R6a/R6b: a page of the target's own list, searched and sorted as the design's picker. */
export async function loadPickPage(
  target: DesignAddTarget,
  search: string,
  sort: Sort,
  cursor?: string,
): Promise<{ rows: PickRow[]; nextCursor: string | null; total: number | null }> {
  const q = search.trim() || undefined;
  const field = sort === 'recent' ? 'createdAt' : 'name';
  const dir = sort === 'za' ? 'desc' : sort === 'az' ? 'asc' : 'desc';
  if (target === 'contact') {
    const page = await listContacts({
      search: q,
      searchMode: 'contains',
      sort: `${field}:${dir}`,
      limit: PAGE,
      cursor,
    });
    return {
      rows: page.data.map((c) => ({
        id: c.id,
        name: [c.firstName, c.lastName].filter(Boolean).join(' ') || c.email || 'Untitled',
        sub: c.email ? `(${c.email})` : '',
      })),
      nextCursor: page.nextCursor,
      total: page.total ?? null,
    };
  }
  if (target === 'company') {
    const page = await listCompanies({
      search: q,
      searchMode: 'contains',
      sort: `${field}:${dir}`,
      limit: PAGE,
      cursor,
    });
    return {
      rows: page.data.map((c) => ({
        id: c.id,
        name: c.name,
        sub: c.domain ? `(${c.domain})` : '',
      })),
      nextCursor: page.nextCursor,
      total: page.total ?? null,
    };
  }
  const page = await listDeals({ search: q, sort: field, direction: dir, limit: PAGE, cursor });
  return {
    rows: page.data.map((d) => ({
      id: d.id,
      name: d.name,
      sub: d.stage?.name ? `(${d.stage.name})` : '',
    })),
    nextCursor: page.nextCursor,
    total: page.total ?? null,
  };
}

/** The design's Create new fields per object (record-tabs.js:801-803). */
const CREATE_FIELDS: Record<
  DesignAddTarget,
  Array<{ name: string; label: string; required: boolean; type: 'text' | 'email' | 'number' }>
> = {
  company: [
    { name: 'domain', label: 'Company domain name', required: true, type: 'text' },
    { name: 'name', label: 'Company name', required: true, type: 'text' },
  ],
  contact: [
    { name: 'email', label: 'Email', required: true, type: 'email' },
    { name: 'firstName', label: 'First name', required: false, type: 'text' },
  ],
  deal: [
    { name: 'name', label: 'Deal name', required: true, type: 'text' },
    { name: 'amount', label: 'Amount', required: false, type: 'number' },
  ],
};

/**
 * R6b: "+ Add" on the contact and company record pages' association cards, as the 28 Oct
 * design's panel (record-tabs.js:781-852). "Add existing": search, "N <Many>", the sort,
 * checkboxes (linked records ticked and off), Step 1 of 2 → Step 2 of 2 (labels and, for a
 * company, Primary), Save. "Create new": the design's fields plus the object's required custom
 * properties (the user's call, 19 Nov), Create / Create and add another / Cancel. `link` makes
 * one link without a toast or reload; `onDone` reloads once.
 */
export function AddAssociationDesignDrawer({
  id,
  open,
  onClose,
  anchorType,
  targetType,
  linkedIds,
  allowPrimary = false,
  primaryEach = false,
  canCreate,
  editFormHref,
  link,
  create,
  onDone,
}: {
  id: string;
  open: boolean;
  onClose: () => void;
  /** The page's record type, for the association labels it offers (DR4a: deals too). */
  anchorType: 'contact' | 'company' | 'deal';
  targetType: DesignAddTarget;
  /** Records already linked: shown ticked and off. */
  linkedIds: string[];
  /** Offer Primary in step 2 (company links of a contact). */
  allowPrimary?: boolean;
  /**
   * CQS1 #140 (a company's contacts): Primary may go to every picked record, each getting the
   * anchor as its primary (a company can be primary for many contacts). Off: one record only.
   */
  primaryEach?: boolean;
  /** May create the target object: the Create new tab. */
  canCreate: boolean;
  /** "Edit this form ↗" (admins only), or none. */
  editFormHref?: string;
  link: (input: AssociationLinkInput) => Promise<void>;
  /** Creates the record and links it; resolves to its name. */
  create: (values: Record<string, string>, custom: CustomProperties) => Promise<string>;
  onDone: () => Promise<void>;
}) {
  const toast = useToast();
  const prefs = useUserPrefs();
  const one = ONE[targetType];
  const many = MANY[targetType];
  const [tab, setTab] = useState<'existing' | 'create'>('existing');
  const [step, setStep] = useState<1 | 2>(1);
  const [query, setQuery] = useState('');
  const [sort, setSort] = useState<Sort>('recent');
  const [rows, setRows] = useState<PickRow[] | null>(null);
  const [total, setTotal] = useState<number | null>(null);
  const [cursor, setCursor] = useState<string | null>(null);
  const [loadFailed, setLoadFailed] = useState(false);
  const [picked, setPicked] = useState<Map<string, PickRow>>(new Map());
  const [primary, setPrimary] = useState(false);
  const [labelIds, setLabelIds] = useState<Set<string>>(new Set());
  const [busy, setBusy] = useState(false);
  const [values, setValues] = useState<Record<string, string>>({});
  // DL14: a new deal warns about deals of the same name, as Create deal (contacts, companies as before).
  const sameName = useSameNameDeals(
    open && tab === 'create' && targetType === 'deal',
    values.name ?? '',
  );
  const [customDefs, setCustomDefs] = useState<CustomPropertyDefinition[]>([]);
  const [customValues, setCustomValues] = useState<Record<string, CustomUiValue>>({});
  const reqRef = useRef(0);
  const loadingMore = useRef(false);
  const linked = new Set(linkedIds);

  useEffect(() => {
    if (!open) return;
    setTab('existing');
    setStep(1);
    setQuery('');
    setSort('recent');
    setPicked(new Map());
    setPrimary(false);
    setLabelIds(new Set());
    setValues({});
    setCustomValues({});
  }, [open]);

  // The object's required custom properties, for Create new (the API refuses a create without).
  useEffect(() => {
    if (!open || !canCreate) return;
    let alive = true;
    listCustomProperties({ objectType: targetType }).then(
      (defs) => alive && setCustomDefs(defs.filter((d) => d.required && !d.archived)),
      () => alive && setCustomDefs([]),
    );
    return () => {
      alive = false;
    };
  }, [open, canCreate, targetType]);

  const load = useCallback(
    (fresh: boolean, after?: string) => {
      const req = ++reqRef.current;
      if (fresh) {
        setRows(null);
        setLoadFailed(false);
      }
      loadingMore.current = true;
      loadPickPage(targetType, query, sort, after).then(
        (page) => {
          if (req !== reqRef.current) return;
          setRows((prev) => (fresh || !prev ? page.rows : [...prev, ...page.rows]));
          setTotal(page.total);
          setCursor(page.nextCursor);
          loadingMore.current = false;
        },
        () => {
          if (req !== reqRef.current) return;
          setLoadFailed(true);
          loadingMore.current = false;
        },
      );
    },
    [targetType, query, sort],
  );

  // Step 1's list, again on each search (a short pause after typing) and sort.
  useEffect(() => {
    if (!open || tab !== 'existing' || step !== 1) return;
    const t = setTimeout(() => load(true), query ? 250 : 0);
    return () => clearTimeout(t);
  }, [open, tab, step, query, sort, load]);

  const {
    labels,
    loaded,
    failed: labelsFailed,
  } = useAssociationLabels(anchorType, targetType, open);

  const togglePick = (row: PickRow, on: boolean) =>
    setPicked((prev) => {
      const next = new Map(prev);
      if (on) next.set(row.id, row);
      else next.delete(row.id);
      return next;
    });

  const save = async () => {
    const list = [...picked.values()];
    if (!list.length) return;
    if (!loaded || labelsFailed) {
      toast(
        labelsFailed
          ? 'Labels could not be loaded. Try again before adding.'
          : 'Still loading labels…',
        'danger',
        { durationMs: 8000 },
      );
      return;
    }
    setBusy(true);
    const failures: string[] = [];
    for (const row of list) {
      try {
        await link({
          record: { id: row.id, type: targetType, title: row.name, subtitle: null },
          isPrimary: allowPrimary && primary && (primaryEach || list.length === 1),
          labelIds: [...labelIds],
          inverseLabelIds: [],
        });
      } catch (err) {
        failures.push(associationErrorText(err));
      }
    }
    const done = list.length - failures.length;
    if (done) await onDone();
    setBusy(false);
    if (!failures.length) {
      toast(`${done} ${done === 1 ? one.toLowerCase() : many.toLowerCase()} associated`);
      onClose();
      return;
    }
    toast(
      failures.length === 1 && !done
        ? failures[0]!
        : `${done} associated, ${failures.length} not: ${failures[0]}`,
      'danger',
      { durationMs: 8000 },
    );
  };

  const fields = CREATE_FIELDS[targetType];
  const runCreate = async (again: boolean) => {
    const missing = fields.find((f) => f.required && !values[f.name]?.trim());
    if (missing) {
      toast('Fill in the required fields', 'danger');
      document.getElementById(`${id}-c-${missing.name}`)?.focus();
      return;
    }
    const custom = customValuesForCreate(customDefs, customValues, prefs.timeZone);
    if ('error' in custom) {
      toast(custom.error, 'danger');
      return;
    }
    setBusy(true);
    try {
      const trimmed = Object.fromEntries(fields.map((f) => [f.name, values[f.name]?.trim() ?? '']));
      await create(trimmed, custom.value);
      await onDone();
      toast(`1 ${one.toLowerCase()} associated`);
      if (again) {
        setValues({});
        setCustomValues({});
        document.getElementById(`${id}-c-${fields[0]!.name}`)?.focus();
      } else {
        onClose();
      }
    } catch (err) {
      toast(associationErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  const title = tab === 'create' ? `Create ${one}` : `Add existing ${one}`;
  const shownTotal = total ?? rows?.length ?? 0;

  return (
    <CrmModal id={id} open={open} onClose={onClose} drawer className="aad">
      <ModalHeader id={id} title={title} onClose={onClose} />
      {canCreate ? (
        <nav className="aad-tabs" role="tablist" aria-label={`Add ${one.toLowerCase()}`}>
          {(['create', 'existing'] as const).map((t) => (
            <button
              key={t}
              type="button"
              role="tab"
              aria-selected={tab === t}
              className={tab === t ? 'is-on' : undefined}
              onClick={() => {
                setTab(t);
                setStep(1);
              }}
            >
              {t === 'create' ? 'Create new' : 'Add existing'}
            </button>
          ))}
        </nav>
      ) : null}

      {tab === 'create' ? (
        <>
          <div className="modal__body aad-body">
            {editFormHref ? (
              <p className="aad-right">
                <Link href={editFormHref} target="_blank" rel="noopener">
                  Edit this form ↗
                </Link>
              </p>
            ) : null}
            {fields.map((f) => (
              <Field
                key={f.name}
                label={f.required ? `${f.label} *` : f.label}
                htmlFor={`${id}-c-${f.name}`}
              >
                <input
                  id={`${id}-c-${f.name}`}
                  className="input"
                  type={f.type}
                  value={values[f.name] ?? ''}
                  aria-required={f.required || undefined}
                  onChange={(e) => setValues((v) => ({ ...v, [f.name]: e.target.value }))}
                />
                {f.name === 'name' && targetType === 'deal' ? (
                  <SameNameDealsWarning deals={sameName} />
                ) : null}
              </Field>
            ))}
            {customDefs.length ? (
              <CustomFieldsForm
                defs={customDefs}
                values={customValues}
                onChange={(name, value) => setCustomValues((v) => ({ ...v, [name]: value }))}
                idPrefix={`${id}-cf`}
                timeZone={prefs.timeZone}
                designLabels
              />
            ) : null}
          </div>
          <div className="modal__footer">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={busy}
              onClick={() => void runCreate(false)}
            >
              Create
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              disabled={busy}
              onClick={() => void runCreate(true)}
            >
              Create and add another
            </button>
            <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
              Cancel
            </button>
          </div>
        </>
      ) : step === 2 ? (
        <>
          <div className="modal__body aad-body">
            <p>
              Choose an association label for the {picked.size} selected{' '}
              {picked.size === 1 ? one.toLowerCase() : many.toLowerCase()}.
            </p>
            {allowPrimary ? (
              <div className="aad-radios" role="radiogroup" aria-label="Association">
                <label>
                  <input
                    type="radio"
                    name={`${id}-primary`}
                    checked={!primary}
                    onChange={() => setPrimary(false)}
                  />{' '}
                  Unlabeled
                </label>
                <label
                  title={
                    !primaryEach && picked.size > 1 ? 'Only one company can be primary' : undefined
                  }
                >
                  <input
                    type="radio"
                    name={`${id}-primary`}
                    checked={primary}
                    disabled={!primaryEach && picked.size > 1}
                    onChange={() => setPrimary(true)}
                  />{' '}
                  Primary
                </label>
              </div>
            ) : null}
            {/* Master's link labels, kept (the user's call, 19 Nov). */}
            {!loaded ? (
              <p className="crm-text-body-secondary">Loading labels…</p>
            ) : labelsFailed ? (
              <p className="crm-text-body-secondary">Labels could not be loaded.</p>
            ) : labels.length ? (
              <LabelChecklist
                labels={labels.map((l) => ({ id: l.id, name: l.name }))}
                selected={labelIds}
                onChange={setLabelIds}
              />
            ) : null}
          </div>
          <div className="modal__footer aad-foot">
            <span className="aad-step">Step 2 of 2</span>
            <button type="button" className="btn-crm btn-crm--outline" onClick={() => setStep(1)}>
              Back
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={busy}
              onClick={() => void save()}
            >
              Save
            </button>
          </div>
        </>
      ) : (
        <>
          <div
            className="modal__body aad-body"
            onScroll={(e) => {
              const el = e.currentTarget;
              if (
                cursor &&
                !loadingMore.current &&
                el.scrollTop + el.clientHeight > el.scrollHeight - 80
              ) {
                load(false, cursor);
              }
            }}
          >
            <input
              className="input aad-search"
              type="search"
              placeholder={`Search ${many}`}
              aria-label={`Search ${many}`}
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
            <div className="aad-pickhead">
              <strong>
                {shownTotal.toLocaleString()} {many}
              </strong>
              <select
                className="input aad-sort"
                aria-label="Sort"
                value={sort}
                onChange={(e) => setSort(e.target.value as Sort)}
              >
                <option value="recent">Default (Recently added)</option>
                <option value="az">Name (A to Z)</option>
                <option value="za">Name (Z to A)</option>
              </select>
            </div>
            {loadFailed ? (
              <p className="aad-note" role="alert">
                Couldn&apos;t load {many.toLowerCase()}.{' '}
                <button type="button" className="rp-link--btn" onClick={() => load(true)}>
                  Retry
                </button>
              </p>
            ) : rows === null ? (
              <p className="aad-note">Loading…</p>
            ) : rows.length === 0 ? (
              <p className="aad-note">No {many.toLowerCase()} match your search.</p>
            ) : (
              <div className="aad-list">
                {rows.map((r) => {
                  const isLinked = linked.has(r.id);
                  return (
                    <label key={r.id} className={isLinked ? 'aad-pick is-dis' : 'aad-pick'}>
                      <input
                        type="checkbox"
                        checked={isLinked || picked.has(r.id)}
                        disabled={isLinked}
                        onChange={(e) => togglePick(r, e.target.checked)}
                      />
                      <span>
                        {r.name}
                        {r.sub ? <small> {r.sub}</small> : null}
                      </span>
                    </label>
                  );
                })}
              </div>
            )}
          </div>
          <div className="modal__footer aad-foot">
            <span className="aad-step">Step 1 of 2</span>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={picked.size === 0}
              onClick={() => setStep(2)}
            >
              Next ›
            </button>
          </div>
        </>
      )}
    </CrmModal>
  );
}
