'use client'

import { differenceInDays, format, isWeekend, isToday } from 'date-fns'
import type { GanttTask, TimelineItem } from './types'
import { getHealthColor } from './lib/progress'
import { ROW_HEIGHT, ZOOM_LEVELS, INDENT_WIDTH } from './hooks/useGanttState'
import type { UseGanttStateReturn } from './hooks/useGanttState'

export interface GanttTimelineViewProps {
  // Layout props
  infoColumnWidth: number
  infoColumnLabel: string
  showCategory: boolean
  showStatus: boolean
  showFullscreen: boolean

  // State from useGanttState
  zoomIndex: UseGanttStateReturn['zoomIndex']
  setZoomIndex: UseGanttStateReturn['setZoomIndex']
  collapsed: UseGanttStateReturn['collapsed']
  mounted: UseGanttStateReturn['mounted']
  dragState: UseGanttStateReturn['dragState']
  focusedRowIndex: UseGanttStateReturn['focusedRowIndex']
  dayWidth: UseGanttStateReturn['dayWidth']
  tasks: UseGanttStateReturn['tasks']
  startDate: UseGanttStateReturn['startDate']
  days: UseGanttStateReturn['days']
  months: UseGanttStateReturn['months']
  timeHeaderUnits: UseGanttStateReturn['timeHeaderUnits']
  dependencyPaths: UseGanttStateReturn['dependencyPaths']
  timelineWidth: UseGanttStateReturn['timelineWidth']
  bodyHeight: UseGanttStateReturn['bodyHeight']
  isFullscreen: UseGanttStateReturn['isFullscreen']
  categoryColors: UseGanttStateReturn['categoryColors']
  onDateChange: UseGanttStateReturn['onDateChange']

  // Refs
  bodyScrollRef: UseGanttStateReturn['bodyScrollRef']
  headerTimelineRef: UseGanttStateReturn['headerTimelineRef']
  infoColumnRef: UseGanttStateReturn['infoColumnRef']

  // Handlers
  toggleFullscreen: UseGanttStateReturn['toggleFullscreen']
  handleItemClick: UseGanttStateReturn['handleItemClick']
  toggleCollapse: UseGanttStateReturn['toggleCollapse']
  handleBodyScroll: UseGanttStateReturn['handleBodyScroll']
  getBarPosition: UseGanttStateReturn['getBarPosition']
  handleDragStart: UseGanttStateReturn['handleDragStart']
}

