'use client';

import { useState, useEffect } from 'react';
import {
  Typography,
  Box,
  Breadcrumbs,
  Link,
  Card,
  CardContent,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  CircularProgress,
  Alert,
  Chip,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper
} from '@mui/material';
import {
  Home,
  Analytics,
  TrendingUp,
  People,
  Chat,
  FavoriteBorder,
  Bookmarks
} from '@mui/icons-material';
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} from 'recharts';

interface AnalyticsData {
  period: number;
  overview: {
    users: { total: number; new: number; active: number };
    prayerRequests: { total: number; active: number; new: number };
    prayers: { total: number; new: number };
    conversations: { total: number; active: number; new: number };
    messages: { total: number; new: number };
    bookmarks: { total: number; new: number };
  };
  distributions: {
    usersByRole: Array<{ role: string; _count: { role: number } }>;
    prayersByCategory: Array<{ category: string; _count: { category: number } }>;
  };
  topContent: {
    prayerRequests: Array<{
      id: string;
      title: string;
      category: string;
      prayerCount: number;
      author: string;
    }>;
  };
  activity: {
    daily: Array<{
      date: string;
      newUsers: number;
      newPrayers: number;
      newConversations: number;
      newBookmarks: number;
    }>;
  };
}

interface MetricCardProps {
  title: string;
  value: number;
  change: number;
  icon: React.ReactNode;
  color: string;
}

function MetricCard({ title, value, change, icon, color }: MetricCardProps) {
  return (
    <Card>
      <CardContent>
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Box>
            <Typography color="textSecondary" gutterBottom variant="body2">
              {title}
            </Typography>
            <Typography variant="h4">
              {value.toLocaleString()}
            </Typography>
            <Box sx={{ display: 'flex', alignItems: 'center', mt: 1 }}>
              <TrendingUp sx={{ fontSize: 16, mr: 0.5, color: change >= 0 ? 'success.main' : 'error.main' }} />
              <Typography
                variant="body2"
                sx={{ color: change >= 0 ? 'success.main' : 'error.main' }}
              >
                {change >= 0 ? '+' : ''}{change}
              </Typography>
              <Typography variant="body2" color="textSecondary" sx={{ ml: 0.5 }}>
                this period
              </Typography>
            </Box>
          </Box>
          <Box sx={{ color, fontSize: 40 }}>
            {icon}
          </Box>
        </Box>
      </CardContent>
    </Card>
  );
}

const COLORS = ['#8884d8', '#82ca9d', '#ffc658', '#ff7300', '#0088fe', '#00c49f'];

