'use client';

import { useCallback, useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import {
  getWorkflowVersion,
  listWorkflowVersions,
  restoreWorkflowVersion,
} from '@/features/workflows/api.client';
import type {
  WorkflowDetail,
  WorkflowStep,
  WorkflowVersionDetail,
  WorkflowVersionSummary,
} from '@/features/workflows/types';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  branchPathText,
  formatWhen,
  normalizeDefinition,
  stepTitle,
  triggerSummary,
} from './shared';

/** A read-only outline of steps (with branch paths), e.g. for an earlier version. */
export function StepOutline({
  steps,
  highlight,
}: {
  steps: WorkflowStep[];
  highlight?: { added: Set<string>; changed: Set<string> };
}) {
  if (steps.length === 0) return <p className="crm-fs-8 crm-text-muted crm-mb-0">No steps.</p>;
  return (
    <ol className="crm-ps-4 crm-mb-0">
      {steps.map((step) => (
        <li key={step.id} className="crm-mb-1">
          <span className="crm-fw-semibold">{stepTitle(step)}</span>{' '}
          <span className="crm-fs-8 crm-text-muted">({step.id})</span>
          {highlight?.added.has(step.id) ? (
            <span className="badge badge--success crm-ms-2">Added</span>
          ) : null}
          {highlight?.changed.has(step.id) ? (
            <span className="badge badge--warning crm-ms-2">Changed</span>
          ) : null}
          {step.type === 'branch' ? (
            <ul className="crm-ps-3 crm-mb-0">
              {step.paths.map((p) => (
                <li key={p.id}>
                  <span className="crm-fs-7">{branchPathText(step, p)}</span>
                  <StepOutline steps={p.steps ?? []} highlight={highlight} />
                </li>
              ))}
              {/* A random split always takes one of its paths: no "otherwise" unless one was set. */}
              {step.branchType !== 'random_split' || step.otherwise?.steps?.length ? (
                <li>
                  <span className="crm-fs-7">Otherwise</span>
                  <StepOutline steps={step.otherwise?.steps ?? []} highlight={highlight} />
                </li>
              ) : null}
            </ul>
          ) : null}
        </li>
      ))}
    </ol>
  );
}

