'use client';

import { useEffect, useState } from 'react';
import { ROW_HEIGHTS } from '@/features/views/columns';
import type { ViewLayout, ViewRowHeight, ViewSort } from '@/features/views/types';
import { cn } from '@/lib/utils/cn';
import type { ObjectField } from '../fields';
import { OBJECT_RECORD_SORTS, type ObjectRecordSort } from '../types';
import { Icon, type IconName } from './icons';

const VIEW_TYPES: Array<{
  value: ViewLayout | 'calendar' | 'timeline' | 'chart';
  label: string;
  icon: IconName;
}> = [
  { value: 'table', label: 'Table', icon: 'table' },
  { value: 'board', label: 'Board', icon: 'board' },
  { value: 'calendar', label: 'Calendar', icon: 'calendar' },
  { value: 'timeline', label: 'Timeline', icon: 'timeline' },
  { value: 'chart', label: 'Chart', icon: 'chart' },
];

export const SORT_LABELS: Record<ObjectRecordSort, string> = {
  displayName: 'Name',
  createdAt: 'Object create date/time',
  updatedAt: 'Object last modified date/time',
};

/**
 * `.evs`: the View settings panel beside the list (HubSpot's view sidebar): the view's name, its
 * type and type settings, the data it shows (pipeline, filters, sort), sharing and the actions
 * on the view. Calendar, timeline and chart views are not built yet.
 */
