import { useState } from 'react';
import { Button, Box, Paper } from '@mui/material';
import { Download, Upload } from '@mui/icons-material';
import { exportAllData, importDummyData } from '../services/storageService';

function DebugPanel() {
  const [dummyMode, setDummyMode] = useState(false);

  const handleExport = () => {
    const data = exportAllData();
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `claudash-debug-${new Date().toISOString()}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleImport = (event) => {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target.result);
        importDummyData(data);
        setDummyMode(true);
        window.location.reload();
      } catch (error) {
        console.error('Error importing data:', error);
        alert('Failed to import data. Please check the file format.');
      }
    };
    reader.readAsText(file);
  };

  return (
    <Paper sx={{ position: 'fixed', bottom: 80, right: 16, p: 2, width: 250, zIndex: 999 }}>
      <h3 className="debug-title">Debug Tools</h3>

      <Button
        fullWidth
        startIcon={<Download />}
        onClick={handleExport}
        sx={{ mb: 1 }}
        variant="outlined"
      >
        Export Data
      </Button>

      <Button
        fullWidth
        component="label"
        startIcon={<Upload />}
        variant="outlined"
      >
        Import Dummy Data
        <input
          type="file"
          hidden
          accept=".json"
          onChange={handleImport}
        />
      </Button>

      {dummyMode && (
        <span className="debug-warning">Using dummy data</span>
      )}
    </Paper>
  );
}

export default DebugPanel;