'use client';

/**
 * B12 All views' dialogs, exactly as the 6 Nov design draws them (view-all.js:88-101, :207-308):
 * Rename, Delete, Manage sharing, Clone, Export, and the Standard views drawer's Clone and info
 * dialogs. They hold their own fields; the page does the API calls (`onSubmit` resolves true when
 * done; on a refusal the page shows the API's message in its toast and the dialog stays open).
 */
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import type { Owner } from '@/features/owners/api.client';
import type { View, ViewShareMember } from '@/features/views/types';
import { includedData, type ExportAssociationChoice, type ExportScope } from '../actions';
import { initials, VIEW_NAME_MAX } from '../allViews';
import type { ManageExportFormat } from '../exportFile';
import { Avatar, Caret, MvaDialog, SmallSearchIcon } from './parts';

type Submit<T> = (value: T) => Promise<boolean>;

function useSubmit<T>(onSubmit: Submit<T>) {
  const [busy, setBusy] = useState(false);
  const run = async (value: T) => {
    if (busy) return;
    setBusy(true);
    await onSubmit(value);
    setBusy(false);
  };
  return { busy, run };
}

/** "Rename saved view" (view-all.js:88): Cancel, Save. */
export function RenameDialog({
  view,
  onClose,
  onSubmit,
}: {
  view: View;
  onClose: () => void;
  onSubmit: Submit<string>;
}) {
  const [name, setName] = useState(view.name);
  const ref = useRef<HTMLInputElement>(null);
  const { busy, run } = useSubmit(onSubmit);
  useEffect(() => ref.current?.focus(), []);
  const save = () => {
    const n = name.trim();
    if (!n) {
      ref.current?.focus();
      return;
    }
    void run(n);
  };
  return (
    <MvaDialog
      title="Rename saved view"
      onClose={onClose}
      footer={
        <>
          <button type="button" onClick={onClose}>
            Cancel
          </button>
          <button type="button" className="mva-primary" disabled={busy} onClick={save}>
            Save
          </button>
        </>
      }
    >
      <label className="mva-dialog-label">
        Name *
        <input
          ref={ref}
          id="mvaRenameInput"
          value={name}
          maxLength={VIEW_NAME_MAX}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
    </MvaDialog>
  );
}

/** "Delete this saved view?" (view-all.js:91): Delete, Cancel. */
export function DeleteDialog({
  view,
  onClose,
  onSubmit,
}: {
  view: View;
  onClose: () => void;
  onSubmit: Submit<void>;
}) {
  const { busy, run } = useSubmit(onSubmit);
  return (
    <MvaDialog
      title="Delete this saved view?"
      variant="delete"
      onClose={onClose}
      footer={
        <>
          <button
            type="button"
            className="mva-danger mva-delete-confirm"
            disabled={busy}
            onClick={() => void run()}
          >
            Delete
          </button>
          <button type="button" onClick={onClose}>
            Cancel
          </button>
        </>
      }
    >
      <DeleteCopy name={view.name} />
    </MvaDialog>
  );
}

/** The delete dialog's text, the design's own, the note included (view-all.js:91). */
export function DeleteCopy({ name }: { name: string }) {
  return (
    <div className="mva-delete-copy">
      <p>You’re about to delete “{name}”.</p>
      <div className="mva-info-callout">
        You do not own this saved view, but you can delete it because you are an administrator.
      </div>
    </div>
  );
}

export interface PeopleSource {
  people: Owner[];
  teams: Array<{ id: string; name: string }>;
}

type Access = 'private' | 'everyone';

