'use client';

import { useState } from 'react';
import type { DmObject } from '@/features/data-model/model';
import { EXPORT_FORMATS, type ExportFormat } from '../propertyExport';
import { Ico, PpModal } from './properties-ui';

/**
 * "Export properties", as the design's dialog (settings-properties.php) and HubSpot's: the
 * objects to export (the open one to start with), the file format, and where the file goes.
 */
export function ExportPropertiesDialog({
  objects,
  initial,
  onExport,
  onClose,
}: {
  objects: DmObject[];
  /** Keys checked when it opens. */
  initial: string[];
  /** False keeps the dialog open; `progress` gets the number of objects loaded so far. */
  onExport: (
    keys: string[],
    format: ExportFormat,
    progress: (done: number) => void,
  ) => Promise<boolean | void>;
  onClose: () => void;
}) {
  const [sel, setSel] = useState<Set<string>>(() => new Set(initial));
  const [q, setQ] = useState('');
  const [format, setFormat] = useState<ExportFormat>('csv');
  /** Objects loaded so far while exporting; null when not exporting. */
  const [loading, setLoading] = useState<{ done: number; total: number } | null>(null);
  const s = q.trim().toLowerCase();
  const shown = objects.filter((o) => !s || o.name.toLowerCase().includes(s));
  const toggle = (key: string, on: boolean) =>
    setSel((cur) => {
      const next = new Set(cur);
      if (on) next.add(key);
      else next.delete(key);
      return next;
    });

  return (
    <PpModal
      title="Export properties"
      okLabel="Export"
      okDisabled={!sel.size}
      onClose={onClose}
      // In the picker's order, whatever order they were checked in.
      onOk={async () => {
        const keys = objects.filter((o) => sel.has(o.key)).map((o) => o.key);
        setLoading({ done: 0, total: keys.length });
        try {
          return await onExport(keys, format, (done) => setLoading({ done, total: keys.length }));
        } finally {
          setLoading(null);
        }
      }}
    >
      <p className="pp-p">Choose the objects to include in your properties export.</p>
      <div className="pp-exphead">
        <span>
          <b>{sel.size}</b> selected
        </span>
        <span>
          <button
            type="button"
            className="pp-textlink"
            onClick={() => setSel(new Set(objects.map((o) => o.key)))}
          >
            Select all
          </button>
          <button type="button" className="pp-textlink" onClick={() => setSel(new Set())}>
            Deselect all
          </button>
        </span>
      </div>
      <label className="pp-search pp-search--full">
        <input
          type="search"
          placeholder="Search object types"
          aria-label="Search object types"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <Ico name="search" />
      </label>
      <div className="pp-explist">
        {shown.map((o) => (
          <label key={o.key} className="pp-check">
            <input
              type="checkbox"
              checked={sel.has(o.key)}
              onChange={(e) => toggle(o.key, e.target.checked)}
            />
            <span>{o.name}</span>
          </label>
        ))}
        {!shown.length && <p className="pp-help">No object types match</p>}
      </div>
      <label className="pp-field">
        <span className="pp-label">File format</span>
        <select
          className="pp-input"
          value={format}
          onChange={(e) => setFormat(e.target.value as ExportFormat)}
        >
          {EXPORT_FORMATS.map((f) => (
            <option key={f.value} value={f.value}>
              {f.label}
            </option>
          ))}
        </select>
      </label>
      <p className="pp-p" role="status">
        {loading
          ? `Loading usages and fill rates: ${loading.done} of ${loading.total} ${
              loading.total === 1 ? 'object' : 'objects'
            }`
          : sel.size > 1
            ? 'The exported files will download to this computer in a zip file, one per object.'
            : 'The exported file will download to this computer.'}
      </p>
    </PpModal>
  );
}