/** Revision history: the draft and every published version; restore one into the draft. */
export function VersionsTab({
  workflow,
  canEdit,
  dirty,
  timeZone,
  memberName,
  onRestored,
}: {
  workflow: WorkflowDetail;
  canEdit: boolean;
  dirty: boolean;
  timeZone: string;
  memberName: (userId: string | null) => string;
  onRestored: (updated: WorkflowDetail) => void;
}) {
  const toast = useToast();
  const [versions, setVersions] = useState<WorkflowVersionSummary[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [openId, setOpenId] = useState<string | null>(null);
  const [detail, setDetail] = useState<WorkflowVersionDetail | null>(null);
  const [detailError, setDetailError] = useState<string | null>(null);
  const [restoring, setRestoring] = useState<WorkflowVersionSummary | null>(null);
  const [busy, setBusy] = useState(false);

  const load = useCallback(() => {
    listWorkflowVersions(workflow.id).then(
      (res) => {
        setVersions(res.data);
        setError(null);
      },
      (err) => {
        setVersions([]);
        setError(errorText(err));
      },
    );
  }, [workflow.id]);

  // Reload when the workflow changes (publish, restore, save of the draft).
  useEffect(load, [load, workflow.updatedAt]);

  useEffect(() => {
    setDetail(null);
    setDetailError(null);
    if (!openId) return;
    let cancelled = false;
    getWorkflowVersion(workflow.id, openId).then(
      (res) => !cancelled && setDetail(res),
      (err) => !cancelled && setDetailError(errorText(err)),
    );
    return () => {
      cancelled = true;
    };
  }, [workflow.id, openId]);

  const restore = async () => {
    if (!restoring || busy) return;
    setBusy(true);
    try {
      const updated = await restoreWorkflowVersion(workflow.id, restoring.id);
      toast(`Version ${restoring.versionNo} copied into the draft: publish it to use it`);
      setRestoring(null);
      onRestored(updated);
    } catch (err) {
      toast(
        isApiError(err) && err.isConflict
          ? `${errorText(err)}. Reload the page and try again.`
          : errorText(err),
        'danger',
        { durationMs: 9000 },
      );
    } finally {
      setBusy(false);
    }
  };

  const definition = detail ? normalizeDefinition(detail.definition) : null;
  const highlight = detail
    ? { added: new Set(detail.diff.stepsAdded), changed: new Set(detail.diff.stepsChanged) }
    : undefined;

  return (
    <div className="crm-d-flex crm-flex-column crm-gap-3">
      {error ? <Alert tone="danger">{error}</Alert> : null}
      <div className="crm-table-card">
        {versions === null ? (
          <p className="crm-p-5 crm-text-center crm-text-muted">Loading versions…</p>
        ) : versions.length === 0 ? (
          <div className="companies-empty">
            <h3>No versions yet</h3>
          </div>
        ) : (
          <div className="table-wrap crm-table-wrap sales-scroll">
            <table className="crm-table table">
              <thead>
                <tr>
                  <th scope="col">Version</th>
                  <th scope="col">Published</th>
                  <th scope="col">By</th>
                  <th scope="col" className="crm-text-end">
                    Enrollments
                  </th>
                  <th scope="col">
                    <span className="crm-visually-hidden">Actions</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {versions.map((v) => (
                  <tr key={v.id} className={cn(openId === v.id && 'is-selected')}>
                    <td data-label="Version">
                      <strong>v{v.versionNo}</strong>
                      {v.publishedAt === null ? (
                        <span className="badge badge--warning crm-ms-2">Draft</span>
                      ) : null}
                      {v.current ? (
                        <span className="badge badge--success crm-ms-2">Live</span>
                      ) : null}
                    </td>
                    <td data-label="Published" className="crm-text-nowrap">
                      {v.publishedAt ? formatWhen(v.publishedAt, timeZone) : 'Not yet'}
                    </td>
                    <td data-label="By">{memberName(v.createdBy)}</td>
                    <td data-label="Enrollments" className="crm-text-end">
                      {v.enrollments}
                    </td>
                    <td data-label="Actions" className="crm-text-end crm-text-nowrap">
                      <div className="crm-d-inline-flex crm-gap-2">
                        <button
                          type="button"
                          className="btn-crm btn-crm--outline btn-crm--sm"
                          onClick={() => setOpenId(openId === v.id ? null : v.id)}
                        >
                          {openId === v.id ? 'Hide' : 'View'}
                        </button>
                        {canEdit && v.publishedAt !== null ? (
                          <button
                            type="button"
                            className="btn-crm btn-crm--ghost btn-crm--sm"
                            onClick={() => setRestoring(v)}
                          >
                            Restore
                          </button>
                        ) : null}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {openId ? (
        <section className="sales-card sales-card--pad">
          {detailError ? <Alert tone="danger">{detailError}</Alert> : null}
          {!detail && !detailError ? <p className="crm-text-muted">Loading version…</p> : null}
          {detail && definition ? (
            <>
              <h3 className="sales-card__title crm-mb-2">
                Version {detail.versionNo}
                {detail.publishedAt === null ? ' (draft)' : ''}
              </h3>
              <p className="crm-fs-7 crm-text-muted crm-mb-3">
                {detail.diff.againstVersionNo
                  ? `Compared with version ${detail.diff.againstVersionNo}: `
                  : 'First version. '}
                {detail.diff.againstVersionNo
                  ? [
                      detail.diff.triggerChanged ? 'trigger changed' : null,
                      detail.diff.settingsChanged ? 'settings changed' : null,
                      detail.diff.stepsAdded.length
                        ? `${detail.diff.stepsAdded.length} step(s) added`
                        : null,
                      detail.diff.stepsChanged.length
                        ? `${detail.diff.stepsChanged.length} changed`
                        : null,
                      detail.diff.stepsRemoved.length
                        ? `${detail.diff.stepsRemoved.length} removed (${detail.diff.stepsRemoved.join(', ')})`
                        : null,
                    ]
                      .filter(Boolean)
                      .join(', ') || 'no changes.'
                  : ''}
              </p>
              <div className="eyebrow-label crm-mb-1">Trigger</div>
              <p className="crm-mb-3">{triggerSummary(definition.trigger)}</p>
              <div className="eyebrow-label crm-mb-1">Steps</div>
              <StepOutline steps={definition.steps} highlight={highlight} />
            </>
          ) : null}
        </section>
      ) : null}

      <CrmModal
        id="wfRestoreModal"
        open={Boolean(restoring)}
        onClose={busy ? () => {} : () => setRestoring(null)}
      >
        <ModalHeader
          id="wfRestoreModal"
          title={`Restore version ${restoring?.versionNo ?? ''}?`}
          onClose={busy ? () => {} : () => setRestoring(null)}
        />
        <div className="modal__body">
          <p>
            Version {restoring?.versionNo} is copied into the draft
            {workflow.draft ? ', replacing the current draft' : ''}. Nothing changes for records
            until you publish it.
          </p>
          {dirty ? (
            <Alert tone="warning">Your unsaved changes in the editor will be lost.</Alert>
          ) : null}
        </div>
        <div className="modal__footer">
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={() => setRestoring(null)}
            disabled={busy}
          >
            Cancel
          </button>
          <button
            type="button"
            className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
            onClick={() => void restore()}
            disabled={busy}
          >
            Restore into draft
          </button>
        </div>
      </CrmModal>
    </div>
  );
}
