'use client'

import { useRef, useState, useEffect, useCallback } from 'react'
import { cn } from '@/lib/utils'

interface TriplePaneProps {
  left: React.ReactNode
  middle: React.ReactNode
  right: React.ReactNode
  storageKey: string
  defaultLeft?: number   // % width for left pane
  defaultMiddle?: number // % width for middle pane, right gets the rest
  minSize?: number       // minimum px per pane
}

export function TriplePane({
  left, middle, right, storageKey,
  defaultLeft = 28, defaultMiddle = 35, minSize = 180,
}: TriplePaneProps) {
  const containerRef = useRef<HTMLDivElement>(null)

  const load = (key: string, def: number) => {
    if (typeof window === 'undefined') return def
    const stored = localStorage.getItem(`triple-pane:${storageKey}:${key}`)
    if (stored) {
      const val = parseFloat(stored)
      if (!isNaN(val) && val > 0 && val < 100) return val
    }
    return def
  }

  const [leftPct, setLeftPct] = useState(() => load('left', defaultLeft))
  const [midPct, setMidPct] = useState(() => load('mid', defaultMiddle))
  const [dragging, setDragging] = useState<'left' | 'right' | null>(null)
  const [isMobile, setIsMobile] = useState(false)
  const [activeTab, setActiveTab] = useState<'left' | 'middle' | 'right'>('left')

  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth < 1024)
    check()
    window.addEventListener('resize', check)
    return () => window.removeEventListener('resize', check)
  }, [])

  const onMouseMove = useCallback((e: MouseEvent) => {
    if (!dragging || !containerRef.current) return
    const rect = containerRef.current.getBoundingClientRect()
    const width = rect.width
    const minPct = (minSize / width) * 100
    const offsetPct = ((e.clientX - rect.left) / width) * 100

    if (dragging === 'left') {
      const clamped = Math.min(Math.max(offsetPct, minPct), 100 - midPct - minPct)
      setLeftPct(clamped)
      localStorage.setItem(`triple-pane:${storageKey}:left`, String(clamped))
    } else {
      const clamped = Math.min(Math.max(offsetPct - leftPct, minPct), 100 - leftPct - minPct)
      setMidPct(clamped)
      localStorage.setItem(`triple-pane:${storageKey}:mid`, String(clamped))
    }
  }, [dragging, leftPct, midPct, minSize, storageKey])

  const onMouseUp = useCallback(() => setDragging(null), [])

  useEffect(() => {
    if (dragging) {
      window.addEventListener('mousemove', onMouseMove)
      window.addEventListener('mouseup', onMouseUp)
    }
    return () => {
      window.removeEventListener('mousemove', onMouseMove)
      window.removeEventListener('mouseup', onMouseUp)
    }
  }, [dragging, onMouseMove, onMouseUp])

  if (isMobile) {
    const tabs = ['left', 'middle', 'right'] as const
    const labels = ['Backlog', 'Sprint', 'Taken']
    return (
      <div className="flex flex-col h-full">
        <div className="flex border-b border-border shrink-0">
          {tabs.map((tab, i) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={cn(
                'flex-1 py-2 text-xs font-medium transition-colors',
                activeTab === tab
                  ? 'border-b-2 border-primary text-primary'
                  : 'text-muted-foreground hover:text-foreground'
              )}
            >
              {labels[i]}
            </button>
          ))}
        </div>
        <div className="flex-1 overflow-auto">
          {activeTab === 'left' ? left : activeTab === 'middle' ? middle : right}
        </div>
      </div>
    )
  }

  const rightPct = 100 - leftPct - midPct

  return (
    <div ref={containerRef} className="flex h-full overflow-hidden select-none">
      <div className="flex flex-col overflow-hidden" style={{ width: `${leftPct}%` }}>
        {left}
      </div>

      <div
        onMouseDown={() => setDragging('left')}
        className={cn(
          'w-1 shrink-0 bg-border hover:bg-primary transition-colors cursor-col-resize',
          dragging === 'left' && 'bg-primary'
        )}
      />

      <div className="flex flex-col overflow-hidden" style={{ width: `${midPct}%` }}>
        {middle}
      </div>

      <div
        onMouseDown={() => setDragging('right')}
        className={cn(
          'w-1 shrink-0 bg-border hover:bg-primary transition-colors cursor-col-resize',
          dragging === 'right' && 'bg-primary'
        )}
      />

      <div className="flex flex-col overflow-hidden" style={{ width: `${rightPct}%` }}>
        {right}
      </div>
    </div>
  )
}