export function GanttTimelineView({
  infoColumnWidth,
  infoColumnLabel,
  showCategory,
  showStatus,
  showFullscreen,
  zoomIndex,
  setZoomIndex,
  collapsed,
  mounted,
  dragState,
  focusedRowIndex,
  dayWidth,
  tasks,
  startDate,
  days,
  months,
  timeHeaderUnits,
  dependencyPaths,
  timelineWidth,
  bodyHeight,
  isFullscreen,
  categoryColors,
  onDateChange,
  bodyScrollRef,
  headerTimelineRef,
  infoColumnRef,
  toggleFullscreen,
  handleItemClick,
  toggleCollapse,
  handleBodyScroll,
  getBarPosition,
  handleDragStart,
}: GanttTimelineViewProps) {
  return (
    <>
      {/* Header row */}
      <div className="gantt-header-row">
        <div className="gantt-info-header" style={{ width: infoColumnWidth }}>
          <span style={{ flex: 1 }}>{infoColumnLabel}</span>
          <div className="gantt-zoom-controls">
            <button onClick={() => setZoomIndex((i) => Math.max(i - 1, 0))} disabled={zoomIndex === 0} aria-label="Zoom out">-</button>
            <input type="range" min="0" max={ZOOM_LEVELS.length - 1} value={zoomIndex} onChange={(e) => setZoomIndex(parseInt(e.target.value))} className="gantt-zoom-slider" aria-label={`Zoom level: ${dayWidth}px per day`} />
            <button onClick={() => setZoomIndex((i) => Math.min(i + 1, ZOOM_LEVELS.length - 1))} disabled={zoomIndex === ZOOM_LEVELS.length - 1} aria-label="Zoom in">+</button>
            {showFullscreen && (
              <button onClick={toggleFullscreen} aria-label={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'} title={isFullscreen ? 'Exit fullscreen' : 'Fullscreen'}>
                {isFullscreen ? '\u22A0' : '\u229E'}
              </button>
            )}
          </div>
        </div>
        <div className="gantt-timeline-header" ref={headerTimelineRef}>
          <div style={{ width: timelineWidth }}>
            <div className="gantt-month-header" style={{ width: timelineWidth }}>
              {months.map((m, i) => (<div key={i} className="gantt-month" style={{ width: m.days * dayWidth }}>{m.label}</div>))}
            </div>
            <div className="gantt-day-header" style={{ width: timelineWidth }}>
              {timeHeaderUnits.mode === 'weeks' ? (
                timeHeaderUnits.units.map((unit, i) => (
                  <div key={i} className={`gantt-week ${unit.hasToday ? 'has-today' : ''}`} style={{ width: unit.width }}>{unit.width > 40 ? unit.label : ''}</div>
                ))
              ) : (
                timeHeaderUnits.units.map((unit, i) => (
                  <div key={i} className={`gantt-day ${unit.isWeekend ? 'weekend' : ''} ${unit.isToday ? 'today' : ''}`} style={{ width: unit.width }}>{unit.label}</div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Scrollable body */}
      <div className="gantt-body-scroll" ref={bodyScrollRef} onScroll={handleBodyScroll}>
        <div className="gantt-info-column" ref={infoColumnRef} style={{ width: infoColumnWidth }}>
          {tasks.map((task, rowIdx) => (
            <div key={task.item.id} className={`gantt-info-row ${focusedRowIndex === rowIdx ? 'gantt-row-focused' : ''}`}>
              <div className="gantt-row-indent" style={{ width: task.depth * INDENT_WIDTH }} />
              {task.hasChildren ? (
                <button className="gantt-collapse-btn" onClick={() => toggleCollapse(task.item.id)} aria-label={collapsed.has(task.item.id) ? 'Expand' : 'Collapse'}>
                  {collapsed.has(task.item.id) ? '\u25B6' : '\u25BC'}
                </button>
              ) : (<span className="gantt-collapse-spacer" />)}
              <span className="gantt-row-title" onClick={() => handleItemClick(task.item)} title={task.item.title} style={{ cursor: 'pointer' }}>
                {task.item.title}
              </span>
              {showCategory && task.item.category && (
                <span className="gantt-category-badge" style={{ backgroundColor: categoryColors[task.item.category] || categoryColors.other || '#6b7280' }}>
                  {task.item.category}
                </span>
              )}
              {showStatus && (
                <span className={`gantt-status-badge gantt-status-${task.item.status}`}>{task.item.status.replace(/_/g, ' ')}</span>
              )}
            </div>
          ))}
        </div>

        <div className="gantt-timeline-body" style={{ width: timelineWidth, height: bodyHeight }}>
          {days.map((day, i) => (
            <div key={i} className={`gantt-grid-line ${isWeekend(day) ? 'weekend' : ''} ${mounted && isToday(day) ? 'today' : ''}`} style={{ left: i * dayWidth, width: dayWidth, height: bodyHeight }} />
          ))}
          {tasks.map((_, i) => (<div key={i} className="gantt-row-line" style={{ top: (i + 1) * ROW_HEIGHT - 1 }} />))}

          {dependencyPaths.length > 0 && (
            <svg className="gantt-deps-svg" style={{ width: timelineWidth, height: bodyHeight }} aria-hidden="true">
              {dependencyPaths.map((dep, i) => (<path key={`${dep.fromId}-${dep.toId}-${i}`} d={dep.path} className="gantt-dep-line" />))}
            </svg>
          )}

          {tasks.map((task, rowIndex) => {
            const isDragging = dragState?.taskId === task.item.id
            const pos = getBarPosition(task, rowIndex, true)
            const barColor = getHealthColor(task.healthStatus)
            const dates = isDragging ? { start: dragState!.currentStart, end: dragState!.currentEnd } : { start: task.start, end: task.end }

            return (
              <div
                key={task.item.id}
                className={`gantt-bar depth-${Math.min(task.depth, 3)} ${isDragging ? 'dragging' : ''}`}
                style={{
                  left: pos.left, width: pos.width, top: pos.top, height: pos.height,
                  backgroundColor: barColor,
                  cursor: onDateChange ? (dragState ? (dragState.type === 'move' ? 'grabbing' : 'ew-resize') : 'grab') : 'pointer',
                  opacity: task.item.status === 'completed' || task.item.status === 'closed' ? 0.7 : 0.85,
                }}
                onClick={() => !dragState && handleItemClick(task.item)}
                onMouseDown={(e) => handleDragStart(e, task, 'move')}
                title={`${task.item.title}\n${format(dates.start, 'MMM d, yyyy')} \u2013 ${format(dates.end, 'MMM d, yyyy')}\nProgress: ${task.progress}%`}
              >
                {onDateChange && (
                  <>
                    <div className="gantt-bar-handle gantt-bar-handle-left" onMouseDown={(e) => { e.stopPropagation(); handleDragStart(e, task, 'resize-start') }} />
                    <div className="gantt-bar-handle gantt-bar-handle-right" onMouseDown={(e) => { e.stopPropagation(); handleDragStart(e, task, 'resize-end') }} />
                  </>
                )}
                {task.timeProgress > 0 && task.timeProgress < 100 && (
                  <div className="gantt-bar-time-marker" style={{ left: `${task.timeProgress}%` }} />
                )}
                {task.progress > 0 && (
                  <div className={`gantt-bar-progress ${task.progress < task.timeProgress - 10 ? 'behind' : task.progress > task.timeProgress + 10 ? 'ahead' : ''}`} style={{ width: `${task.progress}%` }} />
                )}
                <span className="gantt-bar-label">{pos.width > 80 ? task.item.title.replace(/^\[[^\]]+\]\s*/, '') : ''}</span>
                {isDragging && (<div className="gantt-drag-tooltip">{format(dates.start, 'MMM d')} \u2013 {format(dates.end, 'MMM d')}</div>)}
              </div>
            )
          })}

          {mounted && (() => {
            const todayOffset = differenceInDays(new Date(), startDate)
            if (todayOffset >= 0 && todayOffset < days.length) return <div className="gantt-today-line" style={{ left: todayOffset * dayWidth + dayWidth / 2 }} />
            return null
          })()}
        </div>
      </div>

      <div className="gantt-legend">
        <div className="gantt-legend-item"><div className="gantt-legend-color" style={{ background: '#22c55e' }} /><span>On Track</span></div>
        <div className="gantt-legend-item"><div className="gantt-legend-color" style={{ background: '#eab308' }} /><span>At Risk</span></div>
        <div className="gantt-legend-item"><div className="gantt-legend-color" style={{ background: '#ef4444' }} /><span>Blocked</span></div>
        <div className="gantt-legend-item"><div className="gantt-legend-color" style={{ background: '#9ca3af' }} /><span>Not Started</span></div>
        <div className="gantt-legend-item"><div className="gantt-legend-color" style={{ background: '#3b82f6', width: 2, height: 12 }} /><span>Today</span></div>
      </div>
    </>
  )
}
