'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Typography,
  Paper,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Chip,
  CircularProgress,
  Snackbar,
  Alert,
} from '@mui/material';
import {
  Restaurant,
  Hotel,
  BabyChangingStation,
  MedicalServices,
  EmojiEvents,
  Note,
} from '@mui/icons-material';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { useAuth } from '@/lib/auth/AuthContext';
import { childrenApi, Child } from '@/lib/api/children';
import { trackingApi, Activity } from '@/lib/api/tracking';
import { format } from 'date-fns';
import { useRealTimeActivities } from '@/hooks/useWebSocket';

const activityIcons: Record<string, any> = {
  feeding: <Restaurant />,
  sleep: <Hotel />,
  diaper: <BabyChangingStation />,
  medication: <MedicalServices />,
  milestone: <EmojiEvents />,
  note: <Note />,
};

const activityColors: Record<string, string> = {
  feeding: '#FFB6C1',
  sleep: '#B6D7FF',
  diaper: '#FFE4B5',
  medication: '#FFB8B8',
  milestone: '#FFD700',
  note: '#E0E0E0',
};

export default function ActivitiesPage() {
  const { user } = useAuth();
  const [children, setChildren] = useState<Child[]>([]);
  const [selectedChild, setSelectedChild] = useState<Child | null>(null);
  const [activities, setActivities] = useState<Activity[]>([]);
  const [loading, setLoading] = useState(true);
  const [notification, setNotification] = useState<string | null>(null);

  const familyId = user?.families?.[0]?.familyId;

  // Real-time activity handlers
  const handleActivityCreated = useCallback((activity: Activity) => {
    console.log('[ActivitiesPage] Real-time activity created:', activity);
    setActivities((prev) => [activity, ...prev]);
    setNotification('New activity added by family member');
  }, []);

  const handleActivityUpdated = useCallback((activity: Activity) => {
    console.log('[ActivitiesPage] Real-time activity updated:', activity);
    setActivities((prev) =>
      prev.map((a) => (a.id === activity.id ? activity : a))
    );
    setNotification('Activity updated by family member');
  }, []);

  const handleActivityDeleted = useCallback((data: { activityId: string }) => {
    console.log('[ActivitiesPage] Real-time activity deleted:', data);
    setActivities((prev) => prev.filter((a) => a.id !== data.activityId));
    setNotification('Activity deleted by family member');
  }, []);

  // Subscribe to real-time updates
  useRealTimeActivities(
    handleActivityCreated,
    handleActivityUpdated,
    handleActivityDeleted
  );

  useEffect(() => {
    const loadData = async () => {
      if (!familyId) {
        setLoading(false);
        return;
      }

      try {
        const childrenData = await childrenApi.getChildren(familyId);
        setChildren(childrenData);

        if (childrenData.length > 0) {
          const firstChild = childrenData[0];
          setSelectedChild(firstChild);

          // Load activities for the last 7 days
          const endDate = format(new Date(), 'yyyy-MM-dd');
          const startDate = format(
            new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
            'yyyy-MM-dd'
          );

          const activitiesData = await trackingApi.getActivities(
            firstChild.id,
            undefined,
            startDate,
            endDate
          );
          setActivities(activitiesData);
        }
      } catch (error) {
        console.error('[ActivitiesPage] Failed to load data:', error);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [familyId]);

  const formatActivityTime = (timestamp: string) => {
    const date = new Date(timestamp);
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    const isToday = date.toDateString() === today.toDateString();
    const isYesterday = date.toDateString() === yesterday.toDateString();

    if (isToday) {
      return `Today at ${format(date, 'h:mm a')}`;
    } else if (isYesterday) {
      return `Yesterday at ${format(date, 'h:mm a')}`;
    } else {
      return format(date, 'MMM d, h:mm a');
    }
  };

  const getActivityDescription = (activity: Activity) => {
    switch (activity.type) {
      case 'feeding':
        return activity.data?.amount
          ? `${activity.data.amount} ${activity.data.unit || 'oz'}`
          : 'Feeding';
      case 'sleep':
        if (activity.data?.endedAt) {
          const duration = Math.floor(
            (new Date(activity.data.endedAt).getTime() -
              new Date(activity.timestamp).getTime()) /
              60000
          );
          const hours = Math.floor(duration / 60);
          const mins = duration % 60;
          return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
        }
        return 'Sleep';
      case 'diaper':
        return activity.data?.type || 'Diaper change';
      case 'medication':
        return activity.data?.name || 'Medication';
      default:
        return activity.type;
    }
  };

  return (
    <ProtectedRoute>
      <AppShell>
        <Box>
          <Typography variant="h4" component="h1" gutterBottom fontWeight="600" sx={{ mb: 3 }}>
            Recent Activities
          </Typography>

          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
              <CircularProgress />
            </Box>
          ) : activities.length === 0 ? (
            <Paper sx={{ p: 4, textAlign: 'center' }}>
              <Typography variant="body1" color="text.secondary">
                No activities recorded yet
              </Typography>
            </Paper>
          ) : (
            <Paper>
              <List>
                {activities.map((activity, index) => (
                  <ListItem
                    key={activity.id}
                    sx={{
                      borderBottom:
                        index < activities.length - 1 ? '1px solid' : 'none',
                      borderColor: 'divider',
                    }}
                  >
                    <ListItemIcon>
                      <Box
                        sx={{
                          width: 48,
                          height: 48,
                          borderRadius: 2,
                          bgcolor: activityColors[activity.type] || '#E0E0E0',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          color: 'white',
                        }}
                      >
                        {activityIcons[activity.type] || <Note />}
                      </Box>
                    </ListItemIcon>
                    <ListItemText
                      primary={
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                          <Typography variant="body1" fontWeight="500">
                            {getActivityDescription(activity)}
                          </Typography>
                          <Chip
                            label={activity.type}
                            size="small"
                            sx={{ textTransform: 'capitalize' }}
                          />
                        </Box>
                      }
                      secondary={
                        <Box>
                          <Typography variant="body2" color="text.secondary">
                            {formatActivityTime(activity.timestamp)}
                          </Typography>
                          {activity.notes && (
                            <Typography
                              variant="body2"
                              color="text.secondary"
                              sx={{ mt: 0.5 }}
                            >
                              {activity.notes}
                            </Typography>
                          )}
                        </Box>
                      }
                    />
                  </ListItem>
                ))}
              </List>
            </Paper>
          )}
        </Box>

        {/* Real-time update notification */}
        <Snackbar
          open={!!notification}
          autoHideDuration={3000}
          onClose={() => setNotification(null)}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
        >
          <Alert
            onClose={() => setNotification(null)}
            severity="info"
            sx={{ width: '100%' }}
          >
            {notification}
          </Alert>
        </Snackbar>
      </AppShell>
    </ProtectedRoute>
  );
}
