import * as React from 'react'

import { Calendar } from '@components/ui/calendar/calendar'
import { DataGridCellWrapper } from '@components/ui/data-grid/data-grid-cell-wrapper'
import { Popover, PopoverAnchor, PopoverContent } from '@components/ui/popover/popover'
import { cn } from '@lib/utils'

import { CellVariantProps } from './cell-variant-types'

/**
 * Parse a date value (Date object or ISO string YYYY-MM-DD) as a local date, not UTC.
 * new Date('2025-12-01') interprets as UTC, causing timezone shifts.
 */
function parseToLocalDate(value: string | Date | null | undefined): Date | undefined {
  if (!value) {
    return undefined
  }
  if (value instanceof Date) {
    return value
  }
  if (typeof value !== 'string') {
    return undefined
  }

  // Parse ISO date string in local timezone by explicitly setting year, month, day
  const regex = /^(\d{4})-(\d{2})-(\d{2})$/
  const match = regex.exec(value)
  if (!match) {
    return undefined
  }

  const year = Number.parseInt(match[1], 10)
  const month = Number.parseInt(match[2], 10) - 1 // months are 0-indexed
  const day = Number.parseInt(match[3], 10)

  return new Date(year, month, day)
}

function formatDateToISOString(date: Date): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

export function DateCell<TData>({
  cell,
  table,
  rowIndex,
  columnId,
  isFocused,
  isEditing,
  isSelected,
}: Readonly<CellVariantProps<TData, string>>) {
  const initialValue = cell.getValue() as string | Date | null | undefined
  const [value, setValue] = React.useState<Date | undefined>(parseToLocalDate(initialValue))
  const [open, setOpen] = React.useState(false)
  const containerRef = React.useRef<HTMLDivElement>(null)
  const meta = table.options.meta

  const prevInitialValueRef = React.useRef(initialValue)
  if (initialValue !== prevInitialValueRef.current) {
    prevInitialValueRef.current = initialValue
    setValue(parseToLocalDate(initialValue))
  }

  const onDateSelect = React.useCallback(
    (date: Date | undefined) => {
      if (!date) {
        return
      }

      setValue(date)
      meta?.onDataUpdate?.({ rowIndex, columnId, value: formatDateToISOString(date) })
      setOpen(false)
      meta?.onCellEditingStop?.()
    },
    [meta, rowIndex, columnId],
  )

  const onOpenChange = React.useCallback(
    (isOpen: boolean) => {
      setOpen(isOpen)
      if (!isOpen && isEditing) {
        meta?.onCellEditingStop?.()
      }
    },
    [isEditing, meta],
  )

  const onWrapperKeyDown = React.useCallback(
    (event: React.KeyboardEvent<HTMLDivElement>) => {
      if (isEditing) {
        if (event.key === 'Escape') {
          event.preventDefault()
          setValue(parseToLocalDate(initialValue))
          setOpen(false)
        } else if (event.key === 'Tab') {
          event.preventDefault()
          setOpen(false)
          meta?.onCellEditingStop?.({
            direction: event.shiftKey ? 'left' : 'right',
          })
        }
      }
    },
    [isEditing, initialValue, meta],
  )

  React.useEffect(() => {
    setOpen(isEditing)
  }, [isEditing])

  React.useEffect(() => {
    if (isFocused && !isEditing && !meta?.searchOpen && !meta?.isScrolling && containerRef.current) {
      containerRef.current.focus()
    }
  }, [isFocused, isEditing, meta?.searchOpen, meta?.isScrolling])

  return (
    <DataGridCellWrapper
      ref={containerRef}
      cell={cell}
      table={table}
      rowIndex={rowIndex}
      columnId={columnId}
      isEditing={isEditing}
      isFocused={isFocused}
      isSelected={isSelected}
      onKeyDown={onWrapperKeyDown}
    >
      <Popover open={open} onOpenChange={onOpenChange}>
        <PopoverAnchor asChild>
          <span
            data-slot="grid-cell-content"
            className={cn('tabular-nums', (cell.column.columnDef.meta as any)?.align ?? 'text-right')}
          >
            {value?.toLocaleDateString() ?? ''}
          </span>
        </PopoverAnchor>
        {isEditing && (
          <PopoverContent data-grid-cell-editor="" align="start" sideOffset={10} className="w-auto p-0">
            <Calendar
              showYearNavigation={true}
              autoFocus
              captionLayout="dropdown"
              mode="single"
              className="rounded-md border border-neutral-200 shadow-sm dark:border-neutral-800"
              defaultMonth={value}
              selected={value}
              onSelect={onDateSelect}
            />
          </PopoverContent>
        )}
      </Popover>
    </DataGridCellWrapper>
  )
}
