import React, { useMemo } from 'react';
import moment from 'moment';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import Paper from '@mui/material/Paper';
import MuiTable from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import styled from 'styled-components';
import SettingsIcon from '@mui/icons-material/Settings';
import QueryStatsIcon from '@mui/icons-material/QueryStats';

type ValueEntry = { time: string; value: string | number };
type RowValue = string | number | ValueEntry[] | null | undefined;

type ServerRow = {
  id: number | string;
  name: string;
  data: RowValue[];
  order?: number | string | null;
  type?: string | null;
  unit?: string | null;
};

type TableProps = {
  serverData?: ServerRow[];
  count: number;
};

const locale = typeof document !== 'undefined' ? document.documentElement.lang || 'de' : 'de';

const StyledTable = styled(MuiTable)`
  border-collapse: separate;
  width: 100%;
  --table-header-bg: #f7f7f7;
  --table-header-text: #333333;
  --table-row-bg: #ffffff;
  --table-row-alt-bg: #f2f4f8;
  --table-border-color: rgba(0, 0, 0, 0.12);

  th,
  td {
    white-space: nowrap;
  }

  td {
    font-size: 0.85rem;
    font-weight: 400;
    text-align: left;
  }

  th {
    font-weight: 600;
    text-transform: none;
    font-size: 0.85rem;
    color: var(--table-header-text);
    background-color: var(--table-header-bg);
    border-bottom: 1px solid var(--table-border-color);

  }
`;

const StyledTableRow = styled(TableRow)`
  &:nth-of-type(even) {
    background-color: var(--table-row-alt-bg);
  }

  &:nth-of-type(odd) {
    background-color: var(--table-row-bg);
  }

  &:last-of-type td,
  &:last-of-type th {
    border-bottom: none;
  }
`;

const NameCellWrapper = styled(Box)`
  display: flex;
  align-items: center;
  gap: 2px;
  width: 100%;

  .quick-links {
    display: flex;
    align-items: center;
    gap: 0px;
    opacity: 0;
    pointer-events: none;
    transition: opacity 150ms ease;
    flex-shrink: 0;
  }
`;

const DayHeaderCell = styled(TableCell)`
  border-right: 1px solid var(--table-border-color);
  background-color: var(--table-header-bg);
`;

const BodyCell = styled(TableCell)`
  text-align: center;
  border-bottom: 1px solid var(--table-border-color);
  background-color: inherit;
  width: 80px;
`;

const NameColumnCell = styled(BodyCell)`
  text-align: left;
  width: 1%;
  white-space: nowrap;
  background-color: inherit;

  &:hover .quick-links,
  &:focus-within .quick-links {
    opacity: 1;
    pointer-events: auto;
  }
`;

function mergeDataById(data: ServerRow[]): ServerRow[] {
  const merged: Record<string | number, ServerRow> = {};
  data.forEach((item) => {
    if (!merged[item.id]) {
      merged[item.id] = { ...item, data: Array.isArray(item.data) ? [...item.data] : [] };
    } else if (Array.isArray(item.data)) {
      item.data.forEach((value, index) => {
        // Für Arrays (mehrere Einträge pro Tag): zusammenführen
        if (Array.isArray(value) && value.length > 0) {
          const existing = merged[item.id].data[index];
          if (Array.isArray(existing)) {
            // Kombiniere und limitiere auf 3
            merged[item.id].data[index] = [...existing, ...value].slice(0, 3);
          } else {
            merged[item.id].data[index] = value;
          }
        } else if (value !== null && value !== undefined && value !== '') {
          merged[item.id].data[index] = value;
        }
      });
    }
  });

  return Object.values(merged);
}

function getDayLabel(index: number) {
  return moment()
    .subtract(index, 'days')
    .locale(locale)
    .format('MMM D');
}

