import { Column, FormatterProps, useRowSelection } from "react-data-grid"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import type { RawData } from "../../../types"

const SELECT_COLUMN_KEY = "select-row"

function SelectFormatter(props: FormatterProps<unknown>) {
  const [isRowSelected, onRowSelectionChange] = useRowSelection()

  return (
    <div className="flex h-full items-center pl-2">
      <RadioGroup defaultValue={isRowSelected ? "selected" : undefined}>
        <div className="flex items-center space-x-2">
          <RadioGroupItem
            value="selected"
            id={`row-${props.rowIdx}`}
            checked={isRowSelected}
            onClick={(event) => {
              onRowSelectionChange({
                row: props.row,
                checked: !isRowSelected,
                isShiftClick: (event.nativeEvent as MouseEvent).shiftKey,
              })
            }}
          />
          <Label
            htmlFor={`row-${props.rowIdx}`}
            className="sr-only"
          >
            Select as header row
          </Label>
        </div>
      </RadioGroup>
    </div>
  )
}

export const SelectColumn: Column<any, any> = {
  key: SELECT_COLUMN_KEY,
  name: "Select Header",
  width: 100,
  minWidth: 100,
  maxWidth: 100,
  resizable: false,
  sortable: false,
  frozen: true,
  cellClass: "rdg-radio",
  formatter: SelectFormatter,
}

export const generateSelectionColumns = (data: RawData[]) => {
  const longestRowLength = data.reduce((acc, curr) => (acc > curr.length ? acc : curr.length), 0)
  return [
    SelectColumn,
    ...Array.from(Array(longestRowLength), (_, index) => ({
      key: index.toString(),
      name: `Column ${index + 1}`,
      width: 150,
      formatter: ({ row }: { row: RawData }) => (
        <div className="p-2 overflow-hidden text-ellipsis whitespace-nowrap">
          {row[index]}
        </div>
      ),
    })),
  ]
}
