import { useState, useCallback } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Grid,
  Chip,
  CircularProgress,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from '@mui/material';
import {
  PlayArrow as PlayIcon,
  Stop as StopIcon,
  Refresh as RefreshIcon,
} from '@mui/icons-material';
import toast from 'react-hot-toast';
import { apiJson } from '../lib/api';
import { usePolling, getStatusColor, formatDate } from '../lib/hooks';
import { logger } from '../lib/logger';
import { useI18n } from '../contexts/I18nContext';

interface SyncJob {
  id: number;
  job_type: string;
  sync_direction: string;
  status: string;
  records_processed: number;
  records_failed: number;
  created_at: string;
  started_at: string | null;
  completed_at: string | null;
  error_message: string | null;
}

const SyncPage = () => {
  const { t } = useI18n();
  const [jobs, setJobs] = useState<SyncJob[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  const [loading, setLoading] = useState(true);
  const [syncDialogOpen, setSyncDialogOpen] = useState(false);
  const [syncDirection, setSyncDirection] = useState('sap_to_plesk');
  const [syncType, setSyncType] = useState('incremental_sync');

  const fetchJobs = useCallback(async () => {
    try {
      const data = await apiJson<{ jobs: SyncJob[] }>('/sync/jobs');
      setJobs(data.jobs || []);
      setIsRunning(data.jobs?.some((job: SyncJob) => job.status === 'running') || false);
    } catch (error) {
      logger.error('Failed to fetch jobs:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  usePolling(fetchJobs, 10000);

  const startSync = async () => {
    try {
      await apiJson('/sync/start', {
        method: 'POST',
        body: JSON.stringify({
          job_type: syncType,
          sync_direction: syncDirection,
        }),
      });
      toast.success(t('sync.startedSuccess'));
      setSyncDialogOpen(false);
      fetchJobs();
    } catch (error: unknown) {
      toast.error(error instanceof Error ? error.message : t('sync.startFailed'));
    }
  };

  const stopSync = async () => {
    try {
      await apiJson('/sync/stop', { method: 'POST' });
      toast.success(t('sync.stoppedSuccess'));
      fetchJobs();
    } catch (error: unknown) {
      toast.error(error instanceof Error ? error.message : t('sync.stopFailed'));
    }
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="60vh">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Typography variant="h4" gutterBottom>
        {t('sync.title')}
      </Typography>

      <Grid container spacing={3}>
        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Box display="flex" alignItems="center" justifyContent="space-between">
                <Box display="flex" alignItems="center">
                  {isRunning && (
                    <Box display="flex" alignItems="center" mr={2}>
                      <CircularProgress size={20} sx={{ mr: 1 }} />
                      <Typography>{t('sync.running')}</Typography>
                    </Box>
                  )}
                  <Chip
                    label={isRunning ? t('sync.running') : t('sync.idle')}
                    color={isRunning ? 'primary' : 'default'}
                  />
                </Box>
                <Box>
                  <Button
                    variant="contained"
                    color="primary"
                    startIcon={<PlayIcon />}
                    onClick={() => setSyncDialogOpen(true)}
                    disabled={isRunning}
                    sx={{ mr: 1 }}
                  >
                    {t('sync.startSync')}
                  </Button>
                  <Button
                    variant="contained"
                    color="error"
                    startIcon={<StopIcon />}
                    onClick={stopSync}
                    disabled={!isRunning}
                    sx={{ mr: 1 }}
                  >
                    {t('sync.stopSync')}
                  </Button>
                  <Button
                    variant="outlined"
                    startIcon={<RefreshIcon />}
                    onClick={fetchJobs}
                  >
                    {t('common.refresh')}
                  </Button>
                </Box>
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t('sync.syncJobs')}
              </Typography>
              <TableContainer component={Paper}>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>{t('sync.colId')}</TableCell>
                      <TableCell>{t('sync.colType')}</TableCell>
                      <TableCell>{t('sync.colDirection')}</TableCell>
                      <TableCell>{t('sync.colStatus')}</TableCell>
                      <TableCell>{t('sync.colProcessed')}</TableCell>
                      <TableCell>{t('sync.colFailed')}</TableCell>
                      <TableCell>{t('sync.colStarted')}</TableCell>
                      <TableCell>{t('sync.colCompleted')}</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {jobs.map((job) => (
                      <TableRow key={job.id}>
                        <TableCell>{job.id}</TableCell>
                        <TableCell>{job.job_type}</TableCell>
                        <TableCell>{job.sync_direction}</TableCell>
                        <TableCell>
                          <Chip
                            label={job.status}
                            color={getStatusColor(job.status)}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>{job.records_processed}</TableCell>
                        <TableCell>{job.records_failed}</TableCell>
                        <TableCell>{formatDate(job.started_at)}</TableCell>
                        <TableCell>{formatDate(job.completed_at)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      <Dialog open={syncDialogOpen} onClose={() => setSyncDialogOpen(false)}>
        <DialogTitle>{t('sync.startTitle')}</DialogTitle>
        <DialogContent>
          <Box sx={{ minWidth: 400, mt: 2 }}>
            <FormControl fullWidth sx={{ mb: 2 }}>
              <InputLabel>{t('sync.syncType')}</InputLabel>
              <Select
                value={syncType}
                onChange={(e) => setSyncType(e.target.value)}
                label={t('sync.syncType')}
              >
                <MenuItem value="full_sync">{t('sync.fullSync')}</MenuItem>
                <MenuItem value="incremental_sync">{t('sync.incrementalSync')}</MenuItem>
                <MenuItem value="partial_sync">{t('sync.partialSync')}</MenuItem>
              </Select>
            </FormControl>
            <FormControl fullWidth>
              <InputLabel>{t('sync.direction')}</InputLabel>
              <Select
                value={syncDirection}
                onChange={(e) => setSyncDirection(e.target.value)}
                label={t('sync.direction')}
              >
                <MenuItem value="sap_to_plesk">SAP → Plesk</MenuItem>
                <MenuItem value="plesk_to_sap">Plesk → SAP</MenuItem>
                <MenuItem value="bidirectional">Bidirectional</MenuItem>
              </Select>
            </FormControl>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setSyncDialogOpen(false)}>{t('common.cancel')}</Button>
          <Button onClick={startSync} variant="contained" color="primary">
            {t('sync.start')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default SyncPage;
