'use client';

import { useEffect, useState } from 'react';
import {
  Grid,
  Card,
  CardContent,
  Typography,
  Box,
  Chip,
  CircularProgress,
  Alert
} from '@mui/material';
import {
  People,
  Chat,
  FavoriteBorder,
  TrendingUp,
  TrendingDown
} from '@mui/icons-material';

interface OverviewStats {
  totalUsers: number;
  dailyActiveUsers: number;
  conversationsToday: number;
  prayerRequestsToday: number;
  userGrowthChange: number;
  conversationChange: number;
  prayerChange: number;
  usersToday: number;
}

interface MetricCardProps {
  title: string;
  value: number;
  change?: number;
  icon: React.ReactNode;
  color: 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'info';
  subtitle?: string;
}

function MetricCard({ title, value, change, icon, color, subtitle }: MetricCardProps) {
  const isPositiveChange = change !== undefined && change >= 0;

  return (
    <Card sx={{ height: '100%' }}>
      <CardContent>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <Box>
            <Typography color="text.secondary" gutterBottom variant="h6">
              {title}
            </Typography>
            <Typography variant="h4" component="div" sx={{ mb: 1 }}>
              {value.toLocaleString()}
            </Typography>
            {subtitle && (
              <Typography variant="body2" color="text.secondary">
                {subtitle}
              </Typography>
            )}
          </Box>
          <Box
            sx={{
              backgroundColor: `${color}.main`,
              borderRadius: 2,
              p: 1,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: 'white'
            }}
          >
            {icon}
          </Box>
        </Box>

        {change !== undefined && (
          <Box sx={{ mt: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
            {isPositiveChange ? (
              <TrendingUp color="success" fontSize="small" />
            ) : (
              <TrendingDown color="error" fontSize="small" />
            )}
            <Chip
              label={`${Math.abs(change)}%`}
              color={isPositiveChange ? 'success' : 'error'}
              size="small"
              variant="outlined"
            />
            <Typography variant="body2" color="text.secondary">
              vs yesterday
            </Typography>
          </Box>
        )}
      </CardContent>
    </Card>
  );
}

export function OverviewCards() {
  const [stats, setStats] = useState<OverviewStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await fetch('/api/admin/stats/overview', {
          credentials: 'include'
        });
        const data = await response.json();

        if (response.ok) {
          setStats(data);
        } else {
          setError(data.error || 'Failed to load stats');
        }
      } catch (error) {
        setError('Network error loading stats');
      } finally {
        setLoading(false);
      }
    };

    fetchStats();

    // Refresh stats every 30 seconds
    const interval = setInterval(fetchStats, 30000);
    return () => clearInterval(interval);
  }, []);

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Alert severity="error" sx={{ mb: 3 }}>
        {error}
      </Alert>
    );
  }

  if (!stats) return null;

  return (
    <Box sx={{
      display: 'grid',
      gridTemplateColumns: {
        xs: '1fr',
        sm: 'repeat(2, 1fr)',
        md: 'repeat(4, 1fr)'
      },
      gap: 3
    }}>
      <MetricCard
        title="Total Users"
        value={stats.totalUsers}
        change={stats.userGrowthChange}
        icon={<People />}
        color="primary"
        subtitle={`${stats.usersToday} new today`}
      />

      <MetricCard
        title="Daily Active Users"
        value={stats.dailyActiveUsers}
        icon={<People />}
        color="success"
        subtitle="Logged in today"
      />

      <MetricCard
        title="AI Conversations"
        value={stats.conversationsToday}
        change={stats.conversationChange}
        icon={<Chat />}
        color="info"
        subtitle="Today"
      />

      <MetricCard
        title="Prayer Requests"
        value={stats.prayerRequestsToday}
        change={stats.prayerChange}
        icon={<FavoriteBorder />}
        color="warning"
        subtitle="Today"
      />
    </Box>
  );
}