import type { Cell, Table } from '@tanstack/react-table'

import * as React from 'react'

import { DataGridCellWrapper } from '@components/ui/data-grid/data-grid-cell-wrapper'
import { cn } from '@lib/utils'

export type GanttCellProps<TData> = {
  cell: Cell<TData, { start: Date; end: Date; barClassName?: string } | null>
  table: Table<TData>
  rowIndex: number
  columnId: string
  isEditing: boolean
  isFocused: boolean
  isSelected: boolean
}

export function GanttCell<TData>({
  cell,
  table,
  rowIndex,
  columnId,
  isFocused,
  isEditing,
  isSelected,
}: Readonly<GanttCellProps<TData>>) {
  const initialValue = cell.getValue() as { start: Date; end: Date; barClassName?: string } | null
  const containerRef = React.useRef<HTMLDivElement>(null)
  const cellOpts = (cell.column.columnDef.meta as any)?.cell

  const ts = cellOpts?.dateRangeFrom ?? cellOpts?.timelineStart
  const te = cellOpts?.dateRangeTo ?? cellOpts?.timelineEnd

  const timelineStartMs = ts instanceof Date ? ts.getTime() : undefined
  const timelineEndMs = te instanceof Date ? te.getTime() : undefined

  if (!timelineStartMs || !timelineEndMs) {
    return null
  }

  const timelineDurationMs = timelineEndMs - timelineStartMs
  const msUntilStart = initialValue ? initialValue.start.getTime() - timelineStartMs : 0
  // end - start time considering timeline bounds
  const barWidthMs = initialValue
    ? Math.min(initialValue.end.getTime(), timelineEndMs) - Math.max(initialValue.start.getTime(), timelineStartMs)
    : 0

  return (
    <DataGridCellWrapper
      ref={containerRef}
      cell={cell}
      table={table}
      rowIndex={rowIndex}
      columnId={columnId}
      isEditing={isEditing}
      isFocused={isFocused}
      isSelected={isSelected}
      className="px-1"
    >
      <div className="size-full flex overflow-hidden">
        {initialValue && (
          <>
            <div
              className="shrink-0"
              style={{
                width: `${Math.max(0, (msUntilStart / timelineDurationMs) * 100)}%`,
              }}
            />
            <div
              className={cn('shrink-0 h-full rounded-sm bg-primary', initialValue.barClassName)}
              style={{
                width: `${(barWidthMs / timelineDurationMs) * 100}%`,
              }}
            />
          </>
        )}
      </div>
    </DataGridCellWrapper>
  )
}