/** "Anyone else with the link": the button and its menu, placed on the page (view-all.js:267-296). */
function AccessSelect({ value, onChange }: { value: Access; onChange: (v: Access) => void }) {
  const [pos, setPos] = useState<{ left: number; top: number; width: number } | null>(null);
  const btn = useRef<HTMLButtonElement>(null);
  const menu = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!pos) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (!menu.current?.contains(t) && !btn.current?.contains(t)) setPos(null);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [pos]);
  const open = () => {
    if (pos) {
      setPos(null);
      return;
    }
    const r = btn.current!.getBoundingClientRect();
    const w = Math.min(420, window.innerWidth - 24);
    const h = 150;
    setPos({
      width: w,
      left: Math.max(12, Math.min(r.right - w, window.innerWidth - w - 12)),
      top: r.bottom + h + 8 <= window.innerHeight - 12 ? r.bottom + 6 : Math.max(12, r.top - h - 6),
    });
  };
  const options: Array<[Access, string, string]> = [
    ['private', 'Private', 'Only you have access to this view.'],
    ['everyone', 'Everyone', 'Everyone on your account can access this view.'],
  ];
  return (
    <>
      <button
        ref={btn}
        type="button"
        className="mva-select-button"
        id="mvaAccessSelect"
        aria-expanded={Boolean(pos)}
        onClick={open}
      >
        {value === 'private' ? 'Private' : 'Everyone'} <Caret />
      </button>
      {pos
        ? createPortal(
            <div
              ref={menu}
              className="mva-access-options"
              id="mvaAccessOptions"
              style={{
                position: 'fixed',
                zIndex: 10080,
                width: pos.width,
                maxHeight: 'min(260px, calc(100dvh - 24px))',
                overflowY: 'auto',
                right: 'auto',
                left: pos.left,
                top: pos.top,
              }}
            >
              {options.map(([v, label, sub]) => (
                <button
                  key={v}
                  type="button"
                  onClick={() => {
                    onChange(v);
                    setPos(null);
                  }}
                >
                  <strong>{label}</strong>
                  <small>{sub}</small>
                </button>
              ))}
            </div>,
            document.body,
          )
        : null}
    </>
  );
}

const memberKey = (m: ViewShareMember) => `${m.type}:${m.id}`;

/** Search, people and teams, the owner row and the access row (view-all.js:94, :98, :215-229). */
function AccessForm({
  owner,
  source,
  members,
  setMembers,
  access,
  setAccess,
  labelled,
}: {
  owner: { id: string | null; name: string; email: string } | null;
  source: PeopleSource;
  members: ViewShareMember[];
  setMembers: (m: ViewShareMember[]) => void;
  access: Access;
  setAccess: (a: Access) => void;
  /** Manage sharing's search has a label; Clone's sits under "Access". */
  labelled: boolean;
}) {
  const [q, setQ] = useState('');
  const term = q.trim().toLowerCase();
  const picked = new Set(members.map(memberKey));
  const ownerId = owner?.id ?? null;
  const hits: Array<{ m: ViewShareMember; name: string; sub: string }> = [
    ...source.people
      .filter((p) => p.active && p.userId !== ownerId)
      .map((p) => ({ m: { type: 'user' as const, id: p.userId }, name: p.name, sub: p.email })),
    ...source.teams.map((t) => ({
      m: { type: 'team' as const, id: t.id },
      name: t.name,
      sub: 'Team',
    })),
  ].filter((x) => !picked.has(memberKey(x.m)) && `${x.name} ${x.sub}`.toLowerCase().includes(term));
  const nameOf = (m: ViewShareMember) =>
    m.type === 'user'
      ? (source.people.find((p) => p.userId === m.id) ?? { name: 'Unknown user', email: '' })
      : { name: source.teams.find((t) => t.id === m.id)?.name ?? 'Team', email: 'Team' };
  const input = (
    <div className="mva-search-with-icon">
      <input
        type="search"
        placeholder="Search users and teams"
        value={q}
        onChange={(e) => setQ(e.target.value)}
      />
      <SmallSearchIcon />
    </div>
  );
  return (
    <>
      {labelled ? (
        <label className="mva-dialog-label">
          Search users and teams
          {input}
        </label>
      ) : (
        <label className="mva-dialog-label">{input}</label>
      )}
      <div className="mva-user-results" hidden={!term}>
        {hits.length ? (
          hits.map((x) => (
            <button
              key={memberKey(x.m)}
              type="button"
              className="mva-user-result"
              onClick={() => {
                setMembers([...members, x.m]);
                setQ('');
              }}
            >
              <span className="mva-user-result-check" aria-hidden="true" />
              <Avatar text={initials(x.name)} />
              <span className="mva-user-meta">
                <strong>{x.name}</strong>
                <small>{x.sub}</small>
              </span>
            </button>
          ))
        ) : (
          <div className="mva-no-users">No users found</div>
        )}
      </div>
      {labelled ? <h3>Shared access</h3> : null}
      <div className="mva-shared-users">
        {owner ? (
          <div className="mva-shared-user">
            <Avatar text={initials(owner.name)} />
            <span className="mva-user-meta">
              <strong>{owner.name}</strong>
              <small>{owner.email}</small>
            </span>
            <b className="mva-role">Owner</b>
          </div>
        ) : null}
        {members.map((m) => {
          const who = nameOf(m);
          return (
            <div key={memberKey(m)} className="mva-shared-user">
              <Avatar text={initials(who.name)} />
              <span className="mva-user-meta">
                <strong>{who.name}</strong>
                <small>{who.email}</small>
              </span>
              <b className="mva-role mva-role-visitor">Visitors</b>
              <button
                type="button"
                className="mva-remove-user"
                aria-label={`Remove ${who.name}`}
                onClick={() => setMembers(members.filter((x) => memberKey(x) !== memberKey(m)))}
              >
                ×
              </button>
            </div>
          );
        })}
      </div>
      <div className="mva-anyone-row">
        <strong>Anyone else with the link:</strong>
        <AccessSelect value={access} onChange={setAccess} />
      </div>
    </>
  );
}

