import { useEffect, useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Grid,
  CircularProgress,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
} from '@mui/material';
import {
  Download as DownloadIcon,
} from '@mui/icons-material';
import {
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  BarChart,
  Bar,
} from 'recharts';
import toast from 'react-hot-toast';
import { apiFetch, getErrorMessage } from '../lib/api';
import { logger } from '../lib/logger';
import { useI18n } from '../contexts/I18nContext';

interface SyncStats {
  running: number;
  completed_today: number;
  failed_today: number;
}

interface SyncStatusResponse {
  stats: SyncStats;
}

interface UsageMetric {
  id: number;
  subscription_id: number;
  metric_type: string;
  metric_value: number;
  unit: string;
  recorded_at: string;
}

const ReportsPage = () => {
  const { t } = useI18n();
  const [syncStats, setSyncStats] = useState<SyncStats | null>(null);
  const [usageMetrics, setUsageMetrics] = useState<UsageMetric[]>([]);
  const [loading, setLoading] = useState(true);
  const [reportType, setReportType] = useState('sync');
  const [dateRange, setDateRange] = useState('7d');

  useEffect(() => {
    fetchReportData();
  }, [reportType, dateRange]);

  const fetchReportData = async () => {
    setLoading(true);
    try {
      // Fetch sync stats
      const syncResponse = await apiFetch('/sync/status');
      if (syncResponse.ok) {
        const data: SyncStatusResponse = await syncResponse.json();
        setSyncStats(data.stats);
      }

      // Fetch usage metrics (placeholder)
      setUsageMetrics([]);
    } catch (error) {
      logger.error('Failed to fetch report data:', error);
    } finally {
      setLoading(false);
    }
  };

  const exportReport = async (format: string) => {
    try {
      const response = await apiFetch(`/reports/export/${format}?type=${reportType}&range=${dateRange}`);

      if (!response.ok) {
        toast.error(await getErrorMessage(response, t('reports.exportFailed')));
        return;
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${reportType}-report-${dateRange}.${format}`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      toast.success(t('reports.downloadSuccess'));
    } catch (error) {
      toast.error(t('reports.exportFailed'));
    }
  };

  const chartData = [
    { name: 'Mon', completed: 4, failed: 1 },
    { name: 'Tue', completed: 3, failed: 0 },
    { name: 'Wed', completed: 5, failed: 2 },
    { name: 'Thu', completed: 2, failed: 1 },
    { name: 'Fri', completed: 6, failed: 0 },
    { name: 'Sat', completed: 1, failed: 0 },
    { name: 'Sun', completed: 0, failed: 0 },
  ];

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

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

      <Grid container spacing={3}>
        {/* Controls */}
        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Grid container spacing={2} alignItems="center">
                <Grid item>
                  <FormControl sx={{ minWidth: 200 }}>
                    <InputLabel>{t('reports.reportType')}</InputLabel>
                    <Select
                      value={reportType}
                      onChange={(e) => setReportType(e.target.value)}
                      label={t('reports.reportType')}
                    >
                      <MenuItem value="sync">{t('reports.syncHistory')}</MenuItem>
                      <MenuItem value="usage">{t('reports.usageMetrics')}</MenuItem>
                      <MenuItem value="revenue">{t('reports.revenue')}</MenuItem>
                    </Select>
                  </FormControl>
                </Grid>
                <Grid item>
                  <FormControl sx={{ minWidth: 150 }}>
                    <InputLabel>{t('reports.dateRange')}</InputLabel>
                    <Select
                      value={dateRange}
                      onChange={(e) => setDateRange(e.target.value)}
                      label={t('reports.dateRange')}
                    >
                      <MenuItem value="24h">{t('reports.last24h')}</MenuItem>
                      <MenuItem value="7d">{t('reports.last7d')}</MenuItem>
                      <MenuItem value="30d">{t('reports.last30d')}</MenuItem>
                      <MenuItem value="90d">{t('reports.last90d')}</MenuItem>
                    </Select>
                  </FormControl>
                </Grid>
                <Grid item xs />
                <Grid item>
                  <Button
                    variant="outlined"
                    startIcon={<DownloadIcon />}
                    onClick={() => exportReport('csv')}
                    sx={{ mr: 1 }}
                  >
                    CSV
                  </Button>
                  <Button
                    variant="outlined"
                    startIcon={<DownloadIcon />}
                    onClick={() => exportReport('xlsx')}
                    sx={{ mr: 1 }}
                  >
                    Excel
                  </Button>
                  <Button
                    variant="outlined"
                    startIcon={<DownloadIcon />}
                    onClick={() => exportReport('pdf')}
                  >
                    PDF
                  </Button>
                </Grid>
              </Grid>
            </CardContent>
          </Card>
        </Grid>

        {/* Summary Cards */}
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Typography color="textSecondary" gutterBottom>
                {t('reports.runningJobs')}
              </Typography>
              <Typography variant="h4">{syncStats?.running || 0}</Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Typography color="textSecondary" gutterBottom>
                {t('reports.completedToday')}
              </Typography>
              <Typography variant="h4" color="success.main">
                {syncStats?.completed_today || 0}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Typography color="textSecondary" gutterBottom>
                {t('reports.failedToday')}
              </Typography>
              <Typography variant="h4" color="error.main">
                {syncStats?.failed_today || 0}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Typography color="textSecondary" gutterBottom>
                {t('reports.reportRange')}
              </Typography>
              <Typography variant="h4" color="primary.main">
                {dateRange}
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        {/* Charts */}
        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {t('reports.syncActivity')}
              </Typography>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={chartData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Bar dataKey="completed" fill="#4caf50" name={t('reports.completed')} />
                  <Bar dataKey="failed" fill="#f44336" name={t('reports.failed')} />
                </BarChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        </Grid>

        {/* Usage Metrics Table */}
        {reportType === 'usage' && (
          <Grid item xs={12}>
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  {t('reports.usageMetrics')}
                </Typography>
                <TableContainer component={Paper}>
                  <Table>
                    <TableHead>
                      <TableRow>
                        <TableCell>{t('reports.colId')}</TableCell>
                        <TableCell>{t('reports.colSubscription')}</TableCell>
                        <TableCell>{t('reports.colType')}</TableCell>
                        <TableCell>{t('reports.colValue')}</TableCell>
                        <TableCell>{t('reports.colUnit')}</TableCell>
                        <TableCell>{t('reports.colRecorded')}</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {usageMetrics.map((metric) => (
                        <TableRow key={metric.id}>
                          <TableCell>{metric.id}</TableCell>
                          <TableCell>{metric.subscription_id}</TableCell>
                          <TableCell>{metric.metric_type}</TableCell>
                          <TableCell>{metric.metric_value}</TableCell>
                          <TableCell>{metric.unit}</TableCell>
                          <TableCell>{new Date(metric.recorded_at).toLocaleString()}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              </CardContent>
            </Card>
          </Grid>
        )}
      </Grid>
    </Box>
  );
};

export default ReportsPage;