const NameCell: React.FC<{ row: ServerRow }> = ({ row }) => {
  const resourceType = (row.type ?? '').toUpperCase();
  const statsType = resourceType || 'MWT';
  const configUrl = `/config/AGB${row.id}`;
  const statsUrl = `/stats?resourceType=${encodeURIComponent(statsType)}&resourceId=${encodeURIComponent(
    String(row.id)
  )}`;

  return (
    <NameCellWrapper tabIndex={0} role="group">
      <Typography component="span" fontWeight={400} noWrap>
        {row.name || '-'}
      </Typography>
      <span className="quick-links">
        <Tooltip title="Konfiguration öffnen">
          <IconButton
            component="a"
            href={configUrl}
            target="_blank"
            rel="noopener noreferrer"
            size="small"
            aria-label="Konfiguration öffnen"
            sx={{ padding: '2px' }}
          >
            <SettingsIcon sx={{ fontSize: 14 }} />
          </IconButton>
        </Tooltip>
        <Tooltip title="Stats anzeigen">
          <IconButton
            component="a"
            href={statsUrl}
            target="_blank"
            rel="noopener noreferrer"
            size="small"
            aria-label="Stats anzeigen"
            sx={{ padding: '2px' }}
          >
            <QueryStatsIcon sx={{ fontSize: 14 }} />
          </IconButton>
        </Tooltip>
      </span>
    </NameCellWrapper>
  );
};

const DayHeaders: React.FC<{ count: number }> = ({ count }) => {
  const safeCount = Math.max(count, 0);
  return (
    <TableRow>
      <DayHeaderCell key="name" component="th" scope="col">
        Name
      </DayHeaderCell>
      {Array.from({ length: safeCount }).map((_, index) => (
        <DayHeaderCell key={`day-${index}`} component="th" scope="col">
          {getDayLabel(index)}
        </DayHeaderCell>
      ))}
    </TableRow>
  );
};

const CellContent: React.FC<{ value: RowValue; unit?: string | null }> = ({ value, unit }) => {
  // Array mit mehreren Einträgen (Zeit + Wert)
  if (Array.isArray(value) && value.length > 0) {
    return (
      <Box sx={{
        display: 'flex',
        flexDirection: 'column',
        gap: value.length > 1 ? 0.5 : 0,
        py: value.length > 1 ? 0.5 : 0,
      }}>
        {value.map((entry, i) => (
          <Box
            key={i}
            sx={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'baseline',
              gap: 1,
              minWidth: 70,
            }}
          >
            <Typography
              component="span"
              sx={{
                fontSize: '0.7rem',
                color: '#888',
                flexShrink: 0,
              }}
            >
              {entry.time}
            </Typography>
            <Typography
              component="span"
              sx={{
                fontSize: '0.85rem',
                fontWeight: 500,
              }}
            >
              {entry.value}
              {unit && <span style={{ fontWeight: 400, marginLeft: 2, fontSize: '0.75rem' }}>{unit}</span>}
            </Typography>
          </Box>
        ))}
      </Box>
    );
  }
  // Leeres Array oder null/undefined
  if (Array.isArray(value) && value.length === 0) {
    return <></>;
  }
  // Einzelner Wert (Fallback für alte Daten)
  return <>{String(value ?? '')}</>;
};

const DataRows: React.FC<{ rows: ServerRow[]; count: number }> = ({ rows, count }) => {
  const safeCount = Math.max(count, 0);
  return (
    <>
      {rows.map((row) => {
        const dataset = Array.isArray(row.data) ? row.data : [];
        const values = Array.from({ length: safeCount }).map((_, index) => dataset[index] ?? []);
        return (
          <StyledTableRow key={row.id}>
            <NameColumnCell component="th" scope="row">
              <NameCell row={row} />
            </NameColumnCell>
            {values.map((value, index) => (
              <BodyCell key={`${row.id}-${index}`}>
                <CellContent value={value} unit={row.unit} />
              </BodyCell>
            ))}
          </StyledTableRow>
        );
      })}
    </>
  );
};

const Table: React.FC<TableProps> = ({ serverData, count }) => {
  const mergedRows = useMemo(() => mergeDataById(serverData ?? []), [serverData]);
  const sortedRows = useMemo(
    () =>
      mergedRows.slice().sort((a, b) => {
        const posA = parseInt(String(a.order ?? 0), 10) || 0;
        const posB = parseInt(String(b.order ?? 0), 10) || 0;
        return posA - posB;
      }),
    [mergedRows]
  );

  if (!sortedRows.length) {
    return null;
  }

  const safeCount = Math.max(count, 0);

  return (
    <TableContainer component={Paper} elevation={2} sx={{ borderRadius: 2, overflowX: 'scroll', maxHeight: '100%' }}>
      <StyledTable size="small" stickyHeader>
        <TableHead>
          <DayHeaders count={safeCount} />
        </TableHead>
        <TableBody>
          <DataRows rows={sortedRows} count={safeCount} />
        </TableBody>
      </StyledTable>
    </TableContainer>
  );
};

export default Table;
