'use client';

import {useCallback, useEffect, useState} from 'react';
import {useLoyalyAi} from '@/features/loyaly-ai/providers/LoyalyAiProvider';

export function ResizeHandle() {
  const {panelWidth, setPanelWidth, panelMode} = useLoyalyAi();
  const [isDragging, setIsDragging] = useState(false);

  useEffect(() => {
    if (!isDragging) return;

    const handleMouseMove = (e: MouseEvent) => {
      const newWidth = window.innerWidth - e.clientX;
      setPanelWidth(newWidth);
    };

    const handleMouseUp = () => {
      setIsDragging(false);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging, setPanelWidth]);

  // Hidden when in fullscreen mode
  if (panelMode === 'fullscreen') return null;

  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDoubleClick = () => {
    setPanelWidth(440);
  };

  return (
    <div
      onMouseDown={handleMouseDown}
      onDoubleClick={handleDoubleClick}
      title="Drag to resize panel (Double click to reset)"
      className={`absolute left-0 top-0 bottom-0 w-2 -ml-1 cursor-col-resize z-20 group flex justify-center ${
        isDragging ? 'select-none' : ''
      }`}
    >
      <div
        className={`w-0.5 h-full transition-colors duration-150 ${
          isDragging
            ? 'bg-primary shadow-sm'
            : 'bg-transparent group-hover:bg-border-strong'
        }`}
      />
    </div>
  );
}