export function ViewSettingsPanel({
  open,
  onClose,
  viewName,
  isDefault,
  canEdit,
  onRename,
  layout,
  onLayout,
  rowHeight,
  onRowHeight,
  pinned,
  onPinned,
  onColumns,
  groupBy,
  groupFields,
  onGroupBy,
  hasPipeline,
  pipelines,
  pipelineId,
  allowAllPipelines,
  onPipeline,
  activeFilters,
  onFilters,
  sort,
  sortLabel,
  onSort,
  onCopyLink,
  onShare,
  onExport,
  canExport,
  dirty,
  onSave,
  onReset,
  onClone,
  onDelete,
}: {
  open: boolean;
  onClose: () => void;
  viewName: string;
  /** The built-in "All records" view: can't be renamed, shared or deleted. */
  isDefault: boolean;
  canEdit: boolean;
  onRename: (name: string) => void;
  layout: ViewLayout;
  onLayout: (layout: ViewLayout) => void;
  rowHeight: ViewRowHeight;
  onRowHeight: (height: ViewRowHeight) => void;
  pinned: boolean;
  onPinned: (pinned: boolean) => void;
  onColumns: () => void;
  groupBy: string;
  groupFields: ObjectField[];
  onGroupBy: (groupBy: string) => void;
  hasPipeline: boolean;
  pipelines: Array<{ id: string; name: string }>;
  pipelineId: string;
  /** The board always shows one pipeline, so it has no "All Pipelines". */
  allowAllPipelines: boolean;
  onPipeline: (id: string) => void;
  activeFilters: number;
  onFilters: () => void;
  sort: ViewSort;
  sortLabel: string;
  onSort: (sort: ViewSort) => void;
  onCopyLink: () => void;
  onShare: () => void;
  onExport: () => void;
  canExport: boolean;
  dirty: boolean;
  onSave: () => void;
  onReset: () => void;
  onClone: () => void;
  onDelete: () => void;
}) {
  const [page, setPage] = useState<'main' | 'type' | 'pipeline' | 'sort'>('main');
  const [name, setName] = useState(viewName);
  const editableName = !isDefault && canEdit;

  useEffect(() => setName(viewName), [viewName]);
  useEffect(() => {
    if (!open) setPage('main');
  }, [open]);

  if (!open) return null;

  const commitName = () => {
    const next = name.trim();
    if (!next) setName(viewName);
    else if (next !== viewName) onRename(next);
  };

  const pipelineLabel = pipelines.find((p) => p.id === pipelineId)?.name ?? 'All Pipelines';
  const typeLabel = layout === 'board' ? 'Board settings' : 'Table settings';

  const back = (title: string) => (
    <button type="button" className="evs__back" onClick={() => setPage('main')}>
      <Icon name="chevronLeft" size={14} />
      {title}
    </button>
  );

  return (
    <aside className="evs" id="evlSettings" aria-labelledby="evsTitle">
      <header className="evs__head">
        <h2 id="evsTitle">View settings</h2>
        <button
          type="button"
          className="ev-iconbtn"
          aria-label="Close view settings"
          onClick={onClose}
        >
          <Icon name="x" size={14} />
        </button>
      </header>
      <div className="evs__body">
        {page === 'type' ? (
          <section className="evs__sec">
            {back(typeLabel)}
            {layout === 'table' ? (
              <>
                <p className="evs__label">Row height</p>
                <div className="ev-seg" role="group" aria-label="Row height">
                  {ROW_HEIGHTS.map((h) => (
                    <button
                      key={h.value}
                      type="button"
                      aria-pressed={rowHeight === h.value}
                      onClick={() => onRowHeight(h.value)}
                    >
                      {h.label}
                    </button>
                  ))}
                </div>
                <button type="button" className="evs__row" onClick={onColumns}>
                  <Icon name="table" size={14} />
                  <span>Edit columns</span>
                  <Icon name="chevronRight" size={12} />
                </button>
                <label className="evs__row evs__row--check">
                  <input
                    type="checkbox"
                    checked={pinned}
                    onChange={(e) => onPinned(e.target.checked)}
                  />
                  <span>Pin the name column</span>
                </label>
              </>
            ) : (
              <div className="field">
                <label className="evs__label" htmlFor="evsGroupBy">
                  Group cards by
                </label>
                <select
                  id="evsGroupBy"
                  className="input"
                  value={groupBy}
                  onChange={(e) => onGroupBy(e.target.value)}
                >
                  {groupFields.map((f) => (
                    <option key={f.id} value={groupValue(f)}>
                      {f.label}
                    </option>
                  ))}
                </select>
                <p className="ev-help">
                  Drag a card to another column to change its{' '}
                  {groupFields.find((f) => groupValue(f) === groupBy)?.label.toLowerCase() ??
                    'value'}
                  .
                </p>
              </div>
            )}
          </section>
        ) : page === 'pipeline' ? (
          <section className="evs__sec">
            {back('Pipeline')}
            <div className="evs__choices" role="radiogroup" aria-label="Pipeline">
              {[
                ...(allowAllPipelines ? [{ id: '', name: 'All Pipelines' }] : []),
                ...pipelines,
              ].map((p) => (
                <label key={p.id || 'all'} className="ev-radio">
                  <input
                    type="radio"
                    name="evsPipeline"
                    checked={pipelineId === p.id}
                    onChange={() => onPipeline(p.id)}
                  />{' '}
                  {p.name}
                </label>
              ))}
            </div>
          </section>
        ) : page === 'sort' ? (
          <section className="evs__sec">
            {back('Sort by')}
            <div className="field">
              <label className="evs__label" htmlFor="evsSort">
                Sort by
              </label>
              <select
                id="evsSort"
                className="input"
                value={sort.field}
                onChange={(e) => onSort({ field: e.target.value, direction: sort.direction })}
              >
                {OBJECT_RECORD_SORTS.map((s) => (
                  <option key={s} value={s}>
                    {SORT_LABELS[s]}
                  </option>
                ))}
              </select>
            </div>
            <div className="ev-seg" role="group" aria-label="Sort direction">
              <button
                type="button"
                aria-pressed={sort.direction === 'asc'}
                onClick={() => onSort({ field: sort.field, direction: 'asc' })}
              >
                Ascending
              </button>
              <button
                type="button"
                aria-pressed={sort.direction === 'desc'}
                onClick={() => onSort({ field: sort.field, direction: 'desc' })}
              >
                Descending
              </button>
            </div>
          </section>
        ) : (
          <>
            <section className="evs__sec">
              <label className="evs__label" htmlFor="evsName">
                Name
              </label>
              <input
                id="evsName"
                className="input"
                value={name}
                maxLength={100}
                disabled={!editableName}
                onChange={(e) => setName(e.target.value)}
                onBlur={commitName}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault();
                    commitName();
                  }
                }}
              />
              {isDefault ? (
                <p className="ev-help">
                  The default view can&apos;t be renamed. Save it as a new view to name it.
                </p>
              ) : !canEdit ? (
                <p className="ev-help">Only the owner of this view can rename it.</p>
              ) : null}
            </section>

            <section className="evs__sec">
              <p className="evs__label">View type</p>
              <div className="evs__types" role="radiogroup" aria-label="View type">
                {VIEW_TYPES.map((t) => {
                  const built = t.value === 'table' || t.value === 'board';
                  return (
                    <button
                      key={t.value}
                      type="button"
                      role="radio"
                      className={cn('evs__type', layout === t.value && 'is-on')}
                      aria-checked={layout === t.value}
                      aria-label={built ? t.label : `${t.label} (coming soon)`}
                      title={built ? t.label : `${t.label} views are coming soon`}
                      disabled={!built}
                      onClick={() => built && onLayout(t.value as ViewLayout)}
                    >
                      <Icon name={t.icon} size={14} />
                    </button>
                  );
                })}
              </div>
              <button type="button" className="evs__row" onClick={() => setPage('type')}>
                <Icon name={layout === 'board' ? 'board' : 'table'} size={14} />
                <span>{typeLabel}</span>
                <Icon name="chevronRight" size={12} />
              </button>
            </section>

            <section className="evs__sec">
              <p className="evs__label">Data</p>
              {hasPipeline ? (
                <button type="button" className="evs__row" onClick={() => setPage('pipeline')}>
                  <span>Pipeline</span>
                  <span className="evs__value">{pipelineLabel}</span>
                  <Icon name="chevronRight" size={12} />
                </button>
              ) : null}
              <button type="button" className="evs__row" onClick={onFilters}>
                <Icon name="filter" size={14} />
                <span>Filters</span>
                {activeFilters > 0 ? <span className="evs__value">{activeFilters}</span> : null}
                <Icon name="chevronRight" size={12} />
              </button>
              <button type="button" className="evs__row" onClick={() => setPage('sort')}>
                <Icon name="sort" size={14} />
                <span>Sort by</span>
                <span className="evs__value">{sortLabel}</span>
                <Icon name="chevronRight" size={12} />
              </button>
            </section>

            <section className="evs__sec">
              <p className="evs__label">Sharing</p>
              <button type="button" className="evs__row" onClick={onCopyLink}>
                <Icon name="link" size={14} />
                <span>Copy link to view</span>
              </button>
              <button
                type="button"
                className="evs__row"
                disabled={isDefault || !canEdit}
                title={isDefault ? 'The default view is shared with everyone' : undefined}
                onClick={onShare}
              >
                <Icon name="share" size={14} />
                <span>Manage sharing</span>
              </button>
              <button
                type="button"
                className="evs__row"
                disabled={!canExport}
                title={canExport ? undefined : 'You do not have export access'}
                onClick={onExport}
              >
                <Icon name="upload" size={14} />
                <span>Export</span>
                <kbd className="evs__kbd">Ctrl+Shift+X</kbd>
              </button>
            </section>

            <section className="evs__sec">
              <p className="evs__label">Actions</p>
              <button type="button" className="evs__row" disabled={!dirty} onClick={onSave}>
                <Icon name="save" size={14} />
                <span>Save changes</span>
                <kbd className="evs__kbd">Ctrl+S</kbd>
              </button>
              <button type="button" className="evs__row" disabled={!dirty} onClick={onReset}>
                <Icon name="undo" size={14} />
                <span>Reset to last save</span>
              </button>
              <button type="button" className="evs__row" onClick={onClone}>
                <Icon name="copy" size={14} />
                <span>Clone to new view</span>
              </button>
            </section>

            <section className="evs__sec evs__sec--danger">
              <button
                type="button"
                className="evs__row evs__row--danger"
                disabled={isDefault || !canEdit}
                onClick={onDelete}
              >
                <Icon name="trash" size={14} />
                <span>Delete view</span>
              </button>
              {isDefault ? (
                <p className="ev-help">The default view can&apos;t be deleted.</p>
              ) : null}
            </section>
          </>
        )}
      </div>
    </aside>
  );
}

/** The board's `groupBy` for a field: `stage`, `owner` or `custom.<name>`. */
export function groupValue(field: ObjectField): string {
  if (field.kind === 'stage') return 'stage';
  if (field.kind === 'owner') return 'owner';
  return field.id;
}