/** "Manage sharing" (view-all.js:94): Cancel, Confirm. */
export function SharingDialog({
  view,
  owner,
  source,
  initialMembers,
  onClose,
  onSubmit,
}: {
  view: View;
  owner: { id: string | null; name: string; email: string } | null;
  source: PeopleSource;
  initialMembers: ViewShareMember[];
  onClose: () => void;
  onSubmit: Submit<{ access: Access; members: ViewShareMember[] }>;
}) {
  const [access, setAccess] = useState<Access>(
    view.isShared || view.isSystem ? 'everyone' : 'private',
  );
  const [members, setMembers] = useState(initialMembers);
  const { busy, run } = useSubmit(onSubmit);
  return (
    <MvaDialog
      title="Manage sharing"
      onClose={onClose}
      footer={
        <>
          <button type="button" onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            className="mva-primary"
            disabled={busy}
            onClick={() => void run({ access, members })}
          >
            Confirm
          </button>
        </>
      }
    >
      <div className="mva-access-form">
        <AccessForm
          owner={owner}
          source={source}
          members={members}
          setMembers={setMembers}
          access={access}
          setAccess={setAccess}
          labelled
        />
      </div>
    </MvaDialog>
  );
}

/** "Clone a saved view" (view-all.js:98): name, views created, Access; Confirm, Cancel. */
export function CloneDialog({
  initialName,
  limitText,
  me,
  source,
  onClose,
  onSubmit,
}: {
  initialName: string;
  limitText: string;
  me: { id: string; name: string; email: string };
  source: PeopleSource;
  onClose: () => void;
  onSubmit: Submit<{ name: string; access: Access; members: ViewShareMember[] }>;
}) {
  const [name, setName] = useState(initialName);
  // The design starts the copy on Everyone (view-all.js:98).
  const [access, setAccess] = useState<Access>('everyone');
  const [members, setMembers] = useState<ViewShareMember[]>([]);
  const ref = useRef<HTMLInputElement>(null);
  const { busy, run } = useSubmit(onSubmit);
  const save = () => {
    const n = name.trim();
    if (!n) {
      ref.current?.focus();
      return;
    }
    void run({ name: n, access, members });
  };
  return (
    <MvaDialog
      title="Clone a saved view"
      variant="clone"
      onClose={onClose}
      footer={
        <>
          <button type="button" className="mva-primary" disabled={busy} onClick={save}>
            Confirm
          </button>
          <button type="button" onClick={onClose}>
            Cancel
          </button>
        </>
      }
    >
      <div className="mva-clone-form">
        <label className="mva-dialog-label">
          Name *
          <div className="mva-name-valid">
            <input
              ref={ref}
              id="mvaCloneInput"
              value={name}
              maxLength={VIEW_NAME_MAX}
              onChange={(e) => setName(e.target.value)}
            />
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <path d="m4 12 5 5L20 6" />
            </svg>
          </div>
        </label>
        <p className="mva-views-limit">{limitText}</p>
        <hr />
        <h3>Access</h3>
        <AccessForm
          owner={me}
          source={source}
          members={members}
          setMembers={setMembers}
          access={access}
          setAccess={setAccess}
          labelled={false}
        />
      </div>
    </MvaDialog>
  );
}

