import { useState } from 'react';
import { Box, Button, Divider, Stack, Typography } from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { DT, soft, edge } from 'themes/dt/tokens';

// Drop-in replacement for the unmaintained `mui-daterange-picker` package
// (pinned to React 17, never updated — see the React 19 upgrade plan).
// Matches its public shape: `onChange({ startDate, endDate, label })` fires
// on every selection (preset or custom), `definedRanges` renders the quick
// picks. `open`/`toggle` are accepted for API compatibility but unused —
// visibility is already gated by the parent Dialog.
export const DateRangePicker = ({ onChange, definedRanges = [] }) => {
  const [customStart, setCustomStart] = useState(null);
  const [customEnd, setCustomEnd] = useState(null);

  const pickPreset = (range) => {
    onChange({ startDate: range.startDate, endDate: range.endDate, label: range.label });
  };

  const pickCustom = (nextStart, nextEnd) => {
    if (nextStart && nextEnd) {
      onChange({ startDate: nextStart.toDate(), endDate: nextEnd.toDate(), label: undefined });
    }
  };

  return (
    <Stack spacing={2.5} sx={{ width: '100%', pb: 1 }}>
      <Stack direction="row" flexWrap="wrap" gap={1}>
        {definedRanges.map((range) => (
          <Button
            key={range.label}
            onClick={() => pickPreset(range)}
            sx={{
              borderRadius: DT.radiusPill + 'px',
              px: 2,
              py: 0.75,
              fontWeight: 700,
              fontSize: 13,
              textTransform: 'none',
              color: DT.textPrimary,
              bgcolor: soft('#f59e0b'),
              border: '1px solid',
              borderColor: edge('#f59e0b'),
              '&:hover': { bgcolor: soft('#f59e0b'), borderColor: '#f59e0b' }
            }}
          >
            {range.label}
          </Button>
        ))}
      </Stack>

      <Divider sx={{ borderColor: DT.divider }} />

      <Box>
        <Typography variant="caption" sx={{ color: DT.textSecondary, fontWeight: 700, textTransform: 'uppercase' }}>
          Custom range
        </Typography>
        <LocalizationProvider dateAdapter={AdapterDayjs}>
          <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5} sx={{ mt: 1 }}>
            <DatePicker
              label="Start date"
              value={customStart}
              onChange={(v) => {
                setCustomStart(v);
                pickCustom(v, customEnd);
              }}
              format="DD-MM-YYYY"
              slotProps={{ textField: { size: 'small', fullWidth: true } }}
            />
            <DatePicker
              label="End date"
              value={customEnd}
              minDate={customStart || undefined}
              onChange={(v) => {
                setCustomEnd(v);
                pickCustom(customStart, v);
              }}
              format="DD-MM-YYYY"
              slotProps={{ textField: { size: 'small', fullWidth: true } }}
            />
          </Stack>
        </LocalizationProvider>
      </Box>
    </Stack>
  );
};

export default DateRangePicker;
