'use client';

/**
 * Parts of "Repeat a past import" (DI-2c), with the design's markup and classes
 * (`repeat-past-import.php`), so `repeat-past-import.css` applies as written.
 */
import { useState } from 'react';
import { cn } from '@/lib/utils/cn';
import {
  NUMBER_FORMATS,
  numberFormatHint,
  REPEAT_MODES,
  uploadedBytesText,
  uploadedFileText,
  type RepeatMode,
  type TemplateRow,
} from '../repeatImport';

export function ChevronDown() {
  return (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="m4 6 4 4 4-4" />
    </svg>
  );
}

export function FileIcon() {
  return (
    <svg className="upload-file-icon" viewBox="0 0 40 40" aria-hidden="true">
      <path d="M9 4h14l10 10v22H9z" />
      <path d="M23 4v11h10" />
    </svg>
  );
}

export function ExternalIcon() {
  return (
    <svg viewBox="0 0 16 16" aria-hidden="true">
      <path d="M9 2h5v5M14 2 7 9" />
      <path d="M12 9v3.5A1.5 1.5 0 0 1 10.5 14h-7A1.5 1.5 0 0 1 2 12.5v-7A1.5 1.5 0 0 1 3.5 4H7" />
    </svg>
  );
}

/* ------------------------------------------------------------- step 1 */

export type LoadState = 'loading' | 'failed' | 'ready';

/**
 * The past imports (`.php:69-85`). While the history loads, if it fails, or if there is none, one
 * row says so (the design has static rows only).
 */
export function TemplateTable({
  rows,
  state,
  error,
  busyId,
  onUse,
}: {
  rows: TemplateRow[];
  state: LoadState;
  error: string | null;
  /** The template being read (`GET /imports/:id`): its button waits. */
  busyId: string | null;
  onUse: (row: TemplateRow) => void;
}) {
  const note =
    state === 'loading'
      ? 'Loading past imports…'
      : state === 'failed'
        ? `Past imports could not be loaded. ${error ?? ''}`.trim()
        : rows.length === 0
          ? 'No past imports yet.'
          : null;
  return (
    <div className="repeat-table-wrap">
      <table className="repeat-import-table">
        <thead>
          <tr>
            <th>Name</th>
            <th>User</th>
            <th>Created</th>
          </tr>
        </thead>
        <tbody>
          {note ? (
            <tr>
              <td colSpan={3}>{note}</td>
            </tr>
          ) : (
            rows.map((row) => (
              <tr key={row.id}>
                <td>
                  <div className="repeat-name-cell">
                    <strong>{row.name}</strong>
                    <small>{row.objectText}</small>
                    <button
                      type="button"
                      className="repeat-use-template"
                      data-name={row.name}
                      disabled={busyId === row.id}
                      onClick={() => onUse(row)}
                    >
                      Use as template
                    </button>
                  </div>
                </td>
                <td>
                  {row.user ?? '--'}
                  {row.user && row.email ? <small>{row.email}</small> : null}
                </td>
                <td>
                  {row.date}
                  <small>{row.time}</small>
                </td>
              </tr>
            ))
          )}
        </tbody>
      </table>
    </div>
  );
}

/* ------------------------------------------------------------- step 2 */

/** "Expected columns mismatch" (`.php:90-96`). */
export function MismatchAlert({ shown, onClose }: { shown: boolean; onClose: () => void }) {
  return (
    <div
      className="repeat-mismatch-alert"
      id="repeat-mismatch-alert"
      role="alert"
      aria-live="assertive"
      hidden={!shown}
    >
      <div className="repeat-mismatch-alert__copy">
        <strong>Expected columns mismatch</strong>
        <p>
          The uploaded file doesn’t have the columns expected by the import template. Check the
          import template requirements and edit your file as needed.
        </p>
      </div>
      <button
        type="button"
        id="repeat-mismatch-close"
        aria-label="Close error message"
        onClick={onClose}
      >
        ×
      </button>
    </div>
  );
}

/**
 * "Import template requirements" (`.php:112-116`): the template's columns; once a file is
 * checked, each marked matched (✓) or missing (⚠), with the missing count (`.js:585-617`).
 */
