import { useState } from 'react';
import {
  Box,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  Paper,
  Alert,
  Divider,
} from '@mui/material';

export const ScheduleBuilderDialog: React.FC<{
  open: boolean;
  onClose: () => void;
  onSave: (schedule: { type: string; config: Record<string, unknown> }) => void;
}> = ({ open, onClose, onSave }) => {
  const [scheduleType, setScheduleType] = useState<'daily' | 'weekly' | 'monthly' | 'custom'>('daily');
  const [config, setConfig] = useState({
    hour: 2,
    weekday: 0,
    day: 1,
  });

  const scheduleTypes = [
    { value: 'daily', label: 'Daily', description: 'Run every day at a specific time' },
    { value: 'weekly', label: 'Weekly', description: 'Run every week on a specific day' },
    { value: 'monthly', label: 'Monthly', description: 'Run every month on a specific day' },
    { value: 'custom', label: 'Custom', description: 'Define your own schedule (cron expression)' },
  ];

  const handleSave = () => {
    const scheduleConfig: Record<string, unknown> = { type: scheduleType };
    
    if (scheduleType !== 'custom') {
      scheduleConfig.hour = config.hour;
      if (scheduleType === 'weekly') {
        scheduleConfig.weekday = config.weekday;
        scheduleConfig.dayName = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][config.weekday];
      }
      if (scheduleType === 'monthly') {
        scheduleConfig.day = config.day;
      }
    }

    onSave({ type: scheduleType, config: scheduleConfig });
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>Create Scheduled Sync</DialogTitle>
      <DialogContent>
        <Box sx={{ mt: 2 }}>
          <Typography variant="subtitle2" gutterBottom>Select Schedule Type</Typography>
          
          <Grid container spacing={1} sx={{ mb: 3 }}>
            {scheduleTypes.map((type) => (
              <Grid item xs={12} sm={6} key={type.value}>
                <Paper
                  onClick={() => setScheduleType(type.value as 'daily' | 'weekly' | 'monthly' | 'custom')}
                  sx={{
                    p: 2,
                    cursor: 'pointer',
                    border: scheduleType === type.value ? '2px solid' : '1px solid',
                    borderColor: scheduleType === type.value ? 'primary.main' : 'grey.300',
                    transition: 'all 0.2s',
                  }}
                >
                  <Typography variant="subtitle2" fontWeight={600}>
                    {type.label}
                  </Typography>
                  <Typography variant="caption" color="textSecondary">
                    {type.description}
                  </Typography>
                </Paper>
              </Grid>
            ))}
          </Grid>

          {scheduleType !== 'custom' && (
            <Box>
              <Typography variant="subtitle2" gutterBottom>Schedule Configuration</Typography>
              
              <Box sx={{ mb: 2 }}>
                <Typography variant="caption" gutterBottom>What time should the sync run?</Typography>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Typography variant="subtitle1">
                    At {config.hour.toString().padStart(2, '0')}:00
                  </Typography>
                  <input
                    type="range"
                    min="0"
                    max="23"
                    value={config.hour}
                    onChange={(e) => setConfig({ ...config, hour: parseInt(e.target.value) })}
                    style={{ flex: 1 }}
                  />
                </Box>
              </Box>

              {scheduleType === 'weekly' && (
                <Box sx={{ mb: 2 }}>
                  <Typography variant="caption" gutterBottom>Which day of the week?</Typography>
                  <Grid container spacing={1}>
                    {['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'].map((day, index) => (
                      <Grid item xs={6} sm={3} key={day}>
                        <Button
                          variant={config.weekday === index ? 'contained' : 'outlined'}
                          fullWidth
                          size="small"
                          onClick={() => setConfig({ ...config, weekday: index })}
                        >
                          {day}
                        </Button>
                      </Grid>
                    ))}
                  </Grid>
                </Box>
              )}

              {scheduleType === 'monthly' && (
                <Box sx={{ mb: 2 }}>
                  <Typography variant="caption" gutterBottom>Which day of the month?</Typography>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Typography variant="subtitle1">
                      On day {config.day}
                    </Typography>
                    <input
                      type="range"
                      min="1"
                      max="31"
                      value={config.day}
                      onChange={(e) => setConfig({ ...config, day: parseInt(e.target.value) })}
                      style={{ flex: 1 }}
                    />
                  </Box>
                </Box>
              )}

              <Divider sx={{ my: 2 }} />

              <Typography variant="body2" color="textSecondary">
                <strong>Schedule Summary:</strong>
              </Typography>
              <Alert severity="info" sx={{ mt: 1 }}>
                Run {scheduleType === 'daily' && 'daily'}
                {scheduleType === 'weekly' && `every ${['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][config.weekday]}`}
                {scheduleType === 'monthly' && `on day ${config.day} of each month`}
                {' '}at {config.hour.toString().padStart(2, '0')}:00
              </Alert>
            </Box>
          )}

          {scheduleType === 'custom' && (
            <Alert severity="warning">
              Custom schedules (cron expressions) are not yet supported. Please use the predefined schedule types.
            </Alert>
          )}
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button variant="contained" onClick={handleSave} disabled={scheduleType === 'custom'}>
          Create Schedule
        </Button>
      </DialogActions>
    </Dialog>
  );
};

// This component integrates into the existing SyncPage
export const ScheduleBuilder = () => {
  return (
    <Box sx={{ p: 2, bgcolor: '#f5f5f5', borderRadius: 1 }}>
      <Typography variant="subtitle2" gutterBottom>
        Scheduled Syncs
      </Typography>
      <Typography variant="caption" color="textSecondary">
        Create automated sync schedules
      </Typography>
    </Box>
  );
};
