import { useEffect } from 'react';
import { History, RotateCcw, Check, Loader2, Zap } from 'lucide-react';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from '../ui/sheet';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { ScrollArea } from '../ui/scroll-area';
import { Skeleton } from '../ui/skeleton';
import {
  useVersions,
  useIsLoadingVersions,
  useVersionLoadError,
  useVersionActions,
} from '../../stores/versionStore';
import { Version } from '../../types/workflow';
import { __, sprintf } from '../../lib/i18n';
import { useCapabilities } from '../../hooks/useCapabilities';

export interface VersionHistoryPanelProps {
  /** Workflow ID to load versions for */
  workflowId: number;
  /** Whether the panel is open */
  isOpen: boolean;
  /** Callback when panel is closed */
  onClose: () => void;
  /** Callback when a version is restored */
  onRestore: (version: Version) => void;
  /** Callback when a version is made live */
  onMakeLive: (version: Version) => void;
}

/**
 * Format a date string for display
 */
function formatDate(dateString: string): string {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

  if (diffDays === 0) {
    // Today - show time
    return date.toLocaleTimeString(undefined, {
      hour: '2-digit',
      minute: '2-digit',
    });
  } else if (diffDays === 1) {
    return __('Yesterday');
  } else if (diffDays < 7) {
    return sprintf(__('%d days ago'), diffDays);
  } else {
    // Full date
    return date.toLocaleDateString(undefined, {
      month: 'short',
      day: 'numeric',
      year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined,
    });
  }
}

/**
 * Version History Panel component
 *
 * Displays a list of published versions with the ability to
 * view details and restore previous versions.
 */
export function VersionHistoryPanel({
  workflowId,
  isOpen,
  onClose,
  onRestore,
  onMakeLive,
}: VersionHistoryPanelProps) {
  const { versionHistory } = useCapabilities();
  const versions = useVersions();
  const isLoading = useIsLoadingVersions();
  const loadError = useVersionLoadError();
  const { isRestoring, isMakingLive, loadVersions } = useVersionActions();

  // Load versions when panel opens
  useEffect(() => {
    if (isOpen && workflowId) {
      loadVersions(workflowId);
    }
  }, [isOpen, workflowId, loadVersions]);

  if (!versionHistory) {
    return (
      <Sheet open={isOpen} onOpenChange={(open) => !open && onClose()}>
        <SheetContent className="w-[400px] sm:w-[540px] p-0 flex flex-col">
          <SheetHeader className="px-6 py-4 border-b border-slate-200">
            <SheetTitle>{__('Version History')}</SheetTitle>
            <SheetDescription>{__('Track changes to your workflow')}</SheetDescription>
          </SheetHeader>
          <div className="flex flex-col items-center justify-center py-12 text-center px-6">
            <History className="h-12 w-12 text-slate-300 mb-3" />
            <p className="text-sm text-slate-500">
              {__('Version history is available with Sequensy Pro.')}
            </p>
          </div>
        </SheetContent>
      </Sheet>
    );
  }

  return (
    <Sheet open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <SheetContent className="w-[400px] sm:w-[540px] p-0 flex flex-col">
        <SheetHeader className="px-6 py-4 border-b border-slate-200">
          <SheetTitle className="flex items-center gap-2">
            <History className="w-5 h-5" />
            {__('Version History')}
          </SheetTitle>
          <SheetDescription>
            {__('View and restore previous versions of this workflow.')}
          </SheetDescription>
        </SheetHeader>

        <ScrollArea className="flex-1">
          <div className="px-6 py-4">
            {isLoading ? (
              <div className="space-y-4">
                {[1, 2, 3].map((i) => (
                  <div
                    key={i}
                    className="flex items-start gap-4 p-4 rounded-lg border border-slate-200"
                  >
                    <Skeleton className="w-10 h-10 rounded-full" />
                    <div className="flex-1 space-y-2">
                      <Skeleton className="h-4 w-24" />
                      <Skeleton className="h-3 w-32" />
                    </div>
                  </div>
                ))}
              </div>
            ) : loadError ? (
              <div className="text-center py-8 text-slate-500">
                <p>{loadError}</p>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => loadVersions(workflowId)}
                  className="mt-2"
                >
                  {__('Try again')}
                </Button>
              </div>
            ) : versions.length === 0 ? (
              <div className="text-center py-8 text-slate-500">
                <History className="w-12 h-12 mx-auto mb-4 text-slate-300" />
                <p className="font-medium">{__('No versions yet')}</p>
                <p className="text-sm mt-1">
                  {__('Publish your workflow to create the first version.')}
                </p>
              </div>
            ) : (
              <div className="space-y-3">
                {versions.map((version) => (
                  <VersionItem
                    key={version.id}
                    version={version}
                    onRestore={() => onRestore(version)}
                    onMakeLive={() => onMakeLive(version)}
                    isRestoring={isRestoring}
                    isMakingLive={isMakingLive}
                  />
                ))}
              </div>
            )}
          </div>
        </ScrollArea>
      </SheetContent>
    </Sheet>
  );
}

interface VersionItemProps {
  version: Version;
  onRestore: () => void;
  onMakeLive: () => void;
  isRestoring: boolean;
  isMakingLive: boolean;
}

function VersionItem({
  version,
  onRestore,
  onMakeLive,
  isRestoring,
  isMakingLive,
}: VersionItemProps) {
  const isPublished = version.is_published;
  const isOperationInProgress = isRestoring || isMakingLive;

  return (
    <div
      className={`
        p-4 rounded-lg border transition-colors
        ${
          isPublished
            ? 'border-green-200 bg-green-50/50'
            : 'border-slate-200 hover:border-slate-300'
        }
      `}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <span className="font-semibold text-slate-900">
              {sprintf(__('Version %d'), version.version_number)}
            </span>
            {isPublished && (
              <Badge variant="success" className="text-xs gap-1">
                <Check className="w-3 h-3" />
                {__('Live')}
              </Badge>
            )}
          </div>
          <p className="text-sm text-slate-500 mt-0.5">{formatDate(version.created_at)}</p>
          {version.notes && (
            <p className="text-sm text-slate-600 mt-2 line-clamp-2">{version.notes}</p>
          )}
        </div>

        {!isPublished && (
          <div className="flex gap-2 shrink-0">
            <Button
              variant="ghost"
              size="sm"
              onClick={onRestore}
              disabled={isOperationInProgress}
              className="gap-1.5"
            >
              {isRestoring ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <RotateCcw className="w-4 h-4" />
              )}
              {__('Restore')}
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={onMakeLive}
              disabled={isOperationInProgress}
              className="gap-1.5 border-green-200 text-green-700 hover:bg-green-50 hover:text-green-800"
            >
              {isMakingLive ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Zap className="w-4 h-4" />
              )}
              {__('Make Live')}
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
