'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,
  Avatar
} from '@mui/material';
import {
  Home,
  Analytics,
  People,
  TrendingUp,
  Schedule,
  Assignment
} from '@mui/icons-material';
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} from 'recharts';

interface UserAnalyticsData {
  period: number;
  timeline: {
    registrations: Array<{ date: string; registrations: number }>;
  };
  activity: {
    patterns: Array<{
      id: string;
      email: string;
      name: string | null;
      role: string;
      createdAt: string;
      lastLoginAt: string | null;
      _count: {
        chatConversations: number;
        prayerRequests: number;
        bookmarks: number;
        notes: number;
      };
    }>;
    mostActive: Array<{
      id: string;
      email: string;
      name: string | null;
      role: string;
      totalActivity: number;
      _count: {
        chatConversations: number;
        prayerRequests: number;
        bookmarks: number;
        notes: number;
      };
    }>;
  };
  retention: {
    rate: number;
    newUsers: number;
    activeUsers: number;
  };
  engagement: {
    featureUsage: {
      chat: number;
      prayers: number;
      bookmarks: number;
      notes: number;
    };
    avgSessionLength: number;
    avgMessagesPerSession: number;
  };
  demographics: Array<{
    role: string;
    _count: { role: number };
    _min: { createdAt: string };
    _max: { createdAt: string };
  }>;
}

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

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

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

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

    fetchUserAnalytics();
  }, [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;

  const featureUsageData = Object.entries(data.engagement.featureUsage).map(([key, value]) => ({
    name: key.charAt(0).toUpperCase() + key.slice(1),
    value
  }));

  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>
        <Link
          underline="hover"
          sx={{ display: 'flex', alignItems: 'center' }}
          color="inherit"
          href="/admin/analytics"
        >
          <Analytics sx={{ mr: 0.5 }} fontSize="inherit" />
          Analytics
        </Link>
        <Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
          <People sx={{ mr: 0.5 }} fontSize="inherit" />
          User Analytics
        </Typography>
      </Breadcrumbs>

      {/* Page Header */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
        <Box>
          <Typography variant="h4" component="h1" gutterBottom>
            User Analytics
          </Typography>
          <Typography variant="body1" color="text.secondary">
            Detailed insights into user behavior, engagement, and retention
          </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>

      <Box
        sx={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
          gap: 3,
          mb: 3
        }}
      >
        {/* Key Metrics */}
        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <TrendingUp sx={{ fontSize: 40, color: 'primary.main', mr: 2 }} />
              <Box>
                <Typography color="textSecondary" variant="body2">
                  Retention Rate
                </Typography>
                <Typography variant="h5">
                  {data.retention.rate}%
                </Typography>
              </Box>
            </Box>
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Schedule sx={{ fontSize: 40, color: 'warning.main', mr: 2 }} />
              <Box>
                <Typography color="textSecondary" variant="body2">
                  Avg Session (min)
                </Typography>
                <Typography variant="h5">
                  {data.engagement.avgSessionLength}
                </Typography>
              </Box>
            </Box>
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Assignment sx={{ fontSize: 40, color: 'success.main', mr: 2 }} />
              <Box>
                <Typography color="textSecondary" variant="body2">
                  Avg Messages/Session
                </Typography>
                <Typography variant="h5">
                  {data.engagement.avgMessagesPerSession}
                </Typography>
              </Box>
            </Box>
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <People sx={{ fontSize: 40, color: 'info.main', mr: 2 }} />
              <Box>
                <Typography color="textSecondary" variant="body2">
                  Active/New Users
                </Typography>
                <Typography variant="h5">
                  {data.retention.activeUsers}/{data.retention.newUsers}
                </Typography>
              </Box>
            </Box>
          </CardContent>
        </Card>
      </Box>

      <Box
        sx={{
          display: 'grid',
          gridTemplateColumns: { xs: '1fr', lg: '2fr 1fr' },
          gap: 3,
          mb: 3
        }}
      >
        {/* User Registration Timeline */}
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              User Registration Timeline
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart data={data.timeline.registrations}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Area
                  type="monotone"
                  dataKey="registrations"
                  stroke="#8884d8"
                  fill="#8884d8"
                  fillOpacity={0.6}
                />
              </AreaChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Feature Usage Distribution */}
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Feature Usage Distribution
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={featureUsageData}
                  cx="50%"
                  cy="50%"
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                  label={({ name, percent }: any) => `${name} ${(percent * 100).toFixed(0)}%`}
                >
                  {featureUsageData.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
        }}
      >
        {/* Most Active Users */}
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Most Active Users
            </Typography>
            <TableContainer>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>User</TableCell>
                    <TableCell>Role</TableCell>
                    <TableCell align="right">Total Activity</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {data.activity.mostActive.slice(0, 10).map((user) => (
                    <TableRow key={user.id}>
                      <TableCell>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                          <Avatar sx={{ width: 24, height: 24, fontSize: 12 }}>
                            {(user.name || user.email)[0].toUpperCase()}
                          </Avatar>
                          <Box>
                            <Typography variant="body2">
                              {user.name || 'Unknown User'}
                            </Typography>
                            <Typography variant="caption" color="text.secondary">
                              {user.email}
                            </Typography>
                          </Box>
                        </Box>
                      </TableCell>
                      <TableCell>
                        <Chip
                          label={user.role}
                          size="small"
                          color={user.role === 'admin' ? 'error' : user.role === 'moderator' ? 'warning' : 'primary'}
                          variant="outlined"
                        />
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="body2" fontWeight="medium">
                          {user.totalActivity}
                        </Typography>
                        <Typography variant="caption" color="text.secondary">
                          {user._count.chatConversations}c {user._count.prayerRequests}p {user._count.bookmarks}b
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </CardContent>
        </Card>

        {/* User Demographics */}
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              User Demographics by Role
            </Typography>
            <TableContainer>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>Role</TableCell>
                    <TableCell align="right">Count</TableCell>
                    <TableCell>First User</TableCell>
                    <TableCell>Latest User</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {data.demographics.map((demo) => (
                    <TableRow key={demo.role}>
                      <TableCell>
                        <Chip
                          label={demo.role}
                          size="small"
                          color={demo.role === 'admin' ? 'error' : demo.role === 'moderator' ? 'warning' : 'primary'}
                          variant="outlined"
                        />
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="body2" fontWeight="medium">
                          {demo._count.role}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Typography variant="caption">
                          {new Date(demo._min.createdAt).toLocaleDateString()}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Typography variant="caption">
                          {new Date(demo._max.createdAt).toLocaleDateString()}
                        </Typography>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </CardContent>
        </Card>
      </Box>
    </Box>
  );
}