import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { History, Clock } 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">
            v{currentVersion.version_number}
          </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">
        <Badge variant="outline" className="gap-1.5">
          <Clock className="h-3 w-3" />
          Version {currentVersion.version_number}
        </Badge>
        <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>
    </>
  );
}
