'use client';

import { useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  byText,
  downloadFile,
  fieldTypeLabel,
  groupLabel,
  liveProperties,
  toCsv,
  type DataModel,
} from '../model';
import { Modal, SearchBox, SelectMenu } from './primitives';

type Format = 'csv' | 'excel';

const FORMATS: Array<{ value: Format; label: string }> = [
  { value: 'csv', label: 'CSV' },
  { value: 'excel', label: 'CSV for Excel (UTF-8 with BOM)' },
];

/**
 * Manage > More > "Export properties", as HubSpot's dialog: the objects to export (all to start
 * with), the file format, and where the file goes. The file is made here and downloads at once;
 * there is no Notifications Center to post it to.
 */
export function ExportPropertiesModal({
  model,
  onClose,
}: {
  model: DataModel;
  onClose: () => void;
}) {
  const toast = useToast();
  const objects = model.objects
    .filter((o) => o.active && liveProperties(model, o.key).length > 0)
    .sort((a, b) => byText(a.name, b.name));
  const [chosen, setChosen] = useState<Set<string>>(() => new Set(objects.map((o) => o.key)));
  const [search, setSearch] = useState('');
  const [format, setFormat] = useState<Format>('csv');
  const shown = objects.filter(
    (o) => !search.trim() || o.name.toLowerCase().includes(search.trim().toLowerCase()),
  );
  const toggle = (key: string, on: boolean) =>
    setChosen((cur) => {
      const next = new Set(cur);
      if (on) next.add(key);
      else next.delete(key);
      return next;
    });

  const exportFile = () => {
    const out: Array<Array<string | number>> = [
      [
        'Object',
        'Property label',
        'Internal name',
        'Field type',
        'Group',
        'Required',
        'Unique',
        'Description',
      ],
    ];
    for (const o of objects.filter((x) => chosen.has(x.key))) {
      for (const p of liveProperties(model, o.key)) {
        out.push([
          o.name,
          p.label,
          p.name,
          fieldTypeLabel(p),
          groupLabel(model, o.key, p.groupName),
          p.required ? 'Yes' : 'No',
          p.unique ? 'Yes' : 'No',
          p.description ?? '',
        ]);
      }
    }
    // Excel reads a CSV as UTF-8 only when it starts with a byte order mark.
    const text = format === 'excel' ? `﻿${toCsv(out)}` : toCsv(out);
    downloadFile('properties.csv', text);
    toast(`Properties of ${chosen.size} object${chosen.size === 1 ? '' : 's'} exported`, 'success');
  };

  return (
    <Modal
      title="Export properties"
      okLabel="Export"
      okDisabled={!chosen.size}
      onClose={onClose}
      onOk={exportFile}
    >
      <div className="dm-field">
        <span className="dm-field__label">Object types</span>
        <div className="dm-export__tools">
          <SearchBox value={search} onChange={setSearch} placeholder="Search objects" />
          <button
            type="button"
            className="dm-link"
            onClick={() => setChosen(new Set(objects.map((o) => o.key)))}
          >
            Select all
          </button>
          <button type="button" className="dm-link" onClick={() => setChosen(new Set())}>
            Deselect all
          </button>
        </div>
        <div className="dm-export__list">
          {shown.map((o) => (
            <label key={o.key} className="dm-check">
              <input
                type="checkbox"
                checked={chosen.has(o.key)}
                onChange={(e) => toggle(o.key, e.target.checked)}
              />
              <span>{o.name}</span>
            </label>
          ))}
          {!shown.length && <p className="dm-muted">No objects match your search.</p>}
        </div>
      </div>
      <div className="dm-field">
        <span className="dm-field__label">File format</span>
        <SelectMenu value={format} options={FORMATS} onChange={setFormat} ariaLabel="File format" />
      </div>
      <p className="dm-field__hint">
        The file downloads as soon as it is ready, with one row per property of the objects you
        picked.
      </p>
    </Modal>
  );
}
