'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Paper,
  Chip,
} from '@mui/material';
import {
  TrendingUp,
  TrendingDown,
  People,
  FamilyRestroom,
  ChildCare,
  DevicesOther,
} from '@mui/icons-material';
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';

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

export default function AnalyticsPage() {
  const [timeRange, setTimeRange] = useState('7d');
  const [loading, setLoading] = useState(true);
  const [userGrowthData, setUserGrowthData] = useState<any[]>([]);
  const [activityData, setActivityData] = useState<any[]>([]);
  const [deviceData, setDeviceData] = useState<any[]>([]);
  const [ageDistribution, setAgeDistribution] = useState<any[]>([]);
  const [engagementData, setEngagementData] = useState<any[]>([]);
  const [stats, setStats] = useState<Stat[]>([
    {
      title: 'Total Users',
      value: 0,
      change: 12.5,
      icon: <People />,
      color: 'primary.main',
    },
    {
      title: 'Active Families',
      value: 0,
      change: 8.3,
      icon: <FamilyRestroom />,
      color: 'success.main',
    },
    {
      title: 'Total Children',
      value: 0,
      change: 15.2,
      icon: <ChildCare />,
      color: 'info.main',
    },
    {
      title: 'Connected Devices',
      value: 0,
      change: -2.1,
      icon: <DevicesOther />,
      color: 'warning.main',
    },
  ]);

  useEffect(() => {
    fetchAnalyticsData();
  }, [timeRange]);

  const fetchAnalyticsData = async () => {
    setLoading(true);
    try {
      const days = timeRange === '24h' ? 1 : timeRange === '7d' ? 7 : timeRange === '30d' ? 30 : 90;

      const [
        statsRes,
        growthRes,
        devicesRes,
        activityRes,
        ageRes,
        engagementRes,
      ] = await Promise.all([
        apiClient.get('/admin/dashboard/stats'),
        apiClient.get(`/admin/dashboard/analytics/user-growth?days=${days}`),
        apiClient.get('/admin/dashboard/analytics/device-distribution'),
        apiClient.get(`/admin/dashboard/analytics/activity-by-day?days=${days}`),
        apiClient.get('/admin/dashboard/analytics/age-distribution'),
        apiClient.get(`/admin/dashboard/analytics/engagement-pattern?days=${days}`),
      ]);

      // Update stats
      setStats([
        {
          title: 'Total Users',
          value: statsRes.totalUsers.toLocaleString(),
          change: 12.5,
          icon: <People />,
          color: 'primary.main',
        },
        {
          title: 'Active Families',
          value: statsRes.totalFamilies.toLocaleString(),
          change: 8.3,
          icon: <FamilyRestroom />,
          color: 'success.main',
        },
        {
          title: 'Total Children',
          value: statsRes.totalChildren.toLocaleString(),
          change: 15.2,
          icon: <ChildCare />,
          color: 'info.main',
        },
        {
          title: 'Connected Devices',
          value: '324',
          change: -2.1,
          icon: <DevicesOther />,
          color: 'warning.main',
        },
      ]);

      setUserGrowthData(growthRes);
      setDeviceData(devicesRes);
      setActivityData(activityRes);
      setAgeDistribution(ageRes);
      setEngagementData(engagementRes);
    } catch (error) {
      console.error('Failed to fetch analytics:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <AdminLayout>
      <Box sx={{ mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Box>
            <Typography variant="h4" gutterBottom sx={{ fontWeight: 600 }}>
              Analytics Dashboard
            </Typography>
            <Typography variant="body1" color="text.secondary">
              Platform usage metrics and insights
            </Typography>
          </Box>
          <FormControl size="small" sx={{ minWidth: 120 }}>
            <InputLabel>Time Range</InputLabel>
            <Select
              value={timeRange}
              label="Time Range"
              onChange={(e) => setTimeRange(e.target.value)}
            >
              <MenuItem value="24h">Last 24 Hours</MenuItem>
              <MenuItem value="7d">Last 7 Days</MenuItem>
              <MenuItem value="30d">Last 30 Days</MenuItem>
              <MenuItem value="90d">Last 90 Days</MenuItem>
            </Select>
          </FormControl>
        </Box>
      </Box>

      {/* Stats Cards */}
      <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 3, mb: 4 }}>
        {stats.map((stat) => (
          <Card key={stat.title}>
            <CardContent>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <Box>
                  <Typography color="text.secondary" gutterBottom variant="body2">
                    {stat.title}
                  </Typography>
                  <Typography variant="h4" sx={{ fontWeight: 600, mb: 1 }}>
                    {stat.value}
                  </Typography>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                    {stat.change > 0 ? (
                      <TrendingUp sx={{ fontSize: 20, color: 'success.main' }} />
                    ) : (
                      <TrendingDown sx={{ fontSize: 20, color: 'error.main' }} />
                    )}
                    <Typography
                      variant="body2"
                      sx={{
                        color: stat.change > 0 ? 'success.main' : 'error.main',
                      }}
                    >
                      {Math.abs(stat.change)}%
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      vs last period
                    </Typography>
                  </Box>
                </Box>
                <Box
                  sx={{
                    p: 1,
                    borderRadius: 2,
                    bgcolor: `${stat.color}15`,
                    color: stat.color,
                  }}
                >
                  {stat.icon}
                </Box>
              </Box>
            </CardContent>
          </Card>
        ))}
      </Box>

      {/* Charts Row 1 */}
      <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '2fr 1fr' }, gap: 3, mb: 4 }}>
        <Paper sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            User & Family Growth
          </Typography>
          <ResponsiveContainer width="100%" height={300}>
            <LineChart data={userGrowthData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="date" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Line
                type="monotone"
                dataKey="users"
                stroke="#FF8B7D"
                strokeWidth={2}
                name="Users"
              />
              <Line
                type="monotone"
                dataKey="families"
                stroke="#81C784"
                strokeWidth={2}
                name="Families"
              />
            </LineChart>
          </ResponsiveContainer>
        </Paper>

        <Paper sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            Device Distribution
          </Typography>
          <ResponsiveContainer width="100%" height={300}>
            <PieChart>
              <Pie
                data={deviceData}
                cx="50%"
                cy="50%"
                labelLine={false}
                label={(entry) => `${entry.name}: ${entry.value}%`}
                outerRadius={80}
                fill="#8884d8"
                dataKey="value"
              >
                {deviceData.map((entry, index) => (
                  <Cell key={`cell-${index}`} fill={entry.color} />
                ))}
              </Pie>
              <Tooltip />
            </PieChart>
          </ResponsiveContainer>
        </Paper>
      </Box>

      {/* Charts Row 2 */}
      <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1.4fr 1fr' }, gap: 3, mb: 4 }}>
        <Paper sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            Activity Types by Day
          </Typography>
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={activityData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="day" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Bar dataKey="feeding" fill="#FFB5A0" name="Feeding" />
              <Bar dataKey="sleep" fill="#81C784" name="Sleep" />
              <Bar dataKey="diapers" fill="#64B5F6" name="Diapers" />
            </BarChart>
          </ResponsiveContainer>
        </Paper>

        <Paper sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            Children Age Distribution
          </Typography>
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={ageDistribution} layout="horizontal">
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis type="number" />
              <YAxis dataKey="age" type="category" />
              <Tooltip />
              <Bar dataKey="count" fill="#FFD4CC" />
            </BarChart>
          </ResponsiveContainer>
        </Paper>
      </Box>

      {/* Engagement Chart */}
      <Paper sx={{ p: 3 }}>
        <Typography variant="h6" gutterBottom>
          Daily Engagement Pattern
        </Typography>
        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
          Average sessions by hour of day
        </Typography>
        <ResponsiveContainer width="100%" height={250}>
          <AreaChart data={engagementData}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="hour" />
            <YAxis />
            <Tooltip />
            <Area
              type="monotone"
              dataKey="sessions"
              stroke="#FF8B7D"
              fill="#FFB5A0"
              fillOpacity={0.6}
            />
          </AreaChart>
        </ResponsiveContainer>
      </Paper>
    </AdminLayout>
  );
}