import {
  HeaderCellWidthColor,
  StyledSubTableRow,
  StyledTableRow,
} from '@/shared/components/form/style';
import {
  BaseStyledRow,
  ContratStyledRow,
  TrajetStyledRow,
  WhiteStyledRow,
} from '@/shared/sections/contract/styles';
import { StyledTableContainer } from '@/shared/theme/css';
import { Table, TableHead, TableBody, TableCell, Typography, Box, TableRow } from '@mui/material';
import { CustomColumn, RowData, SubColumn } from './types';
import React from 'react';
import { ValidatedRoadMapTable, ValidatedRouteSheetDay } from '@/shared/types/roadMap';
import RoadMapValidationTableRowFinal from './roadmap-validation-table-final-row';
import dayjs from 'dayjs';
interface RoadMapValidationTableProps {
  columns: CustomColumn[];
  data: RowData[];
  validatedRoadMapTable?: ValidatedRoadMapTable;
  dates: Date[];
  maxHeight?: string;
  isFinalResult?: boolean;
}
export default function RoadMapValidationTableFinal({
  columns,
  data,
  validatedRoadMapTable,
  dates,
  maxHeight = '486px',
  isFinalResult,
}: RoadMapValidationTableProps) {
  const getColumnSpan = (column: CustomColumn) => {
    return column.subColumns?.length || column.colSpan || 1;
  };

  const createSubColumn = (
    id: string,
    label: string,
    align: 'left' | 'center' | 'right' = 'center'
  ): SubColumn => {
    return { id, label, align };
  };

  const getAllSubColumns = (): SubColumn[] => {
    const result: SubColumn[] = [];

    for (const column of columns) {
      if (column.subColumns && column.subColumns.length > 0) {
        result.push(...column.subColumns);
      } else {
        result.push(createSubColumn(column.id, column.label));
      }
    }

    return result;
  };

  const allSubColumns = getAllSubColumns();
  const RowComponent = isFinalResult ? WhiteStyledRow : TrajetStyledRow;
  const SubRowComponent = isFinalResult ? TableRow : StyledSubTableRow;
  const SupRowComponent = isFinalResult ? BaseStyledRow : StyledTableRow;
  const getFinalTableData = (date: Date): ValidatedRouteSheetDay | undefined => {
    if (!validatedRoadMapTable || !validatedRoadMapTable.dailyRoadMaps) {
      return undefined;
    }
    return validatedRoadMapTable.dailyRoadMaps.find((day) =>
      dayjs(day.date).isSame(dayjs(date), 'day')
    );
  };
  return (
    <>
      <StyledTableContainer
        sx={{
          maxHeight: maxHeight,
          '& .MuiTableHead-root .MuiTableRow-root:nth-of-type(2) .MuiTableCell-root': {
            position: 'sticky',
            top: `40px`,
            zIndex: 2,
          },
        }}
      >
        <Table stickyHeader>
          <TableHead>
            <SupRowComponent>
              {columns.map((column, colIndex) => {
                const hasSubs = column.subColumns?.length;
                return (
                  <HeaderCellWidthColor
                    key={`${column.id}-${colIndex}`}
                    align="center"
                    colSpan={hasSubs ? getColumnSpan(column) : 1}
                    rowSpan={hasSubs ? 1 : 2}
                  >
                    {column.label}
                  </HeaderCellWidthColor>
                );
              })}
            </SupRowComponent>

            {columns.some((c) => c.subColumns) ? (
              <SubRowComponent>
                {columns.flatMap(
                  (column, colIndex) =>
                    column.subColumns?.map((sub, subIndex) => (
                      <HeaderCellWidthColor
                        key={`${column.id}-${sub.id}-${colIndex}-${subIndex}`}
                        align={sub.align || 'center'}
                      >
                        {sub.label}
                      </HeaderCellWidthColor>
                    )) || []
                )}
              </SubRowComponent>
            ) : (
              <></>
            )}
          </TableHead>
          <TableBody>
            {dates.map((date, index) => (
              <RoadMapValidationTableRowFinal
                key={index}
                date={date}
                validatedRouteSheetDayRow={getFinalTableData(date)}
              />
            ))}
          </TableBody>
        </Table>
      </StyledTableContainer>
    </>
  );
}
