import { useMemo } from "react"
import type { RawData } from "../../../types"
import {
  Table,
  TableBody,
  TableCell,
  TableRow,
} from "@/components/ui/table"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import { cn } from "@/lib/utils"

interface Props {
  data: RawData[]
  selectedRows: ReadonlySet<number>
  setSelectedRows: (rows: ReadonlySet<number>) => void
}

export const SelectHeaderTable = ({ data, selectedRows, setSelectedRows }: Props) => {
  const columns = useMemo(() => {
    const longestRowLength = data.reduce((acc, curr) => (acc > curr.length ? acc : curr.length), 0)
    return Array.from(Array(longestRowLength), (_, index) => ({
      key: index.toString(),
      name: `Column ${index + 1}`,
    }))
  }, [data])

  if (!data || data.length === 0) {
    return (
      <div className="p-4">
        <p className="text-sm text-muted-foreground">No data available to select headers from.</p>
      </div>
    )
  }

  const selectedRowIndex = Array.from(selectedRows)[0]
  const gridTemplateColumns = `60px repeat(${columns.length}, minmax(150px, 300px))`

  return (
    <div className="rounded-md border p-3">

      <div className="h-[calc(100vh-23rem)] overflow-auto">
        <Table className="relative w-full" style={{ tableLayout: 'fixed' }}>
          
          <TableBody>
            <RadioGroup
              value={selectedRowIndex?.toString()}
              onValueChange={(value) => setSelectedRows(new Set([parseInt(value)]))}
            >
              {data.map((row, rowIndex) => (
                <TableRow 
                  key={rowIndex}
                  className={cn(
                    "grid",
                    selectedRowIndex === rowIndex && "bg-muted font-bold",
                    "group hover:bg-muted/50"
                  )}
                  style={{ gridTemplateColumns }}
                >
                  <TableCell className="overflow-hidden">
                    <div className="flex items-center">
                      <RadioGroupItem value={rowIndex.toString()} id={`row-${rowIndex}`} />
                      <Label htmlFor={`row-${rowIndex}`} className="sr-only">
                        Select as header row
                      </Label>
                    </div>
                  </TableCell>
                  {columns.map((column, colIndex) => (
                    <TableCell 
                      key={`${rowIndex}-${column.key}`}
                      className="overflow-hidden"
                    >
                      <div className="truncate">
                        {row[colIndex] || ""}
                      </div>
                    </TableCell>
                  ))}
                </TableRow>
              ))}
            </RadioGroup>
          </TableBody>
        </Table>
      </div>
    </div>
  )
}
