import * as React from "react";
import { useState } from "react";
import { CollapseToggleProps, TOGGLE_RADIUS } from "./Interface";

export function CollapseToggle({
  isCollapsed,
  borderColor,
  cardHeight,
  onToggle,
  isLoading,
}: CollapseToggleProps) {
  const [isHovered, setIsHovered] = useState(false);
  const [isActive, setIsActive] = useState(false);

  const chevronUp = "M-4,2 L0,-2.5 L4,2";
  const chevronDown = "M-4,-2 L0,2.5 L4,-2";

  return (
    <g
      transform={`translate(0, ${cardHeight / 2})`}
      onClick={(e) => {
        e.stopPropagation();
        if (!isLoading && e.detail !== 0) onToggle();
      }}
      onDoubleClick={(e) => {
        e.stopPropagation();
      }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      onTouchStart={() => setIsActive(true)}
      onTouchEnd={(e) => {
        e.stopPropagation();
        setIsActive(false);
        if (!isLoading) onToggle();
      }}
      style={{ cursor: isLoading ? "wait" : "pointer" }}
    >
      <circle r={22} fill="transparent" />
      <circle
        r={TOGGLE_RADIUS}
        fill={(isHovered || isActive) && !isLoading ? "#f0fdfd" : "#ffffff"}
        stroke={borderColor}
        strokeWidth={(isHovered || isActive) ? 2.5 : 1.5}
        filter={(isHovered || isActive) ? "url(#toggle-hover-shadow)" : undefined}
        style={{ transition: "stroke-width 0.12s ease" }}
      />
      {isLoading ? (
        <path
          d="M0,-7 A7,7 0 0,1 7,0"
          fill="none"
          stroke={borderColor}
          strokeWidth={2.5}
          strokeLinecap="round"
          style={{
            transformOrigin: "0px 0px",
            animation: "toggleSpin 0.6s linear infinite",
          }}
        />
      ) : (
        <path
          d={isCollapsed ? chevronDown : chevronUp}
          fill="none"
          stroke={borderColor}
          strokeWidth={(isHovered || isActive) ? 2.5 : 2}
          strokeLinecap="round"
          strokeLinejoin="round"
          style={{ transition: "stroke-width 0.12s ease" }}
        />
      )}
    </g>
  );
}
