"use client"

import RoadMapValidationTable from "@/shared/components/roadmap/roadmap-validation-table"
import { CustomColumn } from "@/shared/components/roadmap/types"
import { Box } from "@mui/material"

export interface ValidationTableConfig {
  trajets: {
    id: string
    label: string
  }[]
  additionalColumns?: {
    id: string
    label: string
    align?: "left" | "center" | "right"
  }[]
  dates: string[]
}

export default function ValidationTable({ tableConfig }: { tableConfig: ValidationTableConfig }) {
  const hasAdditionalColumns = tableConfig.additionalColumns && tableConfig.additionalColumns.length > 0

  const generateColumns = (): CustomColumn[] => {
    const columns: CustomColumn[] = [{ id: "date", label: "", colSpan: 1 }]

    tableConfig.trajets.forEach((trajet) => {
      columns.push({
        id: `trajet_${trajet.id}`,
        label: trajet.label,
        subColumns: [
          { id: `trajet_${trajet.id}_debut`, label: "Début", align: "center" },
          { id: `trajet_${trajet.id}_fin`, label: "Fin", align: "center" },
        ],
      },
    )
    })
    columns.push({ id: "actions", label: "", colSpan: 1})

    if (hasAdditionalColumns) {
      tableConfig.additionalColumns!.forEach((column) => {
        columns.push({
          id: column.id,
          label: column.label,
        })
      })
    }

    return columns
  }

  const generateData = () => {
    return tableConfig.dates.map((date, index) => {
      const row: any = { id: index + 1, date }

      tableConfig.trajets.forEach((trajet) => {
        row[`trajet_${trajet.id}_debut`] = {
          planned: "08:00",
          actual: "08:20",
        }
        row[`trajet_${trajet.id}_fin`] = {
          planned: "09:00",
          actual: "09:25",
        }
      })

      if (hasAdditionalColumns) {
        tableConfig.additionalColumns!.forEach((column) => {
          row[column.id] = ""
        })
      }

      return row
    })
  }

  const columns = generateColumns()
  const data = generateData()

  return (
    <Box sx={{ width: "100%" }}>
      <RoadMapValidationTable isFinalResult={hasAdditionalColumns} columns={columns} data={data} maxHeight="600px" />
    </Box>
  )
}