const LANGUAGES = [
  'Deutsch',
  'English',
  'Español',
  'Français',
  'Italiano',
  'Nederlands',
  '日本語',
  'Português',
];

export interface ExportChoice {
  name: string;
  format: ManageExportFormat;
  scope: ExportScope;
  association?: ExportAssociationChoice;
  allCompanyDomains: boolean;
}

/** "Export view" (view-all.js:101, :230-308): Export, Cancel. */
export function ExportDialog({
  view,
  rows,
  onClose,
  onSubmit,
}: {
  view: View;
  /** The view's rows, for "N rows in 1 file"; null while counting or when it can't be counted. */
  rows: number | null;
  onClose: () => void;
  onSubmit: Submit<ExportChoice>;
}) {
  const [name, setName] = useState(view.name);
  const [format, setFormat] = useState<ManageExportFormat>('csv');
  const [formatOpen, setFormatOpen] = useState(false);
  const [langOpen, setLangOpen] = useState(false);
  const langSearch = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (!formatOpen && !langOpen) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Element;
      if (!t.closest('#mvaExportFormat') && !t.closest('[data-menu="format"]'))
        setFormatOpen(false);
      if (!t.closest('#mvaExportLanguage') && !t.closest('[data-menu="language"]'))
        setLangOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [formatOpen, langOpen]);
  useEffect(() => {
    if (langOpen) langSearch.current?.focus();
  }, [langOpen]);
  const [langQ, setLangQ] = useState('');
  const [customize, setCustomize] = useState(false);
  // The design's radio starts on "All properties on records" (view-all.js:101).
  const [scope, setScope] = useState<ExportScope>('all');
  const [association, setAssociation] = useState<ExportAssociationChoice | undefined>();
  const [domains, setDomains] = useState(false);
  const { busy, run } = useSubmit(onSubmit);
  const formats: Array<[ManageExportFormat, string]> = [
    ['csv', 'CSV'],
    ['xlsx', 'Excel (XLSX)'],
  ];
  const property = (value: ExportScope, label: ReactNode) => (
    <label className="mva-export-radio">
      <input
        type="radio"
        name="mvaExportProperties"
        value={value}
        checked={scope === value}
        onChange={() => setScope(value)}
      />{' '}
      {label}
    </label>
  );
  const assoc = (value: ExportAssociationChoice, label: string) => (
    <label className="mva-export-radio">
      <input
        type="radio"
        name="mvaExportAssociations"
        value={value}
        checked={association === value}
        disabled={scope !== 'view'}
        onChange={() => setAssociation(value)}
      />{' '}
      {label}
    </label>
  );
  return (
    <MvaDialog
      title="Export view"
      variant="export"
      onClose={onClose}
      footer={
        <>
          <button
            type="button"
            className="mva-primary"
            disabled={busy}
            onClick={() =>
              void run({
                name: name.trim() || view.name,
                format,
                scope,
                association: scope === 'view' ? association : undefined,
                allCompanyDomains: domains,
              })
            }
          >
            Export
          </button>
          <button type="button" onClick={onClose}>
            Cancel
          </button>
        </>
      }
    >
      <div className="mva-export-form">
        <div className="mva-export-top">
          <strong>Send to</strong>
        </div>
        <p className="mva-dialog-muted">
          The exported file downloads to this computer. View this and past exports in{' '}
          {/* The design's link; it opens the CRM's export history (Imports and exports). */}
          <a href="/settings/imports" target="_blank" rel="noopener" data-export-help>
            Export Audit ↗
          </a>
          .
        </p>
        <hr />
        <h3>Prepare your export file</h3>
        <p>
          Exporting: <strong>“{view.name}”</strong>
          {rows !== null ? (
            <>
              {'  '}
              {rows.toLocaleString()} rows in 1 file
            </>
          ) : null}
        </p>
        <label className="mva-dialog-label">
          Export name
          <input id="mvaExportName" value={name} onChange={(e) => setName(e.target.value)} />
        </label>
        <div className="mva-export-grid">
          <label className="mva-dialog-label">
            File format
            <button
              type="button"
              className="mva-select-button"
              id="mvaExportFormat"
              data-value={format === 'csv' ? 'CSV' : 'XLSX'}
              onClick={() => setFormatOpen((o) => !o)}
            >
              {formats.find((f) => f[0] === format)![1]} <Caret />
            </button>
            <div className="mva-export-options" data-menu="format" hidden={!formatOpen}>
              {formats.map(([v, label]) => (
                <button
                  key={v}
                  type="button"
                  onClick={() => {
                    setFormat(v);
                    setFormatOpen(false);
                  }}
                >
                  {label}
                </button>
              ))}
            </div>
          </label>
          <label className="mva-dialog-label">
            Language of column headers{' '}
            <button
              type="button"
              className="mva-select-button"
              id="mvaExportLanguage"
              data-value="English"
              onClick={() => setLangOpen((o) => !o)}
            >
              English <Caret />
            </button>
            <div className="mva-export-options" data-menu="language" hidden={!langOpen}>
              <input
                ref={langSearch}
                type="search"
                placeholder="Search"
                value={langQ}
                onChange={(e) => setLangQ(e.target.value)}
              />
              <div className="mva-language-list">
                {LANGUAGES.filter((l) => l.toLowerCase().includes(langQ.toLowerCase())).map((l) => (
                  <button
                    key={l}
                    type="button"
                    // Decided 6 Nov: no header translations exist, so only English can be chosen.
                    disabled={l !== 'English'}
                    onClick={() => setLangOpen(false)}
                  >
                    {l}
                  </button>
                ))}
              </div>
            </div>
          </label>
        </div>
        <h3>Data included in export</h3>
        <ul id="mvaExportIncludedData">
          {includedData(scope, association).map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>
        <hr />
        <button
          type="button"
          className="mva-export-customize-toggle"
          id="mvaExportCustomize"
          aria-expanded={customize}
          onClick={() => setCustomize((c) => !c)}
        >
          <span>{customize ? '⌄' : '›'}</span> Customize
        </button>
        <div id="mvaExportCustomizeBody" hidden={!customize}>
          <label className="mva-export-check">
            <input
              type="checkbox"
              checked={domains}
              onChange={(e) => setDomains(e.target.checked)}
            />{' '}
            Include all company domains
          </label>
          <h4>Properties included in export</h4>
          {property('view', 'Properties and associations in your view')}
          {property('all', 'All properties on records')}
          {property(
            'all-associations',
            <>
              All properties and all associations on records{' '}
              <small>May result in slower exports</small>
            </>,
          )}
          <h4>Associations included in export</h4>
          {assoc('name', 'Include associated record name')}
          {assoc('1000', 'Include up to 1,000 associated records in each association column')}
          {assoc('all', 'Include all associated records in each association column')}
        </div>
      </div>
    </MvaDialog>
  );
}

