import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Grid,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Tabs,
  Tab,
  Alert,
  CircularProgress,
  LinearProgress,
  IconButton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from '@mui/material';
import {
  PlayArrow as PlayIcon,
  Refresh as RefreshIcon,
  Info as InfoIcon,
  CheckCircle as CheckIcon,
  Warning as WarningIcon,
  Error as ErrorIcon,
  CompareArrows as CompareIcon,
} from '@mui/icons-material';
import { useI18n } from '../contexts/I18nContext';
import toast from 'react-hot-toast';

interface SyncItem {
  id: string;
  source_id: string;
  target_id: string | null;
  name: string;
  status: 'new' | 'update' | 'conflict' | 'unchanged' | 'delete';
  source_data: Record<string, unknown>;
  target_data: Record<string, unknown> | null;
  diff?: Record<string, { source: unknown; target: unknown }>;
}

interface SimulationResult {
  data_type: string;
  direction: string;
  total_records: number;
  new: number;
  updated: number;
  conflicts: number;
  unchanged: number;
  deleted: number;
  items: SyncItem[];
}

const SyncSimulationPage = () => {
  const { t } = useI18n();
  const [loading, setLoading] = useState(false);
  const [simulating, setSimulating] = useState(false);
  const [dataType, setDataType] = useState('customers');
  const [direction, setDirection] = useState('sap_to_plesk');
  const [tabValue, setTabValue] = useState(0);
  const [selectedItem, setSelectedItem] = useState<SyncItem | null>(null);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [results, setResults] = useState<SimulationResult | null>(null);
  const [connectionStatus, setConnectionStatus] = useState<{ plesk: boolean; sap: boolean } | null>(null);

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

  const checkConnections = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/setup/status', { credentials: 'include' });
      if (response.ok) {
        const data = await response.json();
        setConnectionStatus({
          plesk: data.plesk_configured,
          sap: data.sap_configured,
        });
      }
    } catch {
      toast.error('Failed to check connections');
    } finally {
      setLoading(false);
    }
  };

  const runSimulation = async () => {
    if (!connectionStatus?.plesk || !connectionStatus?.sap) {
      toast.error(t('simulation.not_configured'));
      return;
    }

    setSimulating(true);
    setResults(null);

    try {
      const response = await fetch('/api/sync/simulate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          data_type: dataType,
          direction: direction,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        setResults(data);
        toast.success(t('simulation.complete'));
      } else {
        toast.error(t('simulation.error'));
      }
    } catch {
      toast.error(t('simulation.error'));
    } finally {
      setSimulating(false);
    }
  };

  const getStatusIcon = (status: string): React.ReactElement | undefined => {
    switch (status) {
      case 'new':
        return <CheckIcon fontSize="small" />;
      case 'update':
        return <CompareIcon fontSize="small" />;
      case 'conflict':
        return <WarningIcon fontSize="small" />;
      case 'unchanged':
        return <CheckIcon fontSize="small" />;
      case 'delete':
        return <ErrorIcon fontSize="small" />;
      default:
        return undefined;
    }
  };

  const getStatusColor = (status: string): 'success' | 'info' | 'warning' | 'default' | 'error' => {
    switch (status) {
      case 'new':
        return 'success';
      case 'update':
        return 'info';
      case 'conflict':
        return 'warning';
      case 'unchanged':
        return 'default';
      case 'delete':
        return 'error';
      default:
        return 'default';
    }
  };

  const getStatusLabel = (status: string): string => {
    switch (status) {
      case 'new':
        return t('simulation.status_new');
      case 'update':
        return t('simulation.status_update');
      case 'conflict':
        return t('simulation.status_conflict');
      case 'unchanged':
        return t('simulation.status_unchanged');
      case 'delete':
        return t('simulation.status_delete');
      default:
        return status;
    }
  };

  const showItemDetails = (item: SyncItem) => {
    setSelectedItem(item);
    setDetailDialogOpen(true);
  };

  const filteredItems = results?.items.filter((item) => {
    if (tabValue === 0) return true;
    if (tabValue === 1) return item.status === 'new';
    if (tabValue === 2) return item.status === 'update';
    if (tabValue === 3) return item.status === 'conflict';
    if (tabValue === 4) return item.status === 'unchanged';
    return true;
  });

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Typography variant="h4" gutterBottom sx={{ fontWeight: 700 }}>
        {t('simulation.title')}
      </Typography>
      <Typography variant="body2" color="textSecondary" sx={{ mb: 3 }}>
        {t('simulation.description')}
      </Typography>

      {(!connectionStatus?.plesk || !connectionStatus?.sap) && (
        <Alert severity="warning" sx={{ mb: 3 }}>
          {t('simulation.not_configured')}
          <Button size="small" href="/setup" sx={{ ml: 2 }}>
            {t('simulation.go_setup')}
          </Button>
        </Alert>
      )}

      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} md={3}>
              <FormControl fullWidth>
                <InputLabel>{t('simulation.data_type')}</InputLabel>
                <Select
                  value={dataType}
                  onChange={(e) => setDataType(e.target.value)}
                  label={t('simulation.data_type')}
                >
                  <MenuItem value="customers">{t('simulation.customers')}</MenuItem>
                  <MenuItem value="domains">{t('simulation.domains')}</MenuItem>
                  <MenuItem value="subscriptions">{t('simulation.subscriptions')}</MenuItem>
                  <MenuItem value="invoices">{t('simulation.invoices')}</MenuItem>
                  <MenuItem value="contacts">{t('simulation.contacts')}</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={3}>
              <FormControl fullWidth>
                <InputLabel>{t('simulation.direction')}</InputLabel>
                <Select
                  value={direction}
                  onChange={(e) => setDirection(e.target.value)}
                  label={t('simulation.direction')}
                >
                  <MenuItem value="sap_to_plesk">SAP → Plesk</MenuItem>
                  <MenuItem value="plesk_to_sap">Plesk → SAP</MenuItem>
                  <MenuItem value="bidirectional">{t('simulation.bidirectional')}</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={3}>
              <Button
                variant="contained"
                size="large"
                startIcon={simulating ? <CircularProgress size={20} /> : <PlayIcon />}
                onClick={runSimulation}
                disabled={simulating || !connectionStatus?.plesk || !connectionStatus?.sap}
                fullWidth
              >
                {simulating ? t('simulation.running') : t('simulation.run')}
              </Button>
            </Grid>
            <Grid item xs={12} md={3}>
              <Button
                variant="outlined"
                size="large"
                startIcon={<RefreshIcon />}
                onClick={checkConnections}
                disabled={loading}
                fullWidth
              >
                {t('simulation.refresh')}
              </Button>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {simulating && (
        <Box sx={{ mb: 3 }}>
          <LinearProgress />
          <Typography variant="body2" color="textSecondary" sx={{ mt: 1, textAlign: 'center' }}>
            {t('simulation.analyzing')}
          </Typography>
        </Box>
      )}

      {results && (
        <>
          <Grid container spacing={2} sx={{ mb: 3 }}>
            <Grid item xs={6} md={2}>
              <Card>
                <CardContent sx={{ textAlign: 'center' }}>
                  <Typography variant="h4" color="primary">
                    {results.total_records}
                  </Typography>
                  <Typography variant="body2" color="textSecondary">
                    {t('simulation.total')}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={6} md={2}>
              <Card>
                <CardContent sx={{ textAlign: 'center' }}>
                  <Typography variant="h4" color="success.main">
                    {results.new}
                  </Typography>
                  <Typography variant="body2" color="textSecondary">
                    {t('simulation.status_new')}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={6} md={2}>
              <Card>
                <CardContent sx={{ textAlign: 'center' }}>
                  <Typography variant="h4" color="info.main">
                    {results.updated}
                  </Typography>
                  <Typography variant="body2" color="textSecondary">
                    {t('simulation.status_update')}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={6} md={2}>
              <Card>
                <CardContent sx={{ textAlign: 'center' }}>
                  <Typography variant="h4" color="warning.main">
                    {results.conflicts}
                  </Typography>
                  <Typography variant="body2" color="textSecondary">
                    {t('simulation.status_conflict')}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={6} md={2}>
              <Card>
                <CardContent sx={{ textAlign: 'center' }}>
                  <Typography variant="h4" color="text.disabled">
                    {results.unchanged}
                  </Typography>
                  <Typography variant="body2" color="textSecondary">
                    {t('simulation.status_unchanged')}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={6} md={2}>
              <Card>
                <CardContent sx={{ textAlign: 'center' }}>
                  <Typography variant="h4" color="error.main">
                    {results.deleted}
                  </Typography>
                  <Typography variant="body2" color="textSecondary">
                    {t('simulation.status_delete')}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
          </Grid>

          <Card>
            <Tabs
              value={tabValue}
              onChange={(_, v) => setTabValue(v)}
              variant="scrollable"
              scrollButtons="auto"
            >
              <Tab label={`${t('simulation.all')} (${results.items.length})`} />
              <Tab label={`${t('simulation.status_new')} (${results.new})`} />
              <Tab label={`${t('simulation.status_update')} (${results.updated})`} />
              <Tab label={`${t('simulation.status_conflict')} (${results.conflicts})`} />
              <Tab label={`${t('simulation.status_unchanged')} (${results.unchanged})`} />
            </Tabs>

            <TableContainer component={Paper} variant="outlined">
              <Table size="medium">
                <TableHead>
                  <TableRow>
                    <TableCell>{t('simulation.col_status')}</TableCell>
                    <TableCell>{t('simulation.col_source_id')}</TableCell>
                    <TableCell>{t('simulation.col_target_id')}</TableCell>
                    <TableCell>{t('simulation.col_name')}</TableCell>
                    <TableCell>{t('simulation.col_actions')}</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {filteredItems?.map((item) => (
                    <TableRow
                      key={item.id}
                      hover
                      sx={{ cursor: 'pointer' }}
                      onClick={() => showItemDetails(item)}
                    >
                      <TableCell>
                        <Chip
                          icon={getStatusIcon(item.status)}
                          label={getStatusLabel(item.status)}
                          color={getStatusColor(item.status)}
                          size="small"
                        />
                      </TableCell>
                      <TableCell>{item.source_id}</TableCell>
                      <TableCell>{item.target_id || '-'}</TableCell>
                      <TableCell>{item.name}</TableCell>
                      <TableCell>
                        <Tooltip title={t('simulation.view_details')}>
                          <IconButton size="small">
                            <InfoIcon />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  ))}
                  {filteredItems?.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={5} align="center">
                        <Typography variant="body2" color="textSecondary" sx={{ py: 4 }}>
                          {t('simulation.no_records')}
                        </Typography>
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Card>
        </>
      )}

      <Dialog
        open={detailDialogOpen}
        onClose={() => setDetailDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          {t('simulation.details_title')}: {selectedItem?.name}
        </DialogTitle>
        <DialogContent dividers>
          {selectedItem && (
            <Grid container spacing={2}>
              <Grid item xs={12}>
                <Chip
                  icon={getStatusIcon(selectedItem.status)}
                  label={getStatusLabel(selectedItem.status)}
                  color={getStatusColor(selectedItem.status)}
                />
              </Grid>
              
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 700 }}>
                  {t('simulation.source_data')}:
                </Typography>
                <Paper variant="outlined" sx={{ p: 2, bgcolor: 'grey.50' }}>
                  <pre style={{ margin: 0, fontSize: '0.75rem', overflow: 'auto' }}>
                    {JSON.stringify(selectedItem.source_data, null, 2)}
                  </pre>
                </Paper>
              </Grid>
              
              <Grid item xs={12} md={6}>
                <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 700 }}>
                  {t('simulation.target_data')}:
                </Typography>
                <Paper variant="outlined" sx={{ p: 2, bgcolor: 'grey.50' }}>
                  {selectedItem.target_data ? (
                    <pre style={{ margin: 0, fontSize: '0.75rem', overflow: 'auto' }}>
                      {JSON.stringify(selectedItem.target_data, null, 2)}
                    </pre>
                  ) : (
                    <Typography variant="body2" color="textSecondary">
                      {t('simulation.no_target_data')}
                    </Typography>
                  )}
                </Paper>
              </Grid>
              
              {selectedItem.diff && Object.keys(selectedItem.diff).length > 0 && (
                <Grid item xs={12}>
                  <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 700 }}>
                    {t('simulation.differences')}:
                  </Typography>
                  <TableContainer component={Paper} variant="outlined">
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>{t('simulation.col_field')}</TableCell>
                          <TableCell>{t('simulation.col_source_value')}</TableCell>
                          <TableCell>{t('simulation.col_target_value')}</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {Object.entries(selectedItem.diff).map(([field, values]) => (
                          <TableRow key={field}>
                            <TableCell>{field}</TableCell>
                            <TableCell>
                              <Typography variant="body2" sx={{ fontFamily: 'monospace' }}>
                                {JSON.stringify(values.source)}
                              </Typography>
                            </TableCell>
                            <TableCell>
                              <Typography variant="body2" sx={{ fontFamily: 'monospace' }}>
                                {JSON.stringify(values.target)}
                              </Typography>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                </Grid>
              )}
            </Grid>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDetailDialogOpen(false)}>
            {t('simulation.close')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default SyncSimulationPage;
