'use client';
import * as React from 'react';
import { Grid, Button } from '@mui/material';

const LABELS = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'];
const VIEW_TO_INDEX = [1, 2, 3, 4, 5, 6, 0];
const CANONICAL_ORDER = [0, 1, 2, 3, 4, 5, 6];

type Props = {
  value?: number[];
  onChange: (days: number[]) => void;
  disabled?: boolean;
};

export default function DaySelector({ value = [], onChange, disabled }: Props) {
  const selected = new Set(value);

  const toggleByViewPos = (pos: number) => {
    const dayIndex = VIEW_TO_INDEX[pos];
    const next = new Set(selected);
    next.has(dayIndex) ? next.delete(dayIndex) : next.add(dayIndex);
    onChange(CANONICAL_ORDER.filter((d) => next.has(d)));
  };

  return (
    <Grid container spacing={1}>
      {LABELS.map((label, pos) => {
        const dayIndex = VIEW_TO_INDEX[pos];
        const active = selected.has(dayIndex);

        return (
          <Grid item xs={12 / 4} sm={12 / 4} md={12 / 4} key={label}>
            <Button
              fullWidth
              size="small"
              disableElevation
              variant="contained"
              disabled={disabled}
              onClick={() => !disabled && toggleByViewPos(pos)}
              sx={{
                borderRadius: 1,
                textTransform: 'none',
                bgcolor: active ? 'grey.400' : 'grey.200',
                color: 'text.primary',
                '&:hover': {
                  bgcolor: active ? 'grey.500' : 'grey.300',
                },
                py: 0.7,
              }}
            >
              {label}
            </Button>
          </Grid>
        );
      })}
    </Grid>
  );
}
