"use client"
import React, { ComponentPropsWithoutRef } from "react"
import { useContextSelector } from "use-context-selector"
import { classNames } from "../../utils"
import { Button } from "../Button"
import { SpaceBetween, SpaceBetweenProps } from "../SpaceBetween"
import { Text, TextBodyProps } from "../Text"
import { ChartContext } from "./ChartContext"

const ChartPanelBase = ({
  children,
  className,
  ...props
}: ComponentPropsWithoutRef<"figure">) => {
  return (
    <figure
      className={classNames(
        "flex flex-col rounded border-border-1 pt-4 md:border md:p-4",
        className,
      )}
      {...props}
    >
      {children}
    </figure>
  )
}

const ChartPanelTitle = ({
  children,
  size = "md",
  weight = "semibold",
  ...rest
}: TextBodyProps) => {
  return (
    <Text asChild size={size} weight={weight} {...rest}>
      <figcaption>{children}</figcaption>
    </Text>
  )
}

const ChartPanelHeader = ({ className, ...rest }: SpaceBetweenProps) => {
  return (
    <SpaceBetween
      className={classNames("h-14 items-start", className)}
      {...rest}
    />
  )
}

const ChartPanelResetZoom = () => {
  const [isZoomed, resetZoom] = useContextSelector(ChartContext, v => [
    v.isZoomed,
    v.resetZoom,
  ])

  // if not zoomed then don't show the reset button
  if (!isZoomed) {
    return <></>
  }

  return (
    <Button size="sm" variant="secondary" onClick={resetZoom}>
      Reset
    </Button>
  )
}

export const ChartPanel = Object.assign(ChartPanelBase, {
  Header: ChartPanelHeader,
  Title: ChartPanelTitle,
  ResetZoom: ChartPanelResetZoom,
})