export default function AdminAnalyticsPage() {
  const [data, setData] = useState<AnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [period, setPeriod] = useState('30');

  useEffect(() => {
    const fetchAnalytics = async () => {
      setLoading(true);
      try {
        const response = await fetch(`/api/admin/analytics/overview?period=${period}`, {
          credentials: 'include'
        });

        if (response.ok) {
          const analyticsData = await response.json();
          setData(analyticsData);
        } else {
          setError('Failed to load analytics data');
        }
      } catch (error) {
        setError('Network error loading analytics');
      } finally {
        setLoading(false);
      }
    };

    fetchAnalytics();
  }, [period]);

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

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

  if (!data) return null;

  return (
    <Box>
      {/* Breadcrumbs */}
      <Breadcrumbs aria-label="breadcrumb" sx={{ mb: 3 }}>
        <Link
          underline="hover"
          sx={{ display: 'flex', alignItems: 'center' }}
          color="inherit"
          href="/admin"
        >
          <Home sx={{ mr: 0.5 }} fontSize="inherit" />
          Admin
        </Link>
        <Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
          <Analytics sx={{ mr: 0.5 }} fontSize="inherit" />
          Analytics
        </Typography>
      </Breadcrumbs>

      {/* Page Header */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
        <Box>
          <Typography variant="h4" component="h1" gutterBottom>
            Analytics Dashboard
          </Typography>
          <Typography variant="body1" color="text.secondary">
            Comprehensive insights into user behavior and content engagement
          </Typography>
        </Box>
        <FormControl size="small" sx={{ minWidth: 150 }}>
          <InputLabel>Time Period</InputLabel>
          <Select
            value={period}
            label="Time Period"
            onChange={(e) => setPeriod(e.target.value)}
          >
            <MenuItem value="7">Last 7 days</MenuItem>
            <MenuItem value="30">Last 30 days</MenuItem>
            <MenuItem value="90">Last 90 days</MenuItem>
          </Select>
        </FormControl>
      </Box>

      {/* Metric Cards */}
      <Box
        sx={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
          gap: 3,
          mb: 4
        }}
      >
        <Box sx={{ cursor: 'pointer' }} onClick={() => window.location.href = '/admin/analytics/users'}>
          <MetricCard
            title="Total Users"
            value={data.overview.users.total}
            change={data.overview.users.new}
            icon={<People />}
            color="#1976d2"
          />
        </Box>
        <MetricCard
          title="Prayer Requests"
          value={data.overview.prayerRequests.total}
          change={data.overview.prayerRequests.new}
          icon={<FavoriteBorder />}
          color="#d32f2f"
        />
        <MetricCard
          title="Total Prayers"
          value={data.overview.prayers.total}
          change={data.overview.prayers.new}
          icon={<FavoriteBorder />}
          color="#ed6c02"
        />
        <MetricCard
          title="Conversations"
          value={data.overview.conversations.total}
          change={data.overview.conversations.new}
          icon={<Chat />}
          color="#2e7d32"
        />
        <MetricCard
          title="Messages"
          value={data.overview.messages.total}
          change={data.overview.messages.new}
          icon={<Chat />}
          color="#9c27b0"
        />
        <MetricCard
          title="Bookmarks"
          value={data.overview.bookmarks.total}
          change={data.overview.bookmarks.new}
          icon={<Bookmarks />}
          color="#0288d1"
        />
      </Box>

      <Box
        sx={{
          display: 'grid',
          gridTemplateColumns: { xs: '1fr', lg: '2fr 1fr' },
          gap: 3,
          mb: 3
        }}
      >
        {/* Daily Activity Chart */}
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Daily Activity Trends
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={data.activity.daily}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="newUsers" stroke="#8884d8" name="New Users" />
                <Line type="monotone" dataKey="newPrayers" stroke="#82ca9d" name="New Prayers" />
                <Line type="monotone" dataKey="newConversations" stroke="#ffc658" name="New Conversations" />
                <Line type="monotone" dataKey="newBookmarks" stroke="#ff7300" name="New Bookmarks" />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* User Roles Distribution */}
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              User Roles Distribution
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={data.distributions.usersByRole.map(item => ({
                    name: item.role,
                    value: item._count.role
                  }))}
                  cx="50%"
                  cy="50%"
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                  label
                >
                  {data.distributions.usersByRole.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </Box>

      <Box
        sx={{
          display: 'grid',
          gridTemplateColumns: { xs: '1fr', lg: '1fr 1fr' },
          gap: 3
        }}
      >
        {/* Prayer Categories Chart */}
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Prayer Requests by Category
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={data.distributions.prayersByCategory.map(item => ({
                category: item.category,
                count: item._count.category
              }))}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="category" />
                <YAxis />
                <Tooltip />
                <Bar dataKey="count" fill="#8884d8" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Top Prayer Requests */}
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Most Prayed For Requests
            </Typography>
            <TableContainer>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>Title</TableCell>
                    <TableCell>Category</TableCell>
                    <TableCell align="right">Prayers</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {data.topContent.prayerRequests.map((request) => (
                    <TableRow key={request.id}>
                      <TableCell>
                        <Typography variant="body2" noWrap sx={{ maxWidth: 200 }}>
                          {request.title}
                        </Typography>
                        <Typography variant="caption" color="text.secondary">
                          by {request.author}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Chip
                          label={request.category}
                          size="small"
                          variant="outlined"
                        />
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="body2" fontWeight="medium">
                          {request.prayerCount}
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </CardContent>
        </Card>
      </Box>
    </Box>
  );
}