export function RequirementsCard({
  required,
  missing,
  checked,
  expanded,
  onToggle,
}: {
  required: readonly string[];
  missing: readonly string[];
  checked: boolean;
  expanded: boolean;
  onToggle: () => void;
}) {
  return (
    <section className="repeat-requirements-card" aria-labelledby="repeat-requirements-title">
      <h2 id="repeat-requirements-title">Import template requirements</h2>
      <button
        type="button"
        className="repeat-requirements-toggle"
        id="repeat-requirements-toggle"
        aria-expanded={expanded}
        onClick={onToggle}
      >
        <svg viewBox="0 0 20 20" aria-hidden="true">
          <path d="m5 7 5 5 5-5" />
        </svg>
        <strong>
          <span id="repeat-column-count">{required.length}</span> columns expected{' '}
          <span
            id="repeat-missing-count"
            className="repeat-missing-count"
            hidden={!checked || missing.length === 0}
          >
            {missing.length} missing
          </span>
        </strong>
      </button>
      <div className="repeat-requirements-body" id="repeat-requirements-body" hidden={!expanded}>
        <p>The uploaded file must contain the following columns.</p>
        <ol id="repeat-required-columns">
          {required.map((column) =>
            !checked ? (
              <li key={column}>{column}</li>
            ) : missing.includes(column) ? (
              <li key={column} className="is-missing">
                <span className="repeat-column-warning" aria-hidden="true">
                  ⚠
                </span>
                {column}
              </li>
            ) : (
              <li key={column} className="is-matched">
                <span className="repeat-column-match" aria-hidden="true">
                  ✓
                </span>
                {column}
              </li>
            ),
          )}
        </ol>
      </div>
    </section>
  );
}

