import { useMemo, useState } from "react";
import ChartComponent from "../../layout/sidebarLeft/visualization/widgets/ChartComponent";
import { useWidgetStore } from "../../../store/useWidgetStore";

export const DraggableWidget = ({ widget }: { widget: any }) => {
  const { selectedChartId, setSelectedChartId } = useWidgetStore();

  // State for managing the popup visibility and customization options
  const [isPopupOpen, setIsPopupOpen] = useState(false);
  const [customizationOptions, setCustomizationOptions] = useState({
    templateBackground: "#ffffff",
    cardBackground: "#ffffff",
    cardOpacity: 1,
    cardBlur: 0,
    font: "Arial",
    margin: 0,
    radius: 5,
    shadow: "Low",
  });

  // Handle pointer down to select the chart
  const handlePointerDown = () => {
    if (selectedChartId?.id !== widget.id) {
      setSelectedChartId(widget);
    }
  };

  // Handle double-click to open the popup
  const handleDoubleClick = () => {
    setIsPopupOpen(true);
  };

  // Close the popup
  const handleClosePopup = () => {
    setIsPopupOpen(false);
  };

  // Save the changes made in the popup
  const handleSaveChanges = () => {
    // Here you can save the customizationOptions to your store or API
    console.log("Saved Customization Options:", customizationOptions);
    setIsPopupOpen(false);
  };

  // Compute dynamic card styles based on customizationOptions
  const cardStyle = useMemo(() => {
    const shadowLevels = {
      Low: "0px 2px 4px rgba(0, 0, 0, 0.1)",
      Medium: "0px 4px 8px rgba(0, 0, 0, 0.2)",
      High: "0px 8px 16px rgba(0, 0, 0, 0.3)",
    };

    return {
      backgroundColor: customizationOptions.cardBackground,
      opacity: customizationOptions.cardOpacity,
      filter: `blur(${customizationOptions.cardBlur}px)`,
      fontFamily: customizationOptions.font,
      margin: `${customizationOptions.margin}px`,
      borderRadius: `${customizationOptions.radius}px`,
    //   boxShadow: shadowLevels[customizationOptions.shadow],
    };
  }, [customizationOptions]);

  return (
    <>
      <div
        key={widget.id}
        className={`chart-container ${selectedChartId?.id === widget.id && "activeChart"}`}
        style={cardStyle} // Apply dynamic card styles here
        onPointerDown={handlePointerDown}
        onDoubleClick={handleDoubleClick} // Add double-click event
      >
        {widget.type === "progress" ? (
        //   <ProgressCard title={widget.title} data={widget.data} />
        <></>
        ) : (
          <ChartComponent
            type={widget.type}
            title={widget.title}
            fontFamily={customizationOptions.font} // Pass font customization to ChartComponent
            fontSize={widget.fontSize}
            fontWeight={widget.fontWeight}
            data={widget.data}
          />
        )}
      </div>

      {/* Popup for Customizing Template Theme */}
      {isPopupOpen && (
        <div className="popup-overlay">
          <div className="popup-content">
            <h2>Customize Template Theme</h2>
            <div className="form-group">
              <label>Template Background</label>
              <input
                type="color"
                value={customizationOptions.templateBackground}
                onChange={(e) =>
                  setCustomizationOptions((prev) => ({
                    ...prev,
                    templateBackground: e.target.value,
                  }))
                }
              />
            </div>
            <div className="form-group">
              <label>Card Background</label>
              <input
                type="color"
                value={customizationOptions.cardBackground}
                onChange={(e) =>
                  setCustomizationOptions((prev) => ({
                    ...prev,
                    cardBackground: e.target.value,
                  }))
                }
              />
            </div>
            <div className="form-group">
              <label>Card Opacity</label>
              <input
                type="range"
                min="0"
                max="1"
                step="0.1"
                value={customizationOptions.cardOpacity}
                onChange={(e) =>
                  setCustomizationOptions((prev) => ({
                    ...prev,
                    cardOpacity: parseFloat(e.target.value),
                  }))
                }
              />
            </div>
            <div className="form-group">
              <label>Card Blur</label>
              <input
                type="range"
                min="0"
                max="10"
                value={customizationOptions.cardBlur}
                onChange={(e) =>
                  setCustomizationOptions((prev) => ({
                    ...prev,
                    cardBlur: parseInt(e.target.value),
                  }))
                }
              />
            </div>
            <div className="form-group">
              <label>Font</label>
              <select
                value={customizationOptions.font}
                onChange={(e) =>
                  setCustomizationOptions((prev) => ({
                    ...prev,
                    font: e.target.value,
                  }))
                }
              >
                <option value="Arial">Arial</option>
                <option value="Times New Roman">Times New Roman</option>
                <option value="Courier New">Courier New</option>
              </select>
            </div>
            <div className="form-group">
              <label>Margin</label>
              <input
                type="number"
                value={customizationOptions.margin}
                onChange={(e) =>
                  setCustomizationOptions((prev) => ({
                    ...prev,
                    margin: parseInt(e.target.value),
                  }))
                }
              />
            </div>
            <div className="form-group">
              <label>Radius</label>
              <input
                type="number"
                value={customizationOptions.radius}
                onChange={(e) =>
                  setCustomizationOptions((prev) => ({
                    ...prev,
                    radius: parseInt(e.target.value),
                  }))
                }
              />
            </div>
            <div className="form-group">
              <label>Shadow</label>
              <select
                value={customizationOptions.shadow}
                onChange={(e) =>
                  setCustomizationOptions((prev) => ({
                    ...prev,
                    shadow: e.target.value,
                  }))
                }
              >
                <option value="Low">Low</option>
                <option value="Medium">Medium</option>
                <option value="High">High</option>
              </select>
            </div>
            <div className="popup-actions">
              <button onClick={handleClosePopup}>Cancel</button>
              <button onClick={handleSaveChanges}>Save Changes</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
};
