"use client";

import React, { useEffect } from "react";
import { useEditLockStore } from "@/hooks/useEditLockStore";
import { useAuthStore } from "@/hooks/useAuthStore";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Lock, AlertCircle, CheckCircle2 } from "lucide-react";

interface EditLockIndicatorProps {
  entityType: string;
  entityId: string;
}

export function EditLockIndicator({ entityType, entityId }: EditLockIndicatorProps) {
  const { lockInfo, checkLock, acquireLock, releaseLock } = useEditLockStore();
  const { user } = useAuthStore();

  useEffect(() => {
    // Check lock immediately
    checkLock(entityType, entityId);

    // Set up auto-acquisition/renewal if authenticated
    if (user) {
      acquireLock(entityType, entityId);
      
      // Renew every 2 minutes (TTL is 5 minutes)
      const interval = setInterval(() => {
        acquireLock(entityType, entityId);
      }, 120000);

      return () => {
        clearInterval(interval);
        releaseLock(entityType, entityId);
      };
    }
  }, [entityType, entityId, user, checkLock, acquireLock, releaseLock]);

  if (!lockInfo) return null;

  const isOwnLock = lockInfo.userId === user?.id;

  if (isOwnLock) {
    return (
      <Alert className="bg-primary/5 border-primary/20 mb-4">
        <CheckCircle2 className="h-4 w-4 text-primary" />
        <AlertTitle className="text-sm font-semibold">Active Edit Lock</AlertTitle>
        <AlertDescription className="text-xs">
          You have an active edit lock on this {entityType}. Others will see it as &quot;in use&quot;.
        </AlertDescription>
      </Alert>
    );
  }

  return (
    <Alert variant="destructive" className="mb-4 animate-in fade-in slide-in-from-top-2">
      <AlertCircle className="h-4 w-4" />
      <AlertTitle className="text-sm font-semibold text-destructive">Warning: Entity In Use</AlertTitle>
      <AlertDescription className="text-xs">
        Currently being edited by <strong>{lockInfo.userName}</strong>. Your changes might be overwritten if they save first.
      </AlertDescription>
    </Alert>
  );
}
