import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Paper,
  Typography,
  Button,
  Stack,
  Checkbox
} from '@mui/material';
import {
  TableChart,
  CleaningServices,
  Close,
  Save
} from '@mui/icons-material';
import { DataGrid, type GridColDef } from '@mui/x-data-grid';
import { SchemaService } from '../services/api';
import { useAppStore } from '../store/useAppStore';
import type { MainNotification } from '../types/database';

interface DatabaseTablesGridProps {
  database: string;
  setNotification: (n: MainNotification) => void;
}

const DatabaseTablesGrid: React.FC<DatabaseTablesGridProps> = ({ database, setNotification }) => {
  const [tableRows, setTableRows] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectionModel, setSelectionModel] = useState<string[]>([]);
  const { setActiveTable } = useAppStore();

  const fetchTablesMeta = useCallback(async () => {
    setLoading(true);
    try {
      const res = await SchemaService.getTablesMetadata(database);
      setTableRows(res.data);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, [database]);

  useEffect(() => {
    fetchTablesMeta();
  }, [fetchTablesMeta]);

  const handleBulkAction = async (action: 'truncate' | 'drop' | 'optimize') => {
    if (selectionModel.length === 0) return;

    const confirmMsg = `Are you sure you want to ${action} ${selectionModel.length} selected tables? This action is irreversible!`;
    if (!window.confirm(confirmMsg)) return;

    setLoading(true);
    try {
      await SchemaService.bulkAction({
        tables: selectionModel,
        action,
        database
      });
      setNotification({
        open: true,
        title: 'Bulk Action Success',
        message: `Successfully performed ${action} on ${selectionModel.length} tables.`,
        severity: 'success'
      });
      fetchTablesMeta();
      setSelectionModel([]);
    } catch (error: any) {
      setNotification({
        open: true,
        title: 'Bulk Action Error',
        message: error.response?.data?.error || error.message,
        severity: 'error'
      });
    } finally {
      setLoading(false);
    }
  };

  const toggleRow = (name: string) => {
    setSelectionModel(prev =>
      prev.includes(name) ? prev.filter(n => n !== name) : [...prev, name]
    );
  };

  const toggleAll = () => {
    if (selectionModel.length === tableRows.length) {
      setSelectionModel([]);
    } else {
      setSelectionModel(tableRows.map(r => r.name));
    }
  };

  const columns: GridColDef[] = [
    {
      field: '__check__',
      headerName: '',
      width: 50,
      sortable: false,
      filterable: false,
      renderHeader: () => (
        <Checkbox
          size="small"
          indeterminate={selectionModel.length > 0 && selectionModel.length < tableRows.length}
          checked={tableRows.length > 0 && selectionModel.length === tableRows.length}
          onChange={toggleAll}
        />
      ),
      renderCell: (params) => (
        <Checkbox
          size="small"
          checked={selectionModel.includes(params.row.name)}
          onChange={(e) => {
            e.stopPropagation();
            toggleRow(params.row.name);
          }}
        />
      )
    },
    {
      field: 'name',
      headerName: 'Table Name',
      flex: 1,
      minWidth: 200,
      renderCell: (params) => (
        <Button
          size="small"
          startIcon={<TableChart fontSize="small" />}
          onClick={() => setActiveTable(params.value)}
          sx={{ textTransform: 'none', fontWeight: 600, color: '#ffc107', '&:hover': { color: '#ffca28' } }}
        >
          {params.value}
        </Button>
      )
    },
    { field: 'engine', headerName: 'Engine', width: 120 },
    { field: 'rows', headerName: 'Rows', type: 'number', width: 120 },
    {
      field: 'data_length',
      headerName: 'Data Size',
      width: 130,
      valueFormatter: (value) => `${(Number(value) / 1024 / 1024).toFixed(2)} MB`
    },
    {
      field: 'index_length',
      headerName: 'Index Size',
      width: 130,
      valueFormatter: (value) => `${(Number(value) / 1024 / 1024).toFixed(2)} MB`
    },
    { field: 'collation', headerName: 'Collation', width: 180 },
    { field: 'comment', headerName: 'Comment', flex: 1, minWidth: 150 },
  ];

  return (
    <Box sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', gap: 2 }}>
      {selectionModel.length > 0 && (
        <Paper sx={{ p: 1.5, borderRadius: 2, display: 'flex', alignItems: 'center', gap: 2, bgcolor: 'rgba(255, 193, 7, 0.05)', border: '1px dashed #ffc107' }}>
          <Typography variant="body2" sx={{ fontWeight: 700, color: '#ffc107' }}>
            {selectionModel.length} tables selected:
          </Typography>
          <Stack direction="row" spacing={1}>
            <Button size="small" color="warning" variant="outlined" startIcon={<CleaningServices />} onClick={() => handleBulkAction('truncate')}>Truncate</Button>
            <Button size="small" color="error" variant="outlined" startIcon={<Close />} onClick={() => handleBulkAction('drop')}>Drop</Button>
            <Button size="small" color="info" variant="outlined" startIcon={<Save />} onClick={() => handleBulkAction('optimize')}>Optimize</Button>
          </Stack>
          <Box sx={{ flexGrow: 1 }} />
          <Button size="small" onClick={() => setSelectionModel([])}>Clear Selection</Button>
        </Paper>
      )}
      <Paper sx={{
        flexGrow: 1,
        borderRadius: 1,
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column',
        border: 1,
        borderColor: 'divider',
        boxShadow: '0 4px 12px rgba(0,0,0,0.05)'
      }}>
        <DataGrid
          rows={tableRows}
          columns={columns}
          loading={loading}
          getRowId={(row: any) => row.name}
          density="comfortable"
          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 DatabaseTablesGrid;
