'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Typography,
  Card,
  CardContent,
  LinearProgress,
  List,
  ListItem,
  ListItemText,
  ListItemAvatar,
  Avatar,
  Chip,
  IconButton,
} from '@mui/material';
import {
  People,
  FamilyRestroom,
  ChildCare,
  TrendingUp,
  Warning,
  CheckCircle,
  Refresh,
  AccessTime,
} from '@mui/icons-material';
import { LineChart, Line, AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { format, subDays, startOfDay } from 'date-fns';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';

interface DashboardStats {
  totalUsers: number;
  totalFamilies: number;
  totalChildren: number;
  activeUsers: number;
  newUsersToday: number;
  activitiesLogged: number;
  aiQueriesTotal: number;
  systemStatus: 'healthy' | 'warning' | 'error';
}

const COLORS = ['#FF8B7D', '#FFB5A0', '#FFD4CC', '#81C784', '#FFB74D'];

export default function DashboardPage() {
  const [stats, setStats] = useState<DashboardStats>({
    totalUsers: 0,
    totalFamilies: 0,
    totalChildren: 0,
    activeUsers: 0,
    newUsersToday: 0,
    activitiesLogged: 0,
    aiQueriesTotal: 0,
    systemStatus: 'healthy',
  });
  const [loading, setLoading] = useState(true);
  const [userGrowthData, setUserGrowthData] = useState<any[]>([]);
  const [activityData, setActivityData] = useState<any[]>([]);
  const [recentUsers, setRecentUsers] = useState<any[]>([]);

  const fetchDashboardData = async () => {
    setLoading(true);
    try {
      // Fetch dashboard stats from new endpoint
      const statsResponse = await apiClient.get('/admin/dashboard/stats');

      // Fetch all users to calculate additional metrics
      const usersResponse = await apiClient.get('/admin/users');
      const users = usersResponse.users || [];

      // Calculate users created today
      const today = startOfDay(new Date());
      const newUsersToday = users.filter((u: any) => {
        const createdAt = new Date(u.createdAt);
        return createdAt >= today;
      }).length;

      setStats({
        totalUsers: statsResponse.totalUsers,
        totalFamilies: statsResponse.totalFamilies,
        totalChildren: statsResponse.totalChildren,
        activeUsers: statsResponse.activeUsers,
        newUsersToday,
        activitiesLogged: statsResponse.activitiesLogged,
        aiQueriesTotal: statsResponse.aiQueriesTotal,
        systemStatus: statsResponse.systemStatus || 'healthy',
      });

      // Calculate user growth from creation dates
      const growthMap = new Map<string, number>();
      users.forEach((u: any) => {
        const date = format(new Date(u.createdAt), 'MMM dd');
        growthMap.set(date, (growthMap.get(date) || 0) + 1);
      });

      const growthData = Array.from({ length: 30 }, (_, i) => {
        const date = subDays(new Date(), 29 - i);
        const dateKey = format(date, 'MMM dd');
        return {
          date: dateKey,
          users: growthMap.get(dateKey) || 0,
          activities: 0, // TODO: Add when activity data available
        };
      });
      setUserGrowthData(growthData);

      // Fetch real activity distribution
      const activityDistribution = await apiClient.get('/admin/dashboard/activity-distribution');
      setActivityData(activityDistribution);

      // Get most recent users (last 5)
      const sortedUsers = [...users].sort((a: any, b: any) =>
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      ).slice(0, 5);

      setRecentUsers(sortedUsers.map((u: any) => ({
        id: u.id,
        name: u.name,
        email: u.email,
        joinedAt: new Date(u.createdAt),
      })));
    } catch (error) {
      console.error('Failed to fetch dashboard data:', error);
      // Set empty/error state
      setStats({
        totalUsers: 0,
        totalFamilies: 0,
        totalChildren: 0,
        activeUsers: 0,
        newUsersToday: 0,
        activitiesLogged: 0,
        aiQueriesTotal: 0,
        systemStatus: 'error',
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDashboardData();
  }, []);

  const StatCard = ({ icon, title, value, change, color }: any) => (
    <Card sx={{ height: '100%', minWidth: 500 }}>
      <CardContent>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
          <Avatar sx={{ bgcolor: `${color}.light`, color: `${color}.main`, mr: 2 }}>
            {icon}
          </Avatar>
          <Box sx={{ flexGrow: 1 }}>
            <Typography color="text.secondary" variant="body2">
              {title}
            </Typography>
            <Typography variant="h4" fontWeight={600}>
              {value.toLocaleString()}
            </Typography>
            {change && (
              <Typography
                variant="caption"
                sx={{ color: change > 0 ? 'success.main' : 'error.main' }}
              >
                {change > 0 ? '+' : ''}{change}% from yesterday
              </Typography>
            )}
          </Box>
        </Box>
      </CardContent>
    </Card>
  );

  if (loading) {
    return (
      <AdminLayout>
        <LinearProgress />
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <Box>
        <Box sx={{ mb: 3, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Box>
            <Typography variant="h5" fontWeight={600}>
              Dashboard Overview
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Welcome back! Here's what's happening with ParentFlow today.
            </Typography>
          </Box>
          <IconButton onClick={fetchDashboardData}>
            <Refresh />
          </IconButton>
        </Box>

        {/* Stats Cards */}
        <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 3, mb: 3 }}>
          <StatCard
            icon={<People />}
            title="Total Users"
            value={stats.totalUsers}
            change={5.2}
            color="primary"
          />
          <StatCard
            icon={<FamilyRestroom />}
            title="Families"
            value={stats.totalFamilies}
            change={3.1}
            color="secondary"
          />
          <StatCard
            icon={<ChildCare />}
            title="Children"
            value={stats.totalChildren}
            change={4.5}
            color="info"
          />
          <StatCard
            icon={<TrendingUp />}
            title="Activities Today"
            value={stats.activitiesLogged}
            change={12.3}
            color="success"
          />
        </Box>

        {/* Charts Row */}
        <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '2fr 1fr' }, gap: 3, mb: 3 }}>
          <Paper sx={{ p: 3, minWidth: 500 }}>
            <Typography variant="h6" gutterBottom>
              User Growth (Last 30 Days)
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart data={userGrowthData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <Tooltip />
                <Area
                  type="monotone"
                  dataKey="users"
                  stroke="#FF8B7D"
                  fill="#FFB5A0"
                  fillOpacity={0.6}
                />
              </AreaChart>
            </ResponsiveContainer>
          </Paper>
          <Paper sx={{ p: 3, minWidth: 500 }}>
            <Typography variant="h6" gutterBottom>
              Activity Distribution
            </Typography>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={activityData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {activityData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </Paper>
        </Box>

        {/* Recent Activity and System Status */}
        <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, gap: 3 }}>
          <Paper sx={{ p: 3, minWidth: 500 }}>
            <Typography variant="h6" gutterBottom>
              Recent Users
            </Typography>
              <List>
                {recentUsers.map((user) => (
                  <ListItem key={user.id}>
                    <ListItemAvatar>
                      <Avatar sx={{ bgcolor: 'primary.main' }}>
                        {user.name.charAt(0)}
                      </Avatar>
                    </ListItemAvatar>
                    <ListItemText
                      primary={user.name}
                      secondary={user.email}
                    />
                    <Chip
                      icon={<AccessTime />}
                      label="New"
                      size="small"
                      color="success"
                      variant="outlined"
                    />
                  </ListItem>
                ))}
              </List>
            </Paper>
          <Paper sx={{ p: 3, minWidth: 500 }}>
            <Typography variant="h6" gutterBottom>
              System Status
            </Typography>
              <List>
                <ListItem>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: 'success.light' }}>
                      <CheckCircle color="success" />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary="API Server"
                    secondary="Responding normally"
                  />
                  <Chip label="Healthy" color="success" size="small" />
                </ListItem>
                <ListItem>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: 'success.light' }}>
                      <CheckCircle color="success" />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary="Database"
                    secondary="10.0.0.207 - Connected"
                  />
                  <Chip label="Healthy" color="success" size="small" />
                </ListItem>
                <ListItem>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: 'success.light' }}>
                      <CheckCircle color="success" />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary="Redis Cache"
                    secondary="Active connections: 12"
                  />
                  <Chip label="Healthy" color="success" size="small" />
                </ListItem>
                <ListItem>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: 'warning.light' }}>
                      <Warning color="warning" />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary="AI Service"
                    secondary="High usage - 85% of quota"
                  />
                  <Chip label="Warning" color="warning" size="small" />
                </ListItem>
              </List>
            </Paper>
        </Box>
      </Box>
    </AdminLayout>
  );
}