'use client';

import { useMemo } from 'react';
import { Hash, User, StickyNote, Boxes } from 'lucide-react';
import { cn } from '../../lib/utils';
import { Badge } from '../ui/badge';

/**
 * Minimal, in-package shape of a workflow version. Mirrors the subset of the
 * backend version record the history view actually reads — kept local so the
 * component carries no app type coupling.
 */
export interface WorkflowVersion {
  uuid: string;
  versionNumber: number;
  timestamp: string;
  isPublished?: boolean;
  versionNote?: string | null;
  createdBy?: {
    firstName?: string | null;
    lastName?: string | null;
    email: string;
  } | null;
  /** Opaque workflow definition; only `nodes.length` is read for display. */
  workflowData?: Record<string, unknown> | null;
}

export interface WorkflowVersionHistoryProps {
  versions: WorkflowVersion[];
  /**
   * Formats a version's ISO timestamp for display. Supplied by the consumer
   * so this component stays free of date/locale dependencies. Defaults to the
   * raw timestamp string when omitted.
   */
  formatTimestamp?: (timestamp: string) => string;
  className?: string;
}

export function WorkflowVersionHistory({
  versions,
  formatTimestamp,
  className,
}: WorkflowVersionHistoryProps) {
  const sorted = useMemo(
    () => [...versions].sort((a, b) => b.versionNumber - a.versionNumber),
    [versions]
  );

  if (versions.length === 0) {
    return (
      <div className={cn('text-center py-12', className)}>
        <Hash className="h-12 w-12 mx-auto mb-3 text-muted-foreground" />
        <h3 className="text-lg font-semibold mb-2">No Versions Yet</h3>
        <p className="text-muted-foreground max-w-sm mx-auto">
          No versions published yet. Use the canvas toolbar to publish a
          version.
        </p>
      </div>
    );
  }

  const formatTime = formatTimestamp ?? ((t: string) => t);

  return (
    <ol className={cn('relative space-y-6', className)}>
      {sorted.map((version, index) => {
        const label = version.versionNote
          ? `v${version.versionNumber} — ${version.versionNote}`
          : `v${version.versionNumber}`;

        const nodeCount =
          version.workflowData &&
          Array.isArray(
            (version.workflowData as Record<string, unknown>).nodes
          )
            ? (
                (version.workflowData as Record<string, unknown>)
                  .nodes as unknown[]
              ).length
            : null;

        const isLast = index === sorted.length - 1;

        return (
          <li key={version.uuid} className="relative pl-8">
            {/* Timeline rail + dot */}
            {!isLast && (
              <span
                className="absolute left-[7px] top-5 bottom-[-1.5rem] w-px bg-border"
                aria-hidden="true"
              />
            )}
            <span
              className={cn(
                'absolute left-0 top-1 h-3.5 w-3.5 rounded-full border-2',
                version.isPublished
                  ? 'border-green-500 bg-green-500'
                  : 'border-muted-foreground bg-background'
              )}
              aria-hidden="true"
            />

            <div className="flex items-center justify-between gap-2">
              <span className="font-medium text-sm">{label}</span>
              <span className="text-xs text-muted-foreground">
                {formatTime(version.timestamp)}
              </span>
            </div>

            <div className="mt-2 space-y-2 text-sm">
              {version.isPublished && (
                <div>
                  <Badge
                    variant="outline"
                    className="border-green-200 bg-green-50 text-green-700 dark:border-green-800 dark:bg-green-950/30 dark:text-green-400"
                  >
                    Published
                  </Badge>
                </div>
              )}
              {version.createdBy && (
                <div className="flex items-center gap-2 text-muted-foreground">
                  <User className="h-3.5 w-3.5 shrink-0" />
                  <span>
                    {version.createdBy.firstName
                      ? `${version.createdBy.firstName} ${version.createdBy.lastName ?? ''}`.trim()
                      : version.createdBy.email}
                  </span>
                </div>
              )}
              {version.versionNote && (
                <div className="flex items-start gap-2 text-muted-foreground">
                  <StickyNote className="h-3.5 w-3.5 shrink-0 mt-0.5" />
                  <span>{version.versionNote}</span>
                </div>
              )}
              {nodeCount !== null && (
                <div className="flex items-center gap-2 text-muted-foreground">
                  <Boxes className="h-3.5 w-3.5 shrink-0" />
                  <span>
                    {nodeCount} node{nodeCount !== 1 ? 's' : ''}
                  </span>
                </div>
              )}
            </div>
          </li>
        );
      })}
    </ol>
  );
}
