import React, { useState } from 'react';
import { 
  Box, 
  Paper, 
  Typography, 
  Button, 
  CircularProgress 
} from '@mui/material';
import { PlayArrow } from '@mui/icons-material';
import { DataGrid, type GridColDef } from '@mui/x-data-grid';
import Editor from '@monaco-editor/react';
import { SchemaService } from '../services/api';
import { useAppStore } from '../store/useAppStore';
import type { MainNotification } from '../types/database';

interface SqlConsoleProps {
  initialQuery: string;
  setNotification: (n: MainNotification) => void;
}

const SqlConsole: React.FC<SqlConsoleProps> = ({ initialQuery, setNotification }) => {
  const { darkMode } = useAppStore();
  const [sqlQuery, setSqlQuery] = useState(initialQuery);
  const [loading, setLoading] = useState(false);
  const [rows, setRows] = useState<any[]>([]);
  const [columns, setColumns] = useState<GridColDef[]>([]);
  const [rowCount, setRowCount] = useState(0);

  const handleExecute = async () => {
    if (!sqlQuery) return;
    setLoading(true);
    try {
      const response = await SchemaService.executeQuery(sqlQuery);
      const rawData = response.data.data;
      
      if (rawData && rawData.length > 0) {
        const fields = Object.keys(rawData[0]);
        const newCols: GridColDef[] = fields.map(field => ({
          field,
          headerName: field,
          width: 150,
          flex: fields.length < 6 ? 1 : 0
        }));
        setColumns(newCols);
        
        const dataWithIds = rawData.map((row: any, index: number) => ({
          id: row.id || row.ID || `row-${index}`,
          ...row,
        }));
        setRows(dataWithIds);
        setRowCount(response.data.count);
      } else {
        setRows([]);
        setRowCount(0);
        setNotification({
          open: true,
          title: 'Query Executed',
          message: 'Query executed successfully with no results.',
          severity: 'info'
        });
      }
    } catch (error: any) {
      console.error('Execution error', error);
      const msg = error.response?.data?.error || 'An unexpected error occurred during SQL execution.';
      setNotification({
        open: true,
        title: 'SQL Execution Error',
        message: msg,
        severity: 'error'
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', gap: 2, overflow: 'hidden' }}>
      <Paper elevation={0} sx={{ 
        flexShrink: 0, 
        borderRadius: 3, 
        overflow: 'hidden', 
        border: 1, 
        borderColor: 'divider',
        bgcolor: darkMode ? '#111827' : '#ffffff',
      }}>
        <Box sx={{ px: 3, py: 1.5, display: 'flex', alignItems: 'center', justifyContent: 'space-between', bgcolor: 'rgba(0,0,0,0.02)' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <Typography variant="subtitle2" sx={{ fontWeight: 800 }}>SQL CONSOLE</Typography>
            {rowCount > 0 && (
              <Box sx={{ px: 1, py: 0.2, borderRadius: 1, bgcolor: 'rgba(0, 97, 255, 0.1)', color: 'primary.main' }}>
                <Typography variant="caption" sx={{ fontWeight: 700 }}>{rowCount} rows</Typography>
              </Box>
            )}
          </Box>
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Button 
              variant="contained" 
              size="small" 
              onClick={handleExecute}
              disabled={loading}
              startIcon={loading ? <CircularProgress size={16} color="inherit" /> : <PlayArrow />}
              sx={{ borderRadius: 2, textTransform: 'none', fontWeight: 700 }}
            >
              Execute Query
            </Button>
          </Box>
        </Box>
        <Editor
          height="200px"
          defaultLanguage="sql"
          theme={darkMode ? 'vs-dark' : 'light'}
          value={sqlQuery}
          onChange={(value) => setSqlQuery(value || '')}
          options={{ minimap: { enabled: false }, fontSize: 14, automaticLayout: true }}
        />
      </Paper>
      
      <Paper sx={{ flexGrow: 1, borderRadius: 3, overflow: 'hidden', border: 1, borderColor: 'divider' }}>
        <DataGrid
          rows={rows}
          columns={columns}
          rowCount={rowCount}
          loading={loading}
          sx={{
            border: 'none',
            '& .MuiDataGrid-row:nth-of-type(even)': {
              bgcolor: (theme) => theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.02)' : 'rgba(0,0,0,0.01)',
            },
            '& .MuiDataGrid-cell': {
              borderRight: '1px solid',
              borderColor: 'divider',
            },
            '& .MuiDataGrid-columnHeader': {
              borderRight: '1px solid',
              borderColor: 'divider',
            },
            '& .MuiDataGrid-columnHeaders': {
              borderBottom: '1px solid',
              borderColor: 'divider',
            }
          }}
        />
      </Paper>
    </Box>
  );
};

export default SqlConsole;
