// components/ChartConfigModal.js
import React, { useState, useEffect } from 'react';
import {
  Dialog, DialogTitle, DialogContent, DialogActions,
  TextField, Checkbox, FormControlLabel, Button, MenuItem
} from '@mui/material';

const ChartConfigModal = ({ 
  open, 
  onClose, 
  config, 
  onSave, 
  columns = [] 
}) => {
  const [localConfig, setLocalConfig] = useState(config);

  useEffect(() => {
    setLocalConfig(config); // Reset on open
  }, [config]);

  const handleChange = (field, value) => {
    setLocalConfig(prev => ({ ...prev, [field]: value }));
  };

  const handleSubmit = () => {
    onSave(localConfig);
    onClose();
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>Configure Chart</DialogTitle>
      <DialogContent>
        <TextField
          label="Chart Title"
          fullWidth
          value={localConfig.title}
          onChange={e => handleChange('title', e.target.value)}
          margin="dense"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={localConfig.showLegend}
              onChange={e => handleChange('showLegend', e.target.checked)}
            />
          }
          label="Show Chart Legend"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={localConfig.showLabel}
              onChange={e => handleChange('showLabel', e.target.checked)}
            />
          }
          label="Show Chart Label"
        />
        <TextField
          label="Table Name"
          fullWidth
          value={localConfig.tableName}
          onChange={e => handleChange('tableName', e.target.value)}
          margin="dense"
        />
        <TextField
          select
          label="X-Axis"
          fullWidth
          value={localConfig.xAxis}
          onChange={e => handleChange('xAxis', e.target.value)}
          margin="dense"
        >
          {columns.map(col => (
            <MenuItem key={col} value={col}>{col}</MenuItem>
          ))}
        </TextField>
        <TextField
          select
          label="Y-Axis"
          fullWidth
          value={localConfig.yAxis}
          onChange={e => handleChange('yAxis', e.target.value)}
          margin="dense"
        >
          {columns.map(col => (
            <MenuItem key={col} value={col}>{col}</MenuItem>
          ))}
        </TextField>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button onClick={handleSubmit} variant="contained">Save</Button>
      </DialogActions>
    </Dialog>
  );
};

export default ChartConfigModal;
