import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Paper,
  Typography,
  Button,
  CircularProgress,
  Alert,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableRow,
  Avatar
} from '@mui/material';
import {
  Terminal,
  TableChart,
  CleaningServices,
  Save,
  History,
  Info
} from '@mui/icons-material';
import { SchemaService } from '../services/api';
import ConfirmDialog from './ConfirmDialog';
import type { MainNotification } from '../types/database';

interface TechnicalOverviewProps {
  database: string;
  table: string | null;
  setNotification: (n: MainNotification) => void;
}

const TechnicalOverview: React.FC<TechnicalOverviewProps> = ({ database, table, setNotification }) => {
  const [meta, setMeta] = useState<any>(null);
  const [loadingMeta, setLoadingMeta] = useState(true);
  const [truncating, setTruncating] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);

  const fetchMeta = useCallback(async () => {
    setLoadingMeta(true);
    try {
      const res = table
        ? await SchemaService.getTableMetadata(database, table)
        : await SchemaService.getDatabaseMetadata(database);
      setMeta(res.data);
    } catch (e) {
      console.error(e);
    } finally {
      setLoadingMeta(false);
    }
  }, [database, table]);

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

  const handleTruncate = async () => {
    setTruncating(true);
    setShowConfirm(false);
    try {
      await SchemaService.truncateTable(table!);
      setNotification({
        open: true,
        title: 'Success',
        message: `Table "${table}" has been truncated.`,
        severity: 'success'
      });
      fetchMeta();
    } catch (error: any) {
      setNotification({
        open: true,
        title: 'Truncate Error',
        message: error.response?.data?.error || error.message,
        severity: 'error'
      });
    } finally {
      setTruncating(false);
    }
  };

  if (loadingMeta) return <Box sx={{ display: 'flex', justifyContent: 'center', p: 8 }}><CircularProgress /></Box>;
  if (!meta) return <Alert severity="error">Could not load metadata</Alert>;

  const stats = table ? [
    { label: 'Engine', value: meta.engine, icon: <Terminal /> },
    { label: 'Rows', value: meta.rows, icon: <TableChart /> },
    { label: 'Collation', value: meta.collation, icon: <CleaningServices /> },
    { label: 'Data Size', value: `${(meta.data_length / 1024 / 1024).toFixed(2)} MB`, icon: <Save /> },
    { label: 'Index Size', value: `${(meta.index_length / 1024 / 1024).toFixed(2)} MB`, icon: <History /> },
    { label: 'Created', value: meta.create_time, icon: <Info /> },
  ] : [
    { label: 'Character Set', value: meta.charset, icon: <History /> },
    { label: 'Collation', value: meta.collation, icon: <CleaningServices /> },
    { label: 'Tables', value: meta.table_count, icon: <TableChart /> },
    { label: 'Views', value: meta.view_count, icon: <History /> },
    { label: 'Total Size', value: `${(meta.size_bytes / 1024 / 1024).toFixed(2)} MB`, icon: <Save /> },
  ];

  return (
    <Box sx={{ p: 1 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
        <Typography variant="h5" sx={{ fontWeight: 800, letterSpacing: -0.5 }}>
          Technical Specifications: {table ? `${database}.${table}` : database}
        </Typography>
        {table && (
          <Button
            variant="outlined"
            color="error"
            startIcon={truncating ? <CircularProgress size={16} color="inherit" /> : <CleaningServices />}
            onClick={() => setShowConfirm(true)}
            disabled={truncating}
            sx={{ borderRadius: 2, textTransform: 'none', fontWeight: 700 }}
          >
            Truncate Table
          </Button>
        )}
      </Box>

      <ConfirmDialog
        open={showConfirm}
        onClose={() => setShowConfirm(false)}
        onConfirm={handleTruncate}
        title="Truncate Table"
        message={`Are you sure you want to truncate table "${table}"? This action will permanently delete all ${meta?.rows || ''} records. This cannot be undone.`}
        confirmLabel="Truncate Now"
        loading={truncating}
      />
      <TableContainer component={Paper} sx={{
        borderRadius: 1,
        border: 1,
        borderColor: 'divider',
        bgcolor: 'background.paper',
        overflow: 'hidden',
        boxShadow: 'none'
      }}>
        <Table>
          <TableBody>
            {stats.map((stat, i) => (
              <TableRow key={i} sx={{ '&:last-child td, &:last-child th': { border: 0 }, '&:hover': { bgcolor: 'rgba(255,255,255,0.02)' } }}>
                <TableCell sx={{ width: 64 }}>
                  <Avatar sx={{
                    bgcolor: 'rgba(0,123,255,0.1)',
                    color: 'primary.main',
                    width: 40,
                    height: 40
                  }}>
                    {stat.icon}
                  </Avatar>
                </TableCell>
                <TableCell sx={{ fontWeight: 700, color: 'text.secondary', textTransform: 'uppercase', letterSpacing: 1, fontSize: '0.75rem' }}>
                  {stat.label}
                </TableCell>
                <TableCell align="right" sx={{ fontWeight: 800, fontSize: '1.1rem' }}>
                  {stat.value || 'N/A'}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
    </Box>
  );
};

export default TechnicalOverview;
