'use client';

import { useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { listAuditLog, type AuditLogEntry } from '@/features/audit-log/api.client';
import { XFMT, downloadTable, type ExportFormat } from '@/features/goals/export';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { errorText } from '@/lib/api/errors';
import {
  definitionFileBase,
  definitionTable,
  exportingText,
  historyTitle,
  propertyApiRows,
  type DefinitionRow,
} from '../propertyExport';
import { historyTimeText } from '../zoneText';
import { DmIcon } from './icons';
import { Drawer, DrawerHead, Modal, SelectMenu } from './primitives';

/**
 * B10 (user's call): the design's "Export property definition" (data-model.js:1860-1917) with
 * true CSV, XLS and XLSX files. The file downloads at once, so the design's Notifications Center
 * lines are left out.
 */
export function ExportDefinitionModal({
  objectKey,
  objectName,
  rows,
  onClose,
  onDone,
}: {
  objectKey: string;
  objectName: string;
  rows: DefinitionRow[];
  onClose: () => void;
  onDone?: () => void;
}) {
  const toast = useToast();
  const [format, setFormat] = useState<ExportFormat>('CSV');
  return (
    <Modal
      title="Export property definition"
      okLabel="Export"
      onClose={onClose}
      onOk={() => {
        downloadTable(
          definitionTable(objectName, rows),
          format,
          definitionFileBase(objectKey, rows),
        );
        toast(
          rows.length === 1
            ? `Exported the definition of "${rows[0]!.label}" as ${format}.`
            : `Exported the definition of ${rows.length} properties as ${format}.`,
          'success',
        );
        onDone?.();
      }}
    >
      <p className="dm-pe__export">
        Exporting: <b>{exportingText(rows.length)}</b> in 1 file
      </p>
      <div className="dm-field">
        <span className="dm-field__label">File format</span>
        <SelectMenu
          value={format}
          options={XFMT.map((f) => ({ value: f, label: f }))}
          onChange={setFormat}
          ariaLabel="File format"
        />
      </div>
    </Modal>
  );
}

/** B12: the design's API details layout (data-model.js:4374-4416), with the property's values. */
export function PropertyApiModal({
  property,
  onClose,
}: {
  property: { id: string; name: string; type: string; crmDefined: boolean };
  onClose: () => void;
}) {
  return <ApiRowsModal rows={propertyApiRows(property)} onClose={onClose} />;
}

/**
 * The design's API details dialog (data-model.js:4351-4416): each value with Copy ("Copied!"),
 * "Copy all to clipboard" and Cancel. DMG11: shared by properties and association labels.
 */
export function ApiRowsModal({
  rows,
  onClose,
}: {
  rows: Array<{ label: string; value: string }>;
  onClose: () => void;
}) {
  const toast = useToast();
  const [copied, setCopied] = useState<string | null>(null);
  const copy = (text: string, done: string) => {
    if (!navigator.clipboard) {
      toast(text, 'info');
      return;
    }
    navigator.clipboard.writeText(text).then(
      () => toast(done, 'success'),
      () => toast('Copy failed', 'danger'),
    );
  };
  return (
    <Modal
      title="API details"
      okLabel="Copy all to clipboard"
      onClose={onClose}
      onOk={() => {
        copy(
          rows.map((r) => `${r.label}: ${r.value}`).join('\n'),
          'All API details copied to clipboard',
        );
        return false;
      }}
    >
      <p className="dm-muted">Read-only API identifiers for this item.</p>
      <div className="dm-api-list">
        {rows.map((r) => (
          <div key={r.label} className="dm-api-item">
            <span className="dm-api-item__label">{r.label}</span>
            <div className="dm-api-item__field">
              <span className="dm-api-item__val">{r.value}</span>
              <button
                type="button"
                className="dm-api-copy-btn"
                onClick={() => {
                  copy(r.value, `Copied "${r.value}" to clipboard`);
                  setCopied(r.label);
                  setTimeout(() => setCopied((c) => (c === r.label ? null : c)), 1800);
                }}
              >
                <DmIcon name={copied === r.label ? 'check' : 'copy'} size={13} />
                {copied === r.label ? 'Copied!' : 'Copy'}
              </button>
            </div>
          </div>
        ))}
      </div>
    </Modal>
  );
}

/**
 * B12: "Property history: <label>" (data-model.js:4324-4348), from the audit log's entries for
 * this property (Super Admins, as the audit log). The design's sample events are left out.
 */
export function PropertyHistoryDrawer({
  property,
  onClose,
}: {
  property: { id: string; name: string; label: string } | null;
  onClose: () => void;
}) {
  const { timeZone } = useUserPrefs();
  // Kept with the id they are for, so another property never shows them, not even for a frame.
  const [loaded, setLoaded] = useState<{
    id: string;
    entries: AuditLogEntry[] | null;
    error: string | null;
  } | null>(null);
  const id = property?.id;
  const entries = loaded && loaded.id === id ? loaded.entries : null;
  const error = loaded && loaded.id === id ? loaded.error : null;
  useEffect(() => {
    if (!id) return;
    let alive = true;
    listAuditLog({ entity: 'custom_property', entityId: id, limit: 100 }).then(
      (page) => alive && setLoaded({ id, entries: page.data, error: null }),
      (err: unknown) => alive && setLoaded({ id, entries: null, error: errorText(err) }),
    );
    return () => {
      alive = false;
    };
  }, [id]);
  return (
    <Drawer
      open={property !== null}
      onClose={onClose}
      label={property ? `Property history: ${property.label}` : 'Property history'}
    >
      <DrawerHead
        title={property ? `Property history: ${property.label}` : 'Property history'}
        onClose={onClose}
      />
      {property && (
        <div className="dm-drawer__body">
          <p className="dm-muted">{property.name}</p>
          {error ? (
            <p className="dm-error" role="alert">
              {error}
            </p>
          ) : entries === null ? (
            <p className="dm-muted">Loading…</p>
          ) : entries.length === 0 ? (
            <p className="dm-muted">No changes recorded for this property.</p>
          ) : (
            <div className="dm-history-timeline">
              {entries.map((e) => {
                const who = e.actorName ?? e.actorEmail ?? 'System';
                return (
                  <div key={e.id} className="dm-history-item">
                    <div className="dm-history-avatar">{who.charAt(0)}</div>
                    <div className="dm-history-text">
                      <div className="dm-history-title">{historyTitle(e.action, e.changes)}</div>
                      <div className="dm-history-meta">
                        {who} &bull; {historyTimeText(e.createdAt, timeZone)}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}
      <div className="dm-drawer__foot">
        <button type="button" className="dm-btn dm-btn--ghost" onClick={onClose}>
          Close
        </button>
      </div>
    </Drawer>
  );
}
