"use client";

import React, { createContext, useCallback, useContext, useState } from "react";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from "@/components/ui/sheet";

import WhiteboardCanvas from "@/app/components/whiteboard/WhiteboardCanvas";

type WhiteboardContextType = {
  open: () => void;
  close: () => void;
  isOpen: boolean;
};

const WhiteboardContext = createContext<WhiteboardContextType | null>(null);

export const useWhiteboard = (): WhiteboardContextType => {
  const ctx = useContext(WhiteboardContext);
  if (!ctx) {
    throw new Error("useWhiteboard must be used within WhiteboardProvider");
  }
  return ctx;
};

export function WhiteboardProvider({ children }: { children: React.ReactNode }) {
  const [isOpen, setIsOpen] = useState(false);

  const open = useCallback(() => setIsOpen(true), []);
  const close = useCallback(() => setIsOpen(false), []);

  return (
    <WhiteboardContext.Provider value={{ open, close, isOpen }}>
      {children}
      <Sheet open={isOpen} onOpenChange={setIsOpen}>
        <SheetContent side="right" className="w-full sm:max-w-[560px] p-0">
          <SheetHeader className="p-4 border-b">
            <SheetTitle>Whiteboard</SheetTitle>
            <SheetDescription>
              Sketch ideas. Use mouse or touch to draw.
            </SheetDescription>
          </SheetHeader>
          <div className="p-4">
            <WhiteboardCanvas />
          </div>
        </SheetContent>
      </Sheet>
    </WhiteboardContext.Provider>
  );
}
