import ActiveObjectContext from "@/components/Context/activeObject/ObjectContext";
import CanvasContext from "@/components/Context/canvasContext/CanvasContext";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import { useContext, useEffect, useState } from "react";
import { Lock, Unlock } from "lucide-react";
import { Tooltip } from "react-tooltip";

const LockObject = () => {
  const { canvas } = useContext(CanvasContext);
  const { activeObject } = useContext(ActiveObjectContext);
  const [isLocked, setIsLocked] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    if (activeObject?.lockMovementX === false) {
      setIsLocked(false);
    } else {
      setIsLocked(true);
    }
  }, [activeObject]);

  const toggleLock = () => {
    if (!canvas || !activeObject) {
      toast({
        title: "No object selected",
        description: "Please select an object to lock or unlock.",
        variant: "destructive",
      });
      return;
    }

    const newLockState = !activeObject.lockMovementX;
    activeObject.set({
      lockMovementX: newLockState,
      lockMovementY: newLockState,
      lockRotation: newLockState,
      lockScalingX: newLockState,
      lockScalingY: newLockState,
    });

    setIsLocked(newLockState);
    canvas.requestRenderAll();

    toast({
      title: newLockState ? "Object locked" : "Object unlocked",
      description: newLockState
        ? "The object is now locked in place."
        : "The object can now be moved and resized.",
    });
  };

  return (
    <div className="shadow-none border-0">
      <a data-tooltip-id="lock">
        <Button
          onClick={toggleLock}
          variant="outline"
          size="icon"
          disabled={!activeObject}
          title={isLocked ? "Unlock object" : "Lock object"}
        >
          {isLocked ? (
            <Unlock className="h-4 w-4" />
          ) : (
            <Lock className="h-4 w-4" />
          )}
        </Button>
      </a>
      <Tooltip id="lock" content="Lock object" place="bottom" />
    </div>
  );
};

export default LockObject;
