import { useState, useCallback } from 'react';
import {
  Box,
  Card,
  CardContent,
  Grid,
  Typography,
  CircularProgress,
  Chip,
} from '@mui/material';
import {
  CheckCircle as CheckCircleIcon,
  Error as ErrorIcon,
} from '@mui/icons-material';
import { useI18n } from '../contexts/I18nContext';
import { apiFetch } from '../lib/api';
import { usePolling } from '../lib/hooks';
import { logger } from '../lib/logger';

interface SyncStatus {
  is_running: boolean;
  current_job: unknown;
  recent_jobs: Array<{
    id: number;
    job_type: string;
    sync_direction: string;
    status: string;
  }>;
  stats: {
    running: number;
    completed_today: number;
    failed_today: number;
  };
}

interface HealthStatus {
  status: string;
  database: {
    status: string;
    healthy: boolean;
  };
}

interface ServerInfo {
  id: number;
  name: string;
  host: string;
  connection_status: string;
  is_active: boolean;
}

const DashboardPage: React.FC = () => {
  const [syncStatus, setSyncStatus] = useState<SyncStatus | null>(null);
  const [healthStatus, setHealthStatus] = useState<HealthStatus | null>(null);
  const [pleskServers, setPleskServers] = useState<ServerInfo[]>([]);
  const [sapServers, setSapServers] = useState<ServerInfo[]>([]);
  const { t } = useI18n();

  const fetchData = useCallback(async () => {
    try {
      const [syncResponse, healthResponse, pleskResponse, sapResponse] = await Promise.all([
        apiFetch('/sync/status'),
        apiFetch('/health'),
        apiFetch('/servers/plesk'),
        apiFetch('/servers/sap'),
      ]);

      if (syncResponse.ok) {
        setSyncStatus(await syncResponse.json());
      }

      if (healthResponse.ok) {
        setHealthStatus(await healthResponse.json());
      }

      if (pleskResponse.ok) {
        setPleskServers(await pleskResponse.json());
      }

      if (sapResponse.ok) {
        setSapServers(await sapResponse.json());
      }
    } catch (error) {
      logger.error('Failed to fetch dashboard data:', error);
    }
  }, []);

  usePolling(fetchData, 30000);

  const recentJobs = syncStatus?.recent_jobs ?? [];

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

      <Grid container spacing={3}>
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t('dashboard.sync_status')}
              </Typography>
              <Box display="flex" alignItems="center" mb={2}>
                {syncStatus?.is_running ? (
                  <>
                    <CircularProgress size={20} sx={{ mr: 1 }} />
                    <Typography>{t('dashboard.sync_running')}</Typography>
                  </>
                ) : (
                  <>
                    <CheckCircleIcon color="success" sx={{ mr: 1 }} />
                    <Typography>{t('dashboard.no_sync')}</Typography>
                  </>
                )}
              </Box>
                <Grid container spacing={2}>
                <Grid item>
                  <Typography variant="body2" color="textSecondary">
                    {t('dashboard.running')}: {syncStatus?.stats?.running ?? 0}
                  </Typography>
                </Grid>
                <Grid item>
                  <Typography variant="body2" color="textSecondary">
                    {t('dashboard.completed_today')}: {syncStatus?.stats?.completed_today ?? 0}
                  </Typography>
                </Grid>
                <Grid item>
                  <Typography variant="body2" color="textSecondary">
                    {t('dashboard.failed_today')}: {syncStatus?.stats?.failed_today ?? 0}
                  </Typography>
                </Grid>
              </Grid>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t('dashboard.health_status')}
              </Typography>
              <Box mb={2}>
                <Box display="flex" alignItems="center" mb={1}>
                  {healthStatus?.database?.healthy ? (
                    <CheckCircleIcon color="success" sx={{ mr: 1 }} />
                  ) : (
                    <ErrorIcon color="error" sx={{ mr: 1 }} />
                  )}
                  <Typography>
                    {t('dashboard.internal_db')}: {healthStatus?.database?.healthy ? t('dashboard.connected') : t('dashboard.disconnected')}
                  </Typography>
                </Box>

                {pleskServers.length > 0 ? (
                  pleskServers.map((s) => (
                    <Box key={`plesk-${s.id}`} display="flex" alignItems="center" mb={1}>
                      {s.connection_status === 'connected' ? (
                        <CheckCircleIcon color="success" sx={{ mr: 1 }} />
                      ) : (
                        <ErrorIcon color="warning" sx={{ mr: 1 }} />
                      )}
                      <Typography>Plesk ({s.name}): {s.connection_status}</Typography>
                    </Box>
                  ))
                ) : (
                  <Box display="flex" alignItems="center" mb={1}>
                    <ErrorIcon color="disabled" sx={{ mr: 1 }} />
                    <Typography color="textSecondary">{t('dashboard.no_plesk')}</Typography>
                  </Box>
                )}

                {sapServers.length > 0 ? (
                  sapServers.map((s) => (
                    <Box key={`sap-${s.id}`} display="flex" alignItems="center" mb={1}>
                      {s.connection_status === 'connected' ? (
                        <CheckCircleIcon color="success" sx={{ mr: 1 }} />
                      ) : (
                        <ErrorIcon color="warning" sx={{ mr: 1 }} />
                      )}
                      <Typography>SAP ({s.name}): {s.connection_status}</Typography>
                    </Box>
                  ))
                ) : (
                  <Box display="flex" alignItems="center" mb={1}>
                    <ErrorIcon color="disabled" sx={{ mr: 1 }} />
                    <Typography color="textSecondary">{t('dashboard.no_sap')}</Typography>
                  </Box>
                )}
              </Box>
              <Chip
                label={healthStatus?.status === 'healthy' ? t('dashboard.healthy') : t('dashboard.unhealthy')}
                color={healthStatus?.status === 'healthy' ? 'success' : 'error'}
              />
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t('dashboard.recent_jobs')}
              </Typography>
              {recentJobs.length > 0 ? (
                <Box>
                  {recentJobs.map((job) => (
                    <Box key={job.id} mb={2} p={2} bgcolor="grey.100" borderRadius={1}>
                      <Typography variant="body2">
                        Job #{job.id} - {job.job_type} ({job.sync_direction})
                      </Typography>
                      <Chip
                        label={job.status}
                        size="small"
                        color={
                          job.status === 'completed'
                            ? 'success'
                            : job.status === 'failed'
                            ? 'error'
                            : 'warning'
                        }
                        sx={{ mt: 1 }}
                      />
                    </Box>
                  ))}
                </Box>
              ) : (
                <Typography color="textSecondary">{t('dashboard.no_recent_jobs')}</Typography>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  );
};

export default DashboardPage;
