import React, { useState, useEffect } from 'react';
import {
  Box,
  Grid,
  Card,
  CardContent,
  Typography,
  CircularProgress,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  Alert,
  LinearProgress,
  Tabs,
  Tab
} from '@mui/material';
import {
  People,
  Tv,
  Radio,
  PlaylistPlay,
  TrendingUp,
  Speed,
  HealthAndSafety,
  Warning,
  CheckCircle,
  Error as ErrorIcon
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import axios from 'axios';

function TabPanel({ children, value, index, ...other }) {
  return (
    <div hidden={value !== index} {...other}>
      {value === index && <Box sx={{ py: 2 }}>{children}</Box>}
    </div>
  );
}

const Stats = () => {
  const { t } = useTranslation();
  const { token, user } = useAuthStore();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [tabValue, setTabValue] = useState(0);
  
  const [overview, setOverview] = useState(null);
  const [topChannels, setTopChannels] = useState([]);
  const [usageByHour, setUsageByHour] = useState([]);
  const [trends, setTrends] = useState([]);
  const [userActivity, setUserActivity] = useState([]);

  useEffect(() => {
    if (user?.role === 'admin') {
      fetchAllStats();
    }
  }, [user]);

  const fetchAllStats = async () => {
    try {
      setLoading(true);
      
      const [overviewRes, channelsRes, hourlyRes, trendsRes, usersRes] = await Promise.all([
        axios.get('/api/stats/overview', { headers: { Authorization: `Bearer ${token}` } }),
        axios.get('/api/stats/top-channels?limit=15', { headers: { Authorization: `Bearer ${token}` } }),
        axios.get('/api/stats/usage-by-hour?days=7', { headers: { Authorization: `Bearer ${token}` } }),
        axios.get('/api/stats/trends?days=14', { headers: { Authorization: `Bearer ${token}` } }),
        axios.get('/api/stats/user-activity?days=30', { headers: { Authorization: `Bearer ${token}` } })
      ]);

      setOverview(overviewRes.data);
      setTopChannels(channelsRes.data);
      setUsageByHour(hourlyRes.data);
      setTrends(trendsRes.data);
      setUserActivity(usersRes.data);
    } catch (err) {
      setError('Failed to load statistics');
      console.error('Stats fetch error:', err);
    } finally {
      setLoading(false);
    }
  };

  const formatDuration = (seconds) => {
    if (!seconds) return '0m';
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    if (hours > 0) return `${hours}h ${minutes}m`;
    return `${minutes}m`;
  };

  const formatBytes = (bytes) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  };

  if (user?.role !== 'admin') {
    return (
      <Box>
        <Alert severity="error">Admin access required to view statistics.</Alert>
      </Box>
    );
  }

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      <Typography variant="h5" fontWeight="bold" gutterBottom>
        Analytics Dashboard
      </Typography>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      {/* Overview Cards */}
      <Grid container spacing={2} sx={{ mb: 3 }}>
        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography color="text.secondary" variant="caption">
                    Total Users
                  </Typography>
                  <Typography variant="h4" fontWeight="bold">
                    {overview?.totalUsers || 0}
                  </Typography>
                </Box>
                <People sx={{ fontSize: 48, color: 'primary.main', opacity: 0.3 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography color="text.secondary" variant="caption">
                    TV Channels
                  </Typography>
                  <Typography variant="h4" fontWeight="bold">
                    {overview?.totalTvChannels || 0}
                  </Typography>
                </Box>
                <Tv sx={{ fontSize: 48, color: 'success.main', opacity: 0.3 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography color="text.secondary" variant="caption">
                    Radio Channels
                  </Typography>
                  <Typography variant="h4" fontWeight="bold">
                    {overview?.totalRadioChannels || 0}
                  </Typography>
                </Box>
                <Radio sx={{ fontSize: 48, color: 'info.main', opacity: 0.3 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography color="text.secondary" variant="caption">
                    Total Views
                  </Typography>
                  <Typography variant="h4" fontWeight="bold">
                    {overview?.totalWatchHistory?.toLocaleString() || 0}
                  </Typography>
                </Box>
                <TrendingUp sx={{ fontSize: 48, color: 'warning.main', opacity: 0.3 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Channel Health */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
            <HealthAndSafety sx={{ mr: 1 }} />
            <Typography variant="h6">Channel Health Status</Typography>
          </Box>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={4}>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <CheckCircle sx={{ color: 'success.main', mr: 1 }} />
                  <Typography>Healthy</Typography>
                </Box>
                <Chip label={overview?.channelHealth?.healthy || 0} color="success" size="small" />
              </Box>
            </Grid>
            <Grid item xs={12} sm={4}>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Warning sx={{ color: 'warning.main', mr: 1 }} />
                  <Typography>Degraded</Typography>
                </Box>
                <Chip label={overview?.channelHealth?.degraded || 0} color="warning" size="small" />
              </Box>
            </Grid>
            <Grid item xs={12} sm={4}>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <ErrorIcon sx={{ color: 'error.main', mr: 1 }} />
                  <Typography>Dead</Typography>
                </Box>
                <Chip label={overview?.channelHealth?.dead || 0} color="error" size="small" />
              </Box>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* System Resources */}
      {overview?.system && (
        <Card sx={{ mb: 3 }}>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
              <Speed sx={{ mr: 1 }} />
              <Typography variant="h6">System Resources</Typography>
            </Box>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <Typography variant="caption" color="text.secondary">Memory Usage</Typography>
                <Box sx={{ display: 'flex', alignItems: 'center', mt: 0.5 }}>
                  <Box sx={{ flexGrow: 1, mr: 2 }}>
                    <LinearProgress 
                      variant="determinate" 
                      value={(1 - (overview.system.freeMemory / overview.system.totalMemory)) * 100}
                      sx={{ height: 8, borderRadius: 1 }}
                    />
                  </Box>
                  <Typography variant="body2">
                    {formatBytes(overview.system.totalMemory - overview.system.freeMemory)} / {formatBytes(overview.system.totalMemory)}
                  </Typography>
                </Box>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Typography variant="caption" color="text.secondary">Server Uptime</Typography>
                <Typography variant="h6">
                  {Math.floor(overview.system.uptime / 3600)}h {Math.floor((overview.system.uptime % 3600) / 60)}m
                </Typography>
              </Grid>
            </Grid>
          </CardContent>
        </Card>
      )}

      {/* Tabs for detailed stats */}
      <Card>
        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs value={tabValue} onChange={(e, v) => setTabValue(v)}>
            <Tab label="Top Channels" />
            <Tab label="Usage Patterns" />
            <Tab label="User Activity" />
          </Tabs>
        </Box>

        {/* Top Channels */}
        <TabPanel value={tabValue} index={0}>
          <TableContainer>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>Channel</TableCell>
                  <TableCell>Group</TableCell>
                  <TableCell align="right">Views</TableCell>
                  <TableCell align="right">Unique Users</TableCell>
                  <TableCell align="right">Total Duration</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {topChannels.map((channel, index) => (
                  <TableRow key={channel.id}>
                    <TableCell>
                      <Box sx={{ display: 'flex', alignItems: 'center' }}>
                        <Typography variant="body2" fontWeight={index < 3 ? 'bold' : 'normal'}>
                          #{index + 1} {channel.name}
                        </Typography>
                        {channel.is_radio && <Chip label="Radio" size="small" sx={{ ml: 1 }} />}
                      </Box>
                    </TableCell>
                    <TableCell>{channel.group_name || '-'}</TableCell>
                    <TableCell align="right">{channel.watch_count}</TableCell>
                    <TableCell align="right">{channel.unique_users}</TableCell>
                    <TableCell align="right">{formatDuration(channel.total_duration)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>

        {/* Usage Patterns */}
        <TabPanel value={tabValue} index={1}>
          <Typography variant="subtitle2" gutterBottom>Peak Usage Hours (Last 7 Days)</Typography>
          <TableContainer>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>Hour</TableCell>
                  <TableCell align="right">View Count</TableCell>
                  <TableCell align="right">Unique Users</TableCell>
                  <TableCell>Activity</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {usageByHour.map((hour) => (
                  <TableRow key={hour.hour}>
                    <TableCell>{hour.hour}:00</TableCell>
                    <TableCell align="right">{hour.view_count}</TableCell>
                    <TableCell align="right">{hour.unique_users}</TableCell>
                    <TableCell>
                      <LinearProgress 
                        variant="determinate" 
                        value={(hour.view_count / Math.max(...usageByHour.map(h => h.view_count))) * 100}
                        sx={{ height: 6, borderRadius: 1 }}
                      />
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>

        {/* User Activity */}
        <TabPanel value={tabValue} index={2}>
          <Typography variant="subtitle2" gutterBottom>User Activity (Last 30 Days)</Typography>
          <TableContainer>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>Username</TableCell>
                  <TableCell>Email</TableCell>
                  <TableCell align="right">Watch Count</TableCell>
                  <TableCell align="right">Total Duration</TableCell>
                  <TableCell>Last Active</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {userActivity.map((user) => (
                  <TableRow key={user.id}>
                    <TableCell>{user.username}</TableCell>
                    <TableCell>{user.email}</TableCell>
                    <TableCell align="right">{user.watch_count || 0}</TableCell>
                    <TableCell align="right">{formatDuration(user.total_duration)}</TableCell>
                    <TableCell>
                      {user.last_active ? new Date(user.last_active).toLocaleDateString() : 'Never'}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>
      </Card>
    </Box>
  );
};

export default Stats;
