'use client';

import { useEffect, useMemo, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { cn } from '@/lib/utils/cn';
import { LAYOUT_LABELS, ROW_HEIGHTS, sameList, type ColumnOption } from '../columns';
import type { ViewLayout, ViewRowHeight } from '../types';
import type { ViewDisplaySettings } from '../useViewDisplay';

/** The "View settings" button next to Sort by on every list. */
export function ViewSettingsButton({
  onClick,
  active,
  disabled,
  title,
}: {
  onClick: () => void;
  active?: boolean;
  disabled?: boolean;
  title?: string;
}) {
  return (
    <button
      type="button"
      className={cn('btn-crm btn-crm--outline crm-gap-1 crm-px-3', active && 'is-active')}
      aria-haspopup="dialog"
      disabled={disabled}
      title={title}
      onClick={onClick}
    >
      <CrmIcon name="columns" className="iconSize-16" />
      <span>View settings</span>
    </button>
  );
}

type Props = {
  /** Unique per list (`contact-view-settings`). */
  id: string;
  open: boolean;
  onClose: () => void;
  /** Every column the list can show, standard and custom fields. */
  catalog: ColumnOption[];
  /** The columns shown now, in order. */
  columns: string[];
  /** The list's own columns, for "Reset to default". */
  defaultColumns: string[];
  /** Columns that cannot be removed (the one linking to the record). */
  lockedColumns?: string[];
  rowHeight: ViewRowHeight;
  layout: ViewLayout;
  /** Layouts this list offers; the switch shows only when there is more than one. */
  layouts?: ViewLayout[];
  onApply: (settings: ViewDisplaySettings) => void;
};

/**
 * Side panel to edit a list's columns (search, add, remove, drag to reorder; custom fields
 * included), row height and, where the list has one, the layout (table / board). "Apply"
 * hands the draft to the page, which shows it at once; it is stored in the view with the
 * existing "Save view" / "Save as new" buttons of ViewTabs.
 */
export function ViewSettingsPanel(props: Props) {
  const { id, open, onClose } = props;
  // Remount the body on every open so the draft starts from what the page shows.
  const [session, setSession] = useState(0);
  useEffect(() => {
    if (open) setSession((s) => s + 1);
  }, [open]);

  return (
    <CrmModal id={id} open={open} onClose={onClose} drawer>
      <ModalHeader id={id} title="View settings" onClose={onClose} />
      <PanelBody key={session} {...props} />
    </CrmModal>
  );
}

function PanelBody({
  catalog,
  columns,
  defaultColumns,
  lockedColumns = [],
  rowHeight,
  layout,
  layouts = ['table'],
  onApply,
  onClose,
}: Props) {
  const [draft, setDraft] = useState<string[]>(columns);
  const [height, setHeight] = useState<ViewRowHeight>(rowHeight);
  const [chosenLayout, setChosenLayout] = useState<ViewLayout>(layout);
  const [search, setSearch] = useState('');
  const [dragIndex, setDragIndex] = useState<number | null>(null);
  const [overIndex, setOverIndex] = useState<number | null>(null);

  const byId = useMemo(() => new Map(catalog.map((c) => [c.id, c])), [catalog]);
  const selected = useMemo(
    () => draft.map((cid) => byId.get(cid)).filter((c): c is ColumnOption => Boolean(c)),
    [draft, byId],
  );
  const available = useMemo(() => {
    const taken = new Set(draft);
    const q = search.trim().toLowerCase();
    return catalog.filter((c) => !taken.has(c.id) && (!q || c.label.toLowerCase().includes(q)));
  }, [catalog, draft, search]);
  const availableStandard = available.filter((c) => c.group === 'standard');
  const availableCustom = available.filter((c) => c.group === 'custom');

  const changed = !sameList(draft, columns) || height !== rowHeight || chosenLayout !== layout;

  const move = (from: number, to: number) => {
    if (from === to || to < 0 || to >= draft.length) return;
    setDraft((cur) => {
      const next = cur.slice();
      const [item] = next.splice(from, 1);
      next.splice(to, 0, item!);
      return next;
    });
  };
  const remove = (cid: string) => setDraft((cur) => cur.filter((c) => c !== cid));
  const add = (cid: string) => setDraft((cur) => [...cur, cid]);

  const endDrag = () => {
    setDragIndex(null);
    setOverIndex(null);
  };

  const apply = () => {
    onApply({ columns: draft, rowHeight: height, layout: chosenLayout });
    onClose();
  };

  const renderAvailable = (title: string, list: ColumnOption[]) =>
    list.length === 0 ? null : (
      <div className="view-settings__group">
        <p className="view-settings__group-title">{title}</p>
        <ul className="view-settings__list" aria-label={title}>
          {list.map((col) => (
            <li key={col.id} className="view-settings__item">
              <span className="view-settings__label">{col.label}</span>
              <button
                type="button"
                className="icon-btn iconSize-28"
                aria-label={`Add ${col.label} column`}
                onClick={() => add(col.id)}
              >
                <CrmIcon name="plus" className="iconSize-16" />
              </button>
            </li>
          ))}
        </ul>
      </div>
    );

  return (
    <form
      noValidate
      onSubmit={(e) => {
        e.preventDefault();
        if (changed) apply();
      }}
    >
      <div className="modal__body view-settings">
        {layouts.length > 1 ? (
          <section className="field">
            <span className="field__label" id="view-settings-layout">
              Layout
            </span>
            <div
              className="view-settings__segmented"
              role="radiogroup"
              aria-labelledby="view-settings-layout"
            >
              {layouts.map((value) => (
                <button
                  key={value}
                  type="button"
                  role="radio"
                  aria-checked={chosenLayout === value}
                  className={cn(
                    'btn-crm btn-crm--outline btn-crm--sm',
                    chosenLayout === value && 'crm-bg-primary-subtle is-active',
                  )}
                  onClick={() => setChosenLayout(value)}
                >
                  {LAYOUT_LABELS[value]}
                </button>
              ))}
            </div>
            {chosenLayout === 'board' ? (
              <p className="crm-fs-8 crm-text-muted crm-mt-2">
                The board shows deal cards by stage; columns and row height apply to the table.
              </p>
            ) : null}
          </section>
        ) : null}

        <section className="field">
          <span className="field__label" id="view-settings-row-height">
            Row height
          </span>
          <div
            className="view-settings__segmented"
            role="radiogroup"
            aria-labelledby="view-settings-row-height"
          >
            {ROW_HEIGHTS.map((option) => (
              <button
                key={option.value}
                type="button"
                role="radio"
                aria-checked={height === option.value}
                className={cn(
                  'btn-crm btn-crm--outline btn-crm--sm',
                  height === option.value && 'crm-bg-primary-subtle is-active',
                )}
                onClick={() => setHeight(option.value)}
              >
                {option.label}
              </button>
            ))}
          </div>
        </section>

        <section className="field">
          <div className="view-settings__heading">
            <span className="field__label">Columns ({selected.length})</span>
            <button
              type="button"
              className="btn-crm btn-crm--ghost btn-crm--sm"
              disabled={sameList(draft, defaultColumns)}
              onClick={() => setDraft(defaultColumns)}
            >
              Reset to default
            </button>
          </div>
          <ul className="view-settings__list" aria-label="Shown columns">
            {selected.map((col, index) => {
              const locked = lockedColumns.includes(col.id);
              return (
                <li
                  key={col.id}
                  className={cn(
                    'view-settings__item is-selected',
                    dragIndex === index && 'is-dragging',
                    overIndex === index && dragIndex !== index && 'is-over',
                  )}
                  draggable
                  onDragStart={(e) => {
                    e.dataTransfer.effectAllowed = 'move';
                    e.dataTransfer.setData('text/plain', col.id);
                    setDragIndex(index);
                  }}
                  onDragOver={(e) => {
                    if (dragIndex === null) return;
                    e.preventDefault();
                    setOverIndex(index);
                  }}
                  onDrop={(e) => {
                    e.preventDefault();
                    if (dragIndex !== null) move(dragIndex, index);
                    endDrag();
                  }}
                  onDragEnd={endDrag}
                >
                  <button
                    type="button"
                    className="view-settings__grip"
                    aria-label={`Reorder ${col.label}: drag, or use the up and down arrow keys`}
                    onKeyDown={(e) => {
                      if (e.key === 'ArrowUp') {
                        e.preventDefault();
                        move(index, index - 1);
                      } else if (e.key === 'ArrowDown') {
                        e.preventDefault();
                        move(index, index + 1);
                      }
                    }}
                  >
                    <CrmIcon name="grip" className="iconSize-16" />
                  </button>
                  <span className="view-settings__label">
                    {col.label}
                    {col.group === 'custom' ? (
                      <span className="view-settings__badge">Custom</span>
                    ) : null}
                  </span>
                  <button
                    type="button"
                    className={cn('icon-btn iconSize-28', locked && 'is-locked')}
                    aria-label={
                      locked ? `${col.label} cannot be removed` : `Remove ${col.label} column`
                    }
                    title={locked ? 'This column cannot be removed' : undefined}
                    disabled={locked || selected.length <= 1}
                    onClick={() => remove(col.id)}
                  >
                    <CrmIcon name="x" className="iconSize-16" />
                  </button>
                </li>
              );
            })}
          </ul>
        </section>

        <section className="field">
          <span className="field__label">Add columns</span>
          <div className="search-input crm-mb-2">
            <CrmIcon name="search" className="iconSize-16" />
            <input
              className="input crm-h-auto"
              type="search"
              placeholder="Search columns"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              aria-label="Search columns"
            />
          </div>
          {available.length === 0 ? (
            <p className="crm-fs-8 crm-text-muted">
              {search.trim() ? 'No columns match your search.' : 'Every column is already shown.'}
            </p>
          ) : (
            <>
              {renderAvailable('Properties', availableStandard)}
              {renderAvailable('Custom fields', availableCustom)}
            </>
          )}
        </section>
        <p className="crm-fs-8 crm-text-muted">
          Apply shows the changes on this page. Use &quot;Save view&quot; above the list to keep
          them in the view.
        </p>
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
        <button type="submit" className="btn-crm btn-crm--primary" disabled={!changed}>
          Apply
        </button>
      </div>
    </form>
  );
}
