'use client';

import { useEffect, useState } from 'react';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { LOCKED_COLUMNS, type ObjectColumn } from '../columns';
import { Icon } from './icons';

/**
 * "Choose which columns you see": properties on the left (search, tick to add), the chosen
 * columns on the right in order (move up / down, remove). The name column is locked first.
 */
export function ColumnsModal({
  open,
  onClose,
  singular,
  catalog,
  columns,
  onApply,
}: {
  open: boolean;
  onClose: () => void;
  singular: string;
  catalog: ObjectColumn[];
  /** Ids shown now, in order. */
  columns: string[];
  onApply: (ids: string[]) => void;
}) {
  const [picked, setPicked] = useState<string[]>(columns);
  const [query, setQuery] = useState('');

  useEffect(() => {
    if (open) {
      setPicked(columns);
      setQuery('');
    }
  }, [open, columns]);

  const byId = new Map(catalog.map((c) => [c.id, c]));
  const q = query.trim().toLowerCase();
  const matches = (c: ObjectColumn) => !q || c.label.toLowerCase().includes(q);
  const groups: Array<{ title: string; items: ObjectColumn[] }> = [
    {
      title: `${singular} properties`,
      items: catalog.filter((c) => c.group !== 'links' && matches(c)),
    },
    { title: 'Associations', items: catalog.filter((c) => c.group === 'links' && matches(c)) },
  ];
  const toggle = (id: string) =>
    setPicked((cur) => (cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id]));
  const move = (index: number, by: -1 | 1) =>
    setPicked((cur) => {
      const target = index + by;
      // The locked name column stays first.
      if (target < 1 || target >= cur.length) return cur;
      const next = cur.slice();
      [next[index], next[target]] = [next[target]!, next[index]!];
      return next;
    });
  const unsaved = picked.some((id) => byId.get(id)?.savable === false);

  return (
    <CrmModal id="evFormModal" open={open} onClose={onClose} size="wide">
      <form
        noValidate
        className="evc-form"
        onSubmit={(e) => {
          e.preventDefault();
          onApply(picked);
          onClose();
        }}
      >
        <ModalHeader id="evFormModal" title="Choose which columns you see" onClose={onClose} />
        <div className="modal__body">
          <div className="evc">
            <div className="evc__col">
              <div className="ev-search">
                <input
                  type="search"
                  className="input"
                  placeholder="Search properties"
                  aria-label="Search properties"
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                />
                <Icon name="search" size={14} />
              </div>
              <div className="evc__list">
                {groups.map((group) =>
                  group.items.length > 0 ? (
                    <div key={group.title} className="evc__group">
                      <p className="evc__head">{group.title}</p>
                      {group.items.map((c) => {
                        const locked = LOCKED_COLUMNS.includes(c.id);
                        return (
                          <label key={c.id} className="ev-check">
                            <input
                              type="checkbox"
                              checked={locked || picked.includes(c.id)}
                              disabled={locked}
                              onChange={() => toggle(c.id)}
                            />
                            <span>{c.label}</span>
                          </label>
                        );
                      })}
                    </div>
                  ) : null,
                )}
                {groups.every((g) => g.items.length === 0) ? (
                  <p className="ev-help">No properties match.</p>
                ) : null}
              </div>
            </div>
            <div className="evc__col evc__col--sel">
              <p className="evc__head">{picked.length} selected columns</p>
              <ol className="evc__order">
                {picked.map((id, index) => {
                  const column = byId.get(id);
                  if (!column) return null;
                  const locked = LOCKED_COLUMNS.includes(id);
                  return (
                    <li key={id} className="evc__item">
                      <span className="evc__name">{column.label}</span>
                      {locked ? (
                        <span className="evc__locked">Locked</span>
                      ) : (
                        <span className="evc__tools">
                          <button
                            type="button"
                            aria-label={`Move ${column.label} up`}
                            disabled={index <= 1}
                            onClick={() => move(index, -1)}
                          >
                            <Icon name="sortUp" size={12} />
                          </button>
                          <button
                            type="button"
                            aria-label={`Move ${column.label} down`}
                            disabled={index >= picked.length - 1}
                            onClick={() => move(index, 1)}
                          >
                            <Icon name="sortDown" size={12} />
                          </button>
                          <button
                            type="button"
                            aria-label={`Remove ${column.label}`}
                            onClick={() => toggle(id)}
                          >
                            <Icon name="x" size={12} />
                          </button>
                        </span>
                      )}
                    </li>
                  );
                })}
              </ol>
              {unsaved ? (
                <p className="ev-help evc__note">
                  Association columns show on this page but are not saved with a view yet.
                </p>
              ) : null}
            </div>
          </div>
        </div>
        <div className="modal__footer">
          <button
            type="button"
            className="ev-link evc__reset"
            onClick={() => setPicked(picked.filter((id) => LOCKED_COLUMNS.includes(id)))}
          >
            Remove all columns
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          <button type="submit" className="btn-crm btn-crm--primary">
            Apply
          </button>
        </div>
      </form>
    </CrmModal>
  );
}
