"use client";
import Toolbar from "./Toolbar";
import React from "react";
import Board from "./Board";
import Popup from "../PopUp";
import ImageUpload from "../ImageUpload";
import { ToolbarMode, Color } from "@/lib/Enums";
import styles from "@/styles/DrawBoard/DrawBoard.module.css";

type DrawBoardHandle = {
  getCanvasImageBase64: () => string;
  clear: () => void;
};

type DrawBoardProps = {
  timerLabel?: string;
  timerProgress?: number;
  allowWriting?: boolean;
  allowDrawing?: boolean;
  allowImageUpload?: boolean;
};

const DrawBoard = React.forwardRef<DrawBoardHandle, DrawBoardProps>(
  ({ timerLabel, timerProgress, allowWriting = true, allowDrawing = true, allowImageUpload = true }, ref) => {
    const [toolbarMode, setToolbarMode] = React.useState<ToolbarMode>(ToolbarMode.Draw);
    const [imageUrl, setImageUrl] = React.useState<string | null>(null);
    const [color, setColor] = React.useState<Color>(Color.Black);

    const boardRef = React.useRef<{ getCanvasImageBase64: () => string; clear: () => void } | null>(null);
    const clampedProgress = React.useMemo(() => {
      if (typeof timerProgress !== "number") return 1;
      return Math.max(0, Math.min(1, timerProgress));
    }, [timerProgress]);
    const showTimer = typeof timerProgress === "number" || typeof timerLabel === "string";

    React.useImperativeHandle(ref, () => ({
      getCanvasImageBase64() {
        // Prefer the generated canvas data; if not available fall back to uploaded image url
        const data = boardRef.current?.getCanvasImageBase64();
        if (data && data.length) return data;
        return imageUrl ?? "";
      },
      clear() {
        // Clear uploaded image and the visible line layer
        setImageUrl(null);
        try {
          boardRef.current?.clear();
        } catch (err) {
          console.error("DrawBoard.clear failed:", err);
        }
      }
    }), [imageUrl]);

    React.useEffect(() => {
      // wenn aktueller Mode deaktiviert wird, auf erlaubten Modus zurückfallen
      if (!allowDrawing && toolbarMode === ToolbarMode.Draw) {
        setToolbarMode(allowWriting ? ToolbarMode.Write : ToolbarMode.Nothing);
      }
      if (!allowWriting && toolbarMode === ToolbarMode.Write) {
        setToolbarMode(allowDrawing ? ToolbarMode.Draw : ToolbarMode.Nothing);
      }
      if (!allowImageUpload && toolbarMode === ToolbarMode.Image) {
        setToolbarMode(allowDrawing ? ToolbarMode.Draw : ToolbarMode.Nothing);
      }
    }, [allowDrawing, allowWriting, allowImageUpload, toolbarMode]);

    function imageIsUploaded(imageUrl: string) {
      setToolbarMode(ToolbarMode.Draw);
      setImageUrl(imageUrl);
    }

    return (
      <div>
        <div className={styles.boardWrap}>
          {showTimer && (
            <div className={styles.timerFrame} aria-hidden="true">
              <svg className={styles.timerSvg} viewBox="0 0 800 600" preserveAspectRatio="none">
                <defs>
                  <clipPath id="timerClip">
                    <rect x="0" y="0" width="800" height="600" />
                  </clipPath>
                </defs>
                <g clipPath="url(#timerClip)">
                  <rect
                    className={styles.timerTrack}
                    x="3"
                    y="3"
                    width="794"
                    height="594"
                  />
                  <rect
                    className={styles.timerProgress}
                    x="3"
                    y="3"
                    width="794"
                    height="594"
                    pathLength={100}
                    style={{ strokeDashoffset: -100 * (1 - clampedProgress) }}
                  />
                </g>
              </svg>
            </div>
          )}
          {timerLabel && (
            <div className={styles.timerLabel}>
              <span className={styles.timerLabelTitle}>Timer</span>
              <span className={styles.timerLabelValue}>{timerLabel}</span>
            </div>
          )}
          <Board ref={boardRef} toolbarMode={toolbarMode} imageUrl={imageUrl} color={color} />
          <div className={styles.toolbarOverlay}>
            <Toolbar
              toolbarMode={toolbarMode}
              setToolbarMode={setToolbarMode}
              color={color}
              setColor={setColor}
              allowWriting={allowWriting}
              allowDrawing={allowDrawing}
              allowImageUpload={allowImageUpload}
            />
          </div>
        </div>
        <Popup
          isOpen={toolbarMode === ToolbarMode.Image}
          onClose={() => setToolbarMode(ToolbarMode.Draw)}
        >
          <h3>Image Options</h3>
          <ImageUpload addImageCallback={imageIsUploaded} />
        </Popup>
      </div>
    );
  });

DrawBoard.displayName = "DrawBoard";

export default DrawBoard;
export type { DrawBoardHandle };
