'use client'

import { format } from 'date-fns'
import type { GanttChartProps } from './types'
import { useGanttState } from './hooks/useGanttState'
import { GanttFilterBar } from './GanttFilterBar'
import { GanttTimelineView } from './GanttTimelineView'
import { GanttBoardView } from './GanttBoardView'
import { GanttListView } from './GanttListView'

export function GanttChart(props: GanttChartProps) {
  const {
    className,
    infoColumnLabel = 'Item',
    infoColumnWidth = 320,
    showCategory = true,
    showStatus = true,
    showFilterBar = false,
    showFullscreen = false,
    showViewSwitcher = false,
    onItemEdit,
  } = props

  const {
    isFullscreen,
    viewMode,
    setViewMode,
    detailItem,
    setDetailItem,

    uniqueStatuses,
    uniqueCategories,
    filteredItems,
    tasks,

    filters,
    setFilters,

    wrapperRef,

    handleItemClick,

    categoryColors,
    onStatusChange,

    // Timeline view props
    zoomIndex,
    setZoomIndex,
    collapsed,
    mounted,
    dragState,
    focusedRowIndex,
    dayWidth,
    startDate,
    days,
    months,
    timeHeaderUnits,
    dependencyPaths,
    timelineWidth,
    bodyHeight,
    bodyScrollRef,
    headerTimelineRef,
    infoColumnRef,
    toggleFullscreen,
    toggleCollapse,
    handleBodyScroll,
    getBarPosition,
    handleDragStart,
    onDateChange,

    // Board view props
    boardColumns,
    boardDragItem,
    setBoardDragItem,

    // List view props
    listItems,
  } = useGanttState(props)

  if (tasks.length === 0 && filteredItems.length === 0) {
    return (
      <div className={`gantt-empty ${className || ''}`}>
        <p>No items with dates to display</p>
      </div>
    )
  }

  return (
    <div ref={wrapperRef} className={`gantt-wrapper ${isFullscreen ? 'gantt-fullscreen' : ''} ${className || ''}`} tabIndex={0}>
      {/* Filter bar */}
      {showFilterBar && (
        <GanttFilterBar
          filters={filters}
          onFilterChange={(f) => setFilters(f)}
          uniqueStatuses={uniqueStatuses}
          uniqueCategories={uniqueCategories}
        />
      )}

      {/* View switcher */}
      {showViewSwitcher && (
        <div className="gantt-view-switcher">
          {(['timeline', 'board', 'list'] as const).map((mode) => (
            <button
              key={mode}
              className={`gantt-view-tab ${viewMode === mode ? 'active' : ''}`}
              onClick={() => setViewMode(mode)}
            >
              {mode === 'timeline' ? 'Timeline' : mode === 'board' ? 'Board' : 'List'}
            </button>
          ))}
        </div>
      )}

      {/* Timeline view */}
      {viewMode === 'timeline' && (
        <GanttTimelineView
          infoColumnWidth={infoColumnWidth}
          infoColumnLabel={infoColumnLabel}
          showCategory={showCategory}
          showStatus={showStatus}
          showFullscreen={showFullscreen}
          zoomIndex={zoomIndex}
          setZoomIndex={setZoomIndex}
          collapsed={collapsed}
          mounted={mounted}
          dragState={dragState}
          focusedRowIndex={focusedRowIndex}
          dayWidth={dayWidth}
          tasks={tasks}
          startDate={startDate}
          days={days}
          months={months}
          timeHeaderUnits={timeHeaderUnits}
          dependencyPaths={dependencyPaths}
          timelineWidth={timelineWidth}
          bodyHeight={bodyHeight}
          isFullscreen={isFullscreen}
          categoryColors={categoryColors}
          onDateChange={onDateChange}
          bodyScrollRef={bodyScrollRef}
          headerTimelineRef={headerTimelineRef}
          infoColumnRef={infoColumnRef}
          toggleFullscreen={toggleFullscreen}
          handleItemClick={handleItemClick}
          toggleCollapse={toggleCollapse}
          handleBodyScroll={handleBodyScroll}
          getBarPosition={getBarPosition}
          handleDragStart={handleDragStart}
        />
      )}

      {/* Board view */}
      {viewMode === 'board' && (
        <GanttBoardView
          boardColumns={boardColumns}
          boardDragItem={boardDragItem}
          setBoardDragItem={setBoardDragItem}
          onStatusChange={onStatusChange}
          categoryColors={categoryColors}
          handleItemClick={handleItemClick}
        />
      )}

      {/* List view */}
      {viewMode === 'list' && (
        <GanttListView
          listItems={listItems}
          focusedRowIndex={focusedRowIndex}
          categoryColors={categoryColors}
          handleItemClick={handleItemClick}
        />
      )}

      {/* Detail modal */}
      {detailItem && onItemEdit && (
        <div className="gantt-detail-overlay" onClick={() => setDetailItem(null)}>
          <div className="gantt-detail-modal" onClick={(e) => e.stopPropagation()}>
            <div className="gantt-detail-header">
              <h3>{detailItem.title}</h3>
              <button className="gantt-detail-close" onClick={() => setDetailItem(null)} aria-label="Close">x</button>
            </div>
            <div className="gantt-detail-body">
              {detailItem.description && (
                <div className="gantt-detail-field">
                  <label>Description</label>
                  <p>{detailItem.description}</p>
                </div>
              )}
              <div className="gantt-detail-row">
                <div className="gantt-detail-field">
                  <label>Status</label>
                  <select
                    value={detailItem.status}
                    onChange={(e) => {
                      const updated = { ...detailItem, status: e.target.value }
                      setDetailItem(updated)
                      onItemEdit(detailItem.id, { status: e.target.value })
                    }}
                    className="gantt-detail-select"
                  >
                    {uniqueStatuses.map((s) => (
                      <option key={s} value={s}>{s.replace(/_/g, ' ')}</option>
                    ))}
                  </select>
                </div>
                {detailItem.category !== undefined && (
                  <div className="gantt-detail-field">
                    <label>Category</label>
                    <select
                      value={detailItem.category || ''}
                      onChange={(e) => {
                        const updated = { ...detailItem, category: e.target.value || undefined }
                        setDetailItem(updated)
                        onItemEdit(detailItem.id, { category: e.target.value || undefined })
                      }}
                      className="gantt-detail-select"
                    >
                      <option value="">None</option>
                      {uniqueCategories.map((c) => (
                        <option key={c} value={c}>{c}</option>
                      ))}
                    </select>
                  </div>
                )}
              </div>
              <div className="gantt-detail-row">
                <div className="gantt-detail-field">
                  <label>Start Date</label>
                  <input
                    type="date"
                    className="gantt-detail-input"
                    value={detailItem.startDate ? format(new Date(detailItem.startDate), 'yyyy-MM-dd') : ''}
                    onChange={(e) => {
                      const updated = { ...detailItem, startDate: e.target.value || null }
                      setDetailItem(updated)
                      onItemEdit(detailItem.id, { startDate: e.target.value || null })
                    }}
                  />
                </div>
                <div className="gantt-detail-field">
                  <label>End Date</label>
                  <input
                    type="date"
                    className="gantt-detail-input"
                    value={detailItem.endDate ? format(new Date(detailItem.endDate), 'yyyy-MM-dd') : ''}
                    onChange={(e) => {
                      const updated = { ...detailItem, endDate: e.target.value || null }
                      setDetailItem(updated)
                      onItemEdit(detailItem.id, { endDate: e.target.value || null })
                    }}
                  />
                </div>
              </div>
              {detailItem.progress !== undefined && (
                <div className="gantt-detail-field">
                  <label>Progress: {detailItem.progress}%</label>
                  <input
                    type="range"
                    min="0"
                    max="100"
                    value={detailItem.progress}
                    onChange={(e) => {
                      const val = parseInt(e.target.value)
                      const updated = { ...detailItem, progress: val }
                      setDetailItem(updated)
                      onItemEdit(detailItem.id, { progress: val })
                    }}
                    className="gantt-detail-slider"
                  />
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
