import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { History } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { EntityVersionHistory } from './EntityVersionHistory';
import { useEntityVersions } from '@/hooks/useEntityVersions';
import type { EntityType } from '@/types/versioning';

interface VersionIndicatorProps {
  entityType: EntityType;
  entityId: string;
  entityName: string;
  compact?: boolean;
}

export function VersionIndicator({
  entityType,
  entityId,
  entityName,
  compact = false,
}: VersionIndicatorProps) {
  const [showHistory, setShowHistory] = useState(false);
  const { currentVersion, loading } = useEntityVersions(entityType, entityId);

  if (loading || !currentVersion) {
    return null;
  }

  const timeAgo = currentVersion.created_at
    ? formatDistanceToNow(new Date(currentVersion.created_at), { addSuffix: true })
    : 'Unknown';

  if (compact) {
    return (
      <>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setShowHistory(true)}
          className="gap-2"
        >
          <History className="h-4 w-4" />
          <span className="text-xs text-muted-foreground">
            History
          </span>
        </Button>

        <Dialog open={showHistory} onOpenChange={setShowHistory}>
          <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Version History: {entityName}</DialogTitle>
            </DialogHeader>
            <EntityVersionHistory
              entityType={entityType}
              entityId={entityId}
              entityName={entityName}
            />
          </DialogContent>
        </Dialog>
      </>
    );
  }

  return (
    <>
      <div className="flex items-center gap-3">
        <span className="text-sm text-muted-foreground">
          Last edited {timeAgo}
        </span>
        <Button
          variant="outline"
          size="sm"
          onClick={() => setShowHistory(true)}
          className="gap-2"
        >
          <History className="h-4 w-4" />
          View History
        </Button>
      </div>

      <Dialog open={showHistory} onOpenChange={setShowHistory}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Version History: {entityName}</DialogTitle>
          </DialogHeader>
          <EntityVersionHistory
            entityType={entityType}
            entityId={entityId}
            entityName={entityName}
          />
        </DialogContent>
      </Dialog>
    </>
  );
}
