import ActiveObjectContext from "@/components/Context/activeObject/ObjectContext";
import CanvasContext from "@/components/Context/canvasContext/CanvasContext";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { useContext, useEffect, useState } from "react";
import { BsTransparency } from "react-icons/bs";
import { Button } from "@/components/ui/button";
import { Tooltip } from "react-tooltip";

const OpacityCustomization = () => {
  const { activeObject } = useContext(ActiveObjectContext);
  const { canvas } = useContext(CanvasContext);
  const [opacity, setOpacity] = useState(0);

  useEffect(() => {
    if (activeObject) {
      setOpacity(activeObject?.opacity);
    }
  }, [activeObject]);

  const adjustBackgroundOpacity = (newOpacity) => {
    setOpacity(newOpacity);
    if (activeObject) {
      activeObject.set("opacity", newOpacity);
      canvas.renderAll();
    }
  };

  return (
    <div>
      <Popover>
        <PopoverTrigger asChild>
          <a data-tooltip-id="opacity-ic">
            <Button variant="ghost" size="icon" className="h-8 w-8">
              <BsTransparency className="h-4 w-4" size={20} />
            </Button>
          </a>
        </PopoverTrigger>
        <PopoverContent className="w-64 mt-3">
          <div className="grid gap-4">
            <div className="flex items-center justify-between">
              <Label className="text-sm font-medium">Opacity</Label>
              <span className="text-sm text-gray-500">
                {Math.round(opacity * 100)}%
              </span>
            </div>
            <Slider
              value={[opacity]}
              min={0}
              max={1}
              step={0.01}
              onValueChange={(value) => adjustBackgroundOpacity(value[0])}
            />
          </div>
        </PopoverContent>
      </Popover>
      <Tooltip id="opacity-ic" content="Transparency" place="bottom" />
    </div>
  );
};

export default OpacityCustomization;