/** "Clone standard view" (view-all.js:111): Cancel, Clone. */
export function StandardCloneDialog({
  name: source,
  initialName,
  onClose,
  onSubmit,
}: {
  name: string;
  initialName: string;
  onClose: () => void;
  onSubmit: Submit<string>;
}) {
  const [name, setName] = useState(initialName);
  const ref = useRef<HTMLInputElement>(null);
  const { busy, run } = useSubmit(onSubmit);
  const save = () => {
    const n = name.trim();
    if (!n) {
      ref.current?.focus();
      return;
    }
    void run(n);
  };
  return (
    <MvaDialog
      title="Clone standard view"
      onClose={onClose}
      footer={
        <>
          <button type="button" onClick={onClose}>
            Cancel
          </button>
          <button type="button" className="mva-primary" disabled={busy} onClick={save}>
            Clone
          </button>
        </>
      }
    >
      <p>
        Create a copy of <strong>{source}</strong>?
      </p>
      <label className="mva-dialog-label">
        New view name
        <input
          ref={ref}
          id="mvaStandardCloneName"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
    </MvaDialog>
  );
}

/** A standard view's name opens this (view-all.js:111): Close only. */
export function StandardInfoDialog({
  objectLabel,
  view,
  onClose,
}: {
  objectLabel: string;
  view: View;
  onClose: () => void;
}) {
  return (
    <MvaDialog
      title={view.name}
      onClose={onClose}
      footer={
        <button type="button" onClick={onClose}>
          Close
        </button>
      }
    >
      <p>
        <strong>Object:</strong> {objectLabel}
      </p>
      <p>
        <strong>View:</strong> {view.name}
      </p>
      <p>This is a standard view. Open it from the {objectLabel} object to see its records.</p>
    </MvaDialog>
  );
}
