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,
  IconButton,
} from '@mui/material';
import { CustomColumn, RoadMapValidationTableProps, SubColumn } from './types';
import { useState } from 'react';
import VisibilityIcon from '@mui/icons-material/Visibility';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import TrajetDetailsDialog, {
  TrajetDetailsDialogProps,
} from '@/shared/sections/chauffeur/roadmap/components/validate-roadmap/vsn-schedule-modal/trajet-details-dialog';

export default function RoadMapValidationTable({
  columns,
  data,
  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 [selectedTimes, setSelectedTimes] = useState<Record<string, string>>({});
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedRowDetails, setSelectedRowDetails] =
    useState<TrajetDetailsDialogProps['data']>(undefined);

  return (
    <>
      <StyledTableContainer
        sx={{
          maxHeight: maxHeight,
        }}
      >
        <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>
            {data.map((row, rowIndex) => (
              <RowComponent key={rowIndex}>
                {allSubColumns.map((subColumn, colIndex) => (
                  <TableCell
                    key={`${rowIndex}-${colIndex}`}
                    align={subColumn.align || 'center'}
                    sx={{ whiteSpace: 'nowrap', py: 1 }}
                  >
                    {subColumn.id === 'actions' ? (
                      <Box sx={{ display: 'flex', justifyContent: 'center', gap: 1 }}>
                        <IconButton
                          size="small"
                          color="success"
                          onClick={() => {
                            console.log('✔ Validé trajet pour ligne', row);
                          }}
                        >
                          <CheckCircleIcon fontSize="small" />
                        </IconButton>
                      </Box>
                    ) : typeof row[subColumn.id] === 'object' && row[subColumn.id] !== null ? (
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
                          <Box
                            component="button"
                            onClick={() =>
                              setSelectedTimes((prev) => ({
                                ...prev,
                                [`${rowIndex}-${subColumn.id}`]: row[subColumn.id].planned,
                              }))
                            }
                            style={{
                              backgroundColor:
                                selectedTimes[`${rowIndex}-${subColumn.id}`] ===
                                row[subColumn.id].planned
                                  ? '#1976d2'
                                  : '#c8e6c9',
                              color: '#000',
                              padding: '2px 6px',
                              borderRadius: 4,
                              border: 'none',
                              cursor: 'pointer',
                            }}
                          >
                            {row[subColumn.id].planned}
                          </Box>
                          <Box
                            component="button"
                            onClick={() =>
                              setSelectedTimes((prev) => ({
                                ...prev,
                                [`${rowIndex}-${subColumn.id}`]: row[subColumn.id].actual,
                              }))
                            }
                            style={{
                              backgroundColor:
                                selectedTimes[`${rowIndex}-${subColumn.id}`] ===
                                row[subColumn.id].actual
                                  ? '#1976d2'
                                  : '#bbdefb',
                              color: '#000',
                              padding: '2px 6px',
                              borderRadius: 4,
                              border: 'none',
                              cursor: 'pointer',
                            }}
                          >
                            {row[subColumn.id].actual}
                          </Box>
                        </Box>

                        <Box sx={{ fontWeight: 'bold' }}>
                          {selectedTimes[`${rowIndex}-${subColumn.id}`] ?? '-'}
                        </Box>
                      </Box>
                    ) : (
                      row[subColumn.id]
                    )}
                  </TableCell>
                ))}
              </RowComponent>
            ))}
          </TableBody>
        </Table>
      </StyledTableContainer>

      <TrajetDetailsDialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        data={selectedRowDetails}
      />
    </>
  );
}
