import { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  Paper,
} from '@mui/material';
import {
  Warning as WarningIcon,
  CheckCircle as CheckCircleIcon,
  Delete as DeleteIcon,
} from '@mui/icons-material';
import { useI18n } from '../contexts/I18nContext';
import { apiJson } from '../lib/api';
import { logger } from '../lib/logger';

interface Conflict {
  id: number;
  sync_job_id: number;
  entity_type: string;
  entity_id: string;
  resolution_status: string;
  source_data: Record<string, unknown>;
  target_data?: Record<string, unknown>;
  conflict_details?: Record<string, unknown>;
}

type ResolutionAction = 'source' | 'target' | 'merge' | 'skip';

const ConflictsPage: React.FC = () => {
  const { t } = useI18n();
  const [conflicts, setConflicts] = useState<Conflict[]>([]);
  const [, setLoading] = useState(false);
  const [selectedConflict, setSelectedConflict] = useState<Conflict | null>(null);
  const [resolutionDialogOpen, setResolutionDialogOpen] = useState(false);
  const [resolutionAction, setResolutionAction] = useState<ResolutionAction>('source');

  const fetchConflicts = async () => {
    setLoading(true);
    try {
      const data = await apiJson<Conflict[]>('/sync/conflicts');
      setConflicts(data);
    } catch (error) {
      logger.error('Failed to fetch conflicts:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleResolve = async () => {
    if (!selectedConflict) return;
    
    try {
      await apiJson(`/sync/conflicts/${selectedConflict.id}/resolve`, {
        method: 'POST',
        body: JSON.stringify({
          action: resolutionAction,
          resolved_data: resolutionAction === 'source' 
            ? selectedConflict.source_data 
            : selectedConflict.target_data || {},
        }),
      });
      
      setConflicts(conflicts.filter(c => c.id !== selectedConflict.id));
      setResolutionDialogOpen(false);
      setSelectedConflict(null);
    } catch (error) {
      logger.error('Failed to resolve conflict:', error);
    }
  };

  const getStatusColor = (status: string): 'default' | 'error' | 'warning' | 'success' => {
    if (status === 'resolved') return 'success';
    if (status === 'pending') return 'warning';
    return 'default';
  };

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4">{t('conflicts.title')}</Typography>
        <Button 
          variant="contained" 
          onClick={fetchConflicts}
          startIcon={<CheckCircleIcon />}
        >
          {t('conflicts.refresh')}
        </Button>
      </Box>

      <Card>
        <CardContent>
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>{t('conflicts.entityType')}</TableCell>
                  <TableCell>{t('conflicts.entityId')}</TableCell>
                  <TableCell>{t('conflicts.sourceData')}</TableCell>
                  <TableCell>{t('conflicts.targetData')}</TableCell>
                  <TableCell>{t('conflicts.status')}</TableCell>
                  <TableCell>{t('conflicts.actions')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {conflicts.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} align="center">
                      <Typography variant="body2" color="textSecondary">
                        {t('conflicts.noConflicts')}
                      </Typography>
                    </TableCell>
                  </TableRow>
                ) : (
                  conflicts.map((conflict) => (
                    <TableRow key={conflict.id}>
                      <TableCell>{conflict.entity_type}</TableCell>
                      <TableCell>{conflict.entity_id}</TableCell>
                      <TableCell>
                        <Typography variant="body2" noWrap sx={{ maxWidth: 200 }}>
                          {JSON.stringify(conflict.source_data).substr(0, 50)}...
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Typography variant="body2" noWrap sx={{ maxWidth: 200 }}>
                          {conflict.target_data ? JSON.stringify(conflict.target_data).substr(0, 50) + '...' : '-'}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Chip 
                          label={conflict.resolution_status} 
                          color={getStatusColor(conflict.resolution_status)} 
                          size="small"
                        />
                      </TableCell>
                      <TableCell>
                        <Button
                          variant="outlined"
                          size="small"
                          onClick={() => {
                            setSelectedConflict(conflict);
                            setResolutionDialogOpen(true);
                          }}
                        >
                          {t('conflicts.resolve')}
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        </CardContent>
      </Card>

      <Dialog open={resolutionDialogOpen} onClose={() => setResolutionDialogOpen(false)} maxWidth="md" fullWidth>
        <DialogTitle>{t('conflicts.resolveConflict')}</DialogTitle>
        <DialogContent>
          {selectedConflict && (
            <Box>
              <Typography variant="subtitle1" gutterBottom>
                {t('conflicts.entityType')}: {selectedConflict.entity_type} - {selectedConflict.entity_id}
              </Typography>

              <Grid container spacing={3} sx={{ mt: 2 }}>
                <Grid item xs={12} md={6}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="h6">
                        {t('conflicts.source')}
                      </Typography>
                      <Box sx={{ mt: 2, bgcolor: '#f5f5f5', p: 2, borderRadius: 1, maxHeight: 300, overflow: 'auto' }}>
                        <pre style={{ margin: 0 }}>
                          {JSON.stringify(selectedConflict.source_data, null, 2)}
                        </pre>
                      </Box>
                    </CardContent>
                  </Card>
                </Grid>

                <Grid item xs={12} md={6}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="h6">
                        {t('conflicts.target')}
                      </Typography>
                      <Box sx={{ mt: 2, bgcolor: '#f0f7ff', p: 2, borderRadius: 1, maxHeight: 300, overflow: 'auto' }}>
                        <pre style={{ margin: 0 }}>
                          {JSON.stringify(selectedConflict.target_data || {}, null, 2)}
                        </pre>
                      </Box>
                    </CardContent>
                  </Card>
                </Grid>
              </Grid>

              <Box sx={{ mt: 3 }}>
                <Typography variant="subtitle1" gutterBottom>
                  {t('conflicts.resolutionAction')}
                </Typography>
                <Grid container spacing={2}>
                  <Grid item xs={6} md={3}>
                    <Paper 
                      elevation={resolutionAction === 'source' ? 3 : 1}
                      onClick={() => setResolutionAction('source')}
                      sx={{ 
                        p: 2, 
                        cursor: 'pointer',
                        textAlign: 'center',
                        border: resolutionAction === 'source' ? '2px solid ' : '1px solid ',
                        borderColor: resolutionAction === 'source' ? 'primary.main' : 'grey.300',
                        transition: 'all 0.2s'
                      }}
                    >
                      <CheckCircleIcon color="primary" />
                      <Typography variant="body2" sx={{ mt: 1 }}>
                        {t('conflicts.keepSource')}
                      </Typography>
                    </Paper>
                  </Grid>
                  <Grid item xs={6} md={3}>
                    <Paper 
                      elevation={resolutionAction === 'target' ? 3 : 1}
                      onClick={() => setResolutionAction('target')}
                      sx={{ 
                        p: 2, 
                        cursor: 'pointer',
                        textAlign: 'center',
                        border: resolutionAction === 'target' ? '2px solid ' : '1px solid ',
                        borderColor: resolutionAction === 'target' ? 'primary.main' : 'grey.300',
                        transition: 'all 0.2s'
                      }}
                    >
                      <CheckCircleIcon color="primary" />
                      <Typography variant="body2" sx={{ mt: 1 }}>
                        {t('conflicts.keepTarget')}
                      </Typography>
                    </Paper>
                  </Grid>
                  <Grid item xs={6} md={3}>
                    <Paper 
                      elevation={resolutionAction === 'merge' ? 3 : 1}
                      onClick={() => setResolutionAction('merge')}
                      sx={{ 
                        p: 2, 
                        cursor: 'pointer',
                        textAlign: 'center',
                        border: resolutionAction === 'merge' ? '2px solid ' : '1px solid ',
                        borderColor: resolutionAction === 'merge' ? 'primary.main' : 'grey.300',
                        transition: 'all 0.2s'
                      }}
                    >
                      <WarningIcon color="warning" />
                      <Typography variant="body2" sx={{ mt: 1 }}>
                        {t('conflicts.merge')}
                      </Typography>
                    </Paper>
                  </Grid>
                  <Grid item xs={6} md={3}>
                    <Paper 
                      elevation={resolutionAction === 'skip' ? 3 : 1}
                      onClick={() => setResolutionAction('skip')}
                      sx={{ 
                        p: 2, 
                        cursor: 'pointer',
                        textAlign: 'center',
                        border: resolutionAction === 'skip' ? '2px solid ' : '1px solid ',
                        borderColor: resolutionAction === 'skip' ? 'primary.main' : 'grey.300',
                        transition: 'all 0.2s'
                      }}
                    >
                      <DeleteIcon color="error" />
                      <Typography variant="body2" sx={{ mt: 1 }}>
                        {t('conflicts.skip')}
                      </Typography>
                    </Paper>
                  </Grid>
                </Grid>
              </Box>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setResolutionDialogOpen(false)}>
            {t('common.cancel')}
          </Button>
          <Button variant="contained" onClick={handleResolve}>
            {t('conflicts.applyResolution')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default ConflictsPage;