/** "Choose how to import Contacts" (`.js:239-306`). */
export function ModeField({
  mode,
  open,
  onOpen,
  onPick,
}: {
  mode: RepeatMode;
  open: boolean;
  onOpen: (open: boolean) => void;
  onPick: (mode: RepeatMode) => void;
}) {
  const label = REPEAT_MODES.find((m) => m.value === mode)?.label ?? REPEAT_MODES[0]!.label;
  return (
    <div className="upload-mode-field">
      <label htmlFor="import-mode-contacts">Choose how to import Contacts</label>
      <div className="upload-mode-picker">
        <button
          type="button"
          className="upload-mode-trigger"
          id="import-mode-contacts"
          data-object="contacts"
          data-value={mode}
          aria-haspopup="listbox"
          aria-expanded={open}
          onClick={() => onOpen(!open)}
        >
          <span className="upload-mode-value">{label}</span>
          <ChevronDown />
        </button>
        <div className="upload-mode-menu" role="listbox" hidden={!open}>
          {REPEAT_MODES.map((m) => (
            <button
              key={m.value}
              type="button"
              className="upload-mode-option"
              role="option"
              aria-selected={m.value === mode}
              data-value={m.value}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                onPick(m.value);
              }}
            >
              {m.label}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

/** The dropzone once a file is in (`.js:547`). */
export function FileSummary({
  name,
  size,
  onRemove,
}: {
  name: string;
  size: number;
  onRemove: () => void;
}) {
  return (
    <div className="upload-file-summary">
      <FileIcon />
      <strong>{uploadedFileText(name)}</strong>
      <span>{uploadedBytesText(size)}</span>
      <button
        type="button"
        className="upload-remove-file"
        aria-label="Remove uploaded file"
        onClick={(e) => {
          e.stopPropagation();
          onRemove();
        }}
      >
        <svg viewBox="0 0 16 16" aria-hidden="true">
          <path d="m4 4 8 8M12 4l-8 8" />
        </svg>
      </button>
    </div>
  );
}

/* ------------------------------------------------------------- step 4 */

/**
 * "A few final details" (`.php:296-348`). Import name starts as the uploaded file's name and can be
 * changed (B2: the API keeps it). Enrichment isn't sent: the API has none.
 * The number format is sent at Finish (RIB2), and the segment box as `createList` (RIB3). The
 * usage counts come from the view (RIB3), "--" until they're known.
 */
export function DetailsPane({
  importName,
  onImportName,
  consent,
  onConsent,
  numberFormat,
  numberOpen,
  onNumberOpen,
  onNumberFormat,
  onSoon,
  createList,
  onCreateList,
  usage,
}: {
  importName: string;
  /** B2: the name can be changed; without a handler it stays as given. */
  onImportName?: (name: string) => void;
  consent: boolean;
  onConsent: (on: boolean) => void;
  numberFormat: string;
  numberOpen: boolean;
  onNumberOpen: (open: boolean) => void;
  onNumberFormat: (name: string) => void;
  onSoon: (label: string) => void;
  /** RIB3: "Create a contacts segment from this import", sent as `options.createList`. */
  createList: boolean;
  onCreateList: (on: boolean) => void;
  /** RIB3: "used in" counts (`usageCounts`); "--" until known. */
  usage?: { workflows: string; segments: string };
}) {
  const [query, setQuery] = useState('');
  const formats = NUMBER_FORMATS.filter((f) => f.name.toLowerCase().includes(query.toLowerCase()));
  return (
    <div className="details-inner">
      <h1 id="details-heading">A few final details</h1>

      <div className="details-field details-name-field">
        <label htmlFor="import-name">
          Import name <span aria-hidden="true">*</span>
        </label>
        <input
          id="import-name"
          name="import_name"
          type="text"
          required
          value={importName}
          onChange={(e) => onImportName?.(e.target.value)}
        />
      </div>

      {/* RIB3: the design's box (`.php:305-308`, ticked), sent as `options.createList`. QA #417 left
          it out until the API made an import's list (IDB4c). */}
      <label className="details-check-row">
        <input
          id="create-segment"
          type="checkbox"
          checked={createList}
          onChange={(e) => onCreateList(e.target.checked)}
        />
        <span>Create a contacts segment from this import</span>
      </label>

      <label className="details-check-row details-consent-row">
        <input
          id="import-consent"
          type="checkbox"
          checked={consent}
          onChange={(e) => onConsent(e.target.checked)}
        />
        <span>
          * I agree that all contacts in this import are expecting to hear from my organization. I
          have a prior relationship with these contacts and have emailed them at least once in the
          past year. I can confirm this list wasn’t purchased, rented, appended, or provided by a
          third party.
        </span>
      </label>

      <div className="details-field details-number-field">
        <label htmlFor="number-format-trigger">Number Format</label>
        <div className="details-number-picker">
          <button
            type="button"
            className="details-select-trigger"
            id="number-format-trigger"
            aria-expanded={numberOpen}
            onClick={() => onNumberOpen(!numberOpen)}
          >
            <span id="number-format-value">{numberFormat}</span>
            <ChevronDown />
          </button>
          <div className="details-number-menu" id="number-format-menu" hidden={!numberOpen}>
            <label className="details-number-search">
              <input
                id="number-format-search"
                type="search"
                placeholder="Search"
                autoComplete="off"
                aria-label="Search number formats"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
              />
              <svg viewBox="0 0 20 20" aria-hidden="true">
                <circle cx="8.5" cy="8.5" r="5.5" />
                <path d="m13 13 4 4" />
              </svg>
            </label>
            <div className="details-number-options" id="number-format-options" role="listbox">
              {formats.map((f) => (
                <button
                  key={f.name}
                  type="button"
                  className="details-number-option"
                  role="option"
                  aria-selected={f.name === numberFormat}
                  onClick={() => {
                    onNumberFormat(f.name);
                    onNumberOpen(false);
                  }}
                >
                  <span>{f.name}</span>
                </button>
              ))}
            </div>
          </div>
        </div>
        <p id="number-format-hint">{numberFormatHint(numberFormat)}</p>
      </div>

      <section className="details-enrich-card" aria-labelledby="enrich-heading">
        <h2 id="enrich-heading">Enrich these records</h2>
        <p>
          Data Enrichment can enrich and fill in missing data for records you import, ensuring their
          accuracy and completeness.{' '}
          <a
            href="#"
            className="upload-link"
            onClick={(e) => {
              e.preventDefault();
              onSoon('Learn more');
            }}
          >
            Learn more <ExternalIcon />
          </a>
        </p>
        {/* Enrichment isn't built: a tick would claim it, so it stays clear and says so. */}
        {(['Enrich contacts', 'Enrich companies'] as const).map((label, i) => (
          <label key={label} className="details-check-row">
            <input
              id={i === 0 ? 'enrich-contacts' : 'enrich-companies'}
              type="checkbox"
              checked={false}
              onChange={() => onSoon(label)}
            />
            <span>{label}</span>
          </label>
        ))}
      </section>

      <section className="details-usage-section" aria-labelledby="usage-heading">
        <h2 id="usage-heading">Properties in your import are used in:</h2>
        <div className="details-usage-card">
          <div className="details-usage-stat">
            <span>WORKFLOWS</span>
            <strong>{usage?.workflows ?? '--'}</strong>
          </div>
          <div className="details-usage-stat">
            <span>SEGMENTS</span>
            <strong>{usage?.segments ?? '--'}</strong>
          </div>
        </div>
      </section>
    </div>
  );
}

/** The stepper step's class (`.js:505-508`). */
export const stepClass = (index: number, active: number) =>
  cn('import-step', index === active && 'is-current', index < active && 'is-complete');
