'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Button,
  Paper,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  IconButton,
  Alert,
  CircularProgress,
  Card,
  CardContent,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Chip,
  Snackbar,
} from '@mui/material';
import { FormSkeleton, ActivityListSkeleton } from '@/components/common/LoadingSkeletons';
import {
  ArrowBack,
  Refresh,
  Save,
  Delete,
  Bedtime,
  Hotel,
  DirectionsCar,
  Chair,
  Home,
  ChildCare,
  Add,
} from '@mui/icons-material';
import { useRouter } from 'next/navigation';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { useAuth } from '@/lib/auth/AuthContext';
import { trackingApi, Activity } from '@/lib/api/tracking';
import { childrenApi, Child } from '@/lib/api/children';
import { motion } from 'framer-motion';
import { useLocalizedDate } from '@/hooks/useLocalizedDate';
import { useTranslation } from '@/hooks/useTranslation';
import { useDispatch, useSelector } from 'react-redux';
import { fetchChildren, selectChild, selectSelectedChild, childrenSelectors } from '@/store/slices/childrenSlice';
import { AppDispatch, RootState } from '@/store/store';
import ChildSelector from '@/components/common/ChildSelector';

interface SleepData {
  startTime: string;
  endTime?: string;
  quality: 'excellent' | 'good' | 'fair' | 'poor';
  location: string;
  isOngoing?: boolean;
}

export default function SleepTrackPage() {
  const router = useRouter();
  const { user } = useAuth();
  const { t } = useTranslation('tracking');
  const { formatDistanceToNow, format } = useLocalizedDate();
  const dispatch = useDispatch<AppDispatch>();

  // Redux state
  const children = useSelector((state: RootState) => childrenSelectors.selectAll(state));
  const selectedChild = useSelector(selectSelectedChild);
  const familyId = user?.families?.[0]?.familyId;

  // Local state
  const [selectedChildIds, setSelectedChildIds] = useState<string[]>([]);

  // Sleep state
  const [startTime, setStartTime] = useState<string>(
    format(new Date(), "yyyy-MM-dd'T'HH:mm")
  );
  const [endTime, setEndTime] = useState<string>(
    format(new Date(), "yyyy-MM-dd'T'HH:mm")
  );
  const [quality, setQuality] = useState<'excellent' | 'good' | 'fair' | 'poor'>('good');
  const [location, setLocation] = useState<string>('crib');
  const [isOngoing, setIsOngoing] = useState<boolean>(false);

  // Common state
  const [notes, setNotes] = useState<string>('');
  const [recentSleeps, setRecentSleeps] = useState<Activity[]>([]);
  const [loading, setLoading] = useState(false);
  const [sleepsLoading, setSleepsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  // Delete confirmation dialog
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [activityToDelete, setActivityToDelete] = useState<string | null>(null);

  // Load children from Redux
  useEffect(() => {
    if (familyId && children.length === 0) {
      dispatch(fetchChildren(familyId));
    }
  }, [familyId, dispatch, children.length]);

  // Sync selectedChildIds with Redux selectedChild
  useEffect(() => {
    if (selectedChild?.id) {
      setSelectedChildIds([selectedChild.id]);
    }
  }, [selectedChild]);

  // Load recent sleeps when child is selected
  useEffect(() => {
    if (selectedChild?.id) {
      loadRecentSleeps();
    }
  }, [selectedChild?.id]);

  const loadRecentSleeps = async () => {
    if (!selectedChild?.id) return;

    try {
      setSleepsLoading(true);
      const activities = await trackingApi.getActivities(selectedChild.id, 'sleep');
      // Sort by timestamp descending and take last 10
      const sorted = activities.sort((a, b) =>
        new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
      ).slice(0, 10);
      setRecentSleeps(sorted);
    } catch (err: any) {
      console.error('Failed to load recent sleeps:', err);
    } finally {
      setSleepsLoading(false);
    }
  };

  const formatDuration = (start: string, end?: string) => {
    const startDate = new Date(start);
    const endDate = end ? new Date(end) : new Date();
    const diffMs = endDate.getTime() - startDate.getTime();

    if (diffMs < 0) return 'Invalid duration';

    const hours = Math.floor(diffMs / (1000 * 60 * 60));
    const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));

    if (hours === 0) {
      return `${minutes} minute${minutes !== 1 ? 's' : ''}`;
    } else if (minutes === 0) {
      return `${hours} hour${hours !== 1 ? 's' : ''}`;
    } else {
      return `${hours} hour${hours !== 1 ? 's' : ''} ${minutes} minute${minutes !== 1 ? 's' : ''}`;
    }
  };

  const calculateDuration = () => {
    if (!startTime) return null;
    if (isOngoing) {
      return formatDuration(startTime);
    }
    if (!endTime) return null;

    const start = new Date(startTime);
    const end = new Date(endTime);

    if (end <= start) return null;

    return formatDuration(startTime, endTime);
  };

  const setStartNow = () => {
    setStartTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
  };

  const setEndNow = () => {
    setEndTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
  };

  const handleSubmit = async () => {
    if (!selectedChild?.id) {
      setError('Please select a child');
      return;
    }

    // Validation
    if (!startTime) {
      setError('Please enter start time');
      return;
    }

    if (!isOngoing && !endTime) {
      setError('Please enter end time or mark as ongoing');
      return;
    }

    if (!isOngoing && endTime) {
      const start = new Date(startTime);
      const end = new Date(endTime);
      if (end <= start) {
        setError('End time must be after start time');
        return;
      }
    }

    try {
      setLoading(true);
      setError(null);

      const data: SleepData = {
        startTime,
        quality,
        location,
        isOngoing,
      };

      if (!isOngoing && endTime) {
        data.endTime = endTime;
      }

      await trackingApi.createActivity(selectedChild.id, {
        type: 'sleep',
        timestamp: startTime,
        data,
        notes: notes || undefined,
      });

      setSuccessMessage(t('sleep.success'));

      // Reset form
      resetForm();

      // Reload recent sleeps
      await loadRecentSleeps();
    } catch (err: any) {
      console.error('Failed to save sleep:', err);
      setError(err.response?.data?.message || 'Failed to save sleep');
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setStartTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
    setEndTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
    setQuality('good');
    setLocation('crib');
    setIsOngoing(false);
    setNotes('');
  };

  const handleDeleteClick = (activityId: string) => {
    setActivityToDelete(activityId);
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (!activityToDelete) return;

    try {
      setLoading(true);
      await trackingApi.deleteActivity(activityToDelete);
      setSuccessMessage(t('sleep.deleted'));
      setDeleteDialogOpen(false);
      setActivityToDelete(null);
      await loadRecentSleeps();
    } catch (err: any) {
      console.error('Failed to delete sleep:', err);
      setError(err.response?.data?.message || 'Failed to delete sleep');
    } finally {
      setLoading(false);
    }
  };

  const getLocationIcon = (loc: string) => {
    switch (loc) {
      case 'crib':
        return <Hotel />;
      case 'bed':
        return <Bedtime />;
      case 'stroller':
        return <DirectionsCar />;
      case 'carrier':
        return <Chair />;
      case 'other':
        return <Home />;
      default:
        return <Hotel />;
    }
  };

  const getQualityColor = (qual: string) => {
    switch (qual) {
      case 'excellent':
        return 'success';
      case 'good':
        return 'primary';
      case 'fair':
        return 'warning';
      case 'poor':
        return 'error';
      default:
        return 'default';
    }
  };

  const getSleepDetails = (activity: Activity) => {
    const data = activity.data as SleepData;
    const duration = data.endTime
      ? formatDuration(data.startTime, data.endTime)
      : data.isOngoing
        ? t('sleep.ongoing_duration', { duration: formatDuration(data.startTime) })
        : 'No end time';

    return `${duration} - ${data.location.charAt(0).toUpperCase() + data.location.slice(1)}`;
  };

  const childrenLoading = useSelector((state: RootState) => state.children.loading);

  if (childrenLoading && children.length === 0) {
    return (
      <ProtectedRoute>
        <AppShell>
          <Box>
            <Typography variant="h4" fontWeight="600" sx={{ mb: 3 }}>
              {t('sleep.title')}
            </Typography>
            <Paper sx={{ p: 3, mb: 3 }}>
              <FormSkeleton />
            </Paper>
            <Typography variant="h6" fontWeight="600" sx={{ mb: 2 }}>
              {t('sleep.title')}
            </Typography>
            <ActivityListSkeleton count={3} />
          </Box>
        </AppShell>
      </ProtectedRoute>
    );
  }

  if (!familyId || children.length === 0) {
    return (
      <ProtectedRoute>
        <AppShell>
          <Card>
            <CardContent sx={{ textAlign: 'center', py: 8 }}>
              <ChildCare sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
              <Typography variant="h6" color="text.secondary" gutterBottom>
                {t('common.noChildrenAdded')}
              </Typography>
              <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
                {t('common.noChildrenMessage')}
              </Typography>
              <Button
                variant="contained"
                startIcon={<Add />}
                onClick={() => router.push('/children')}
              >
                {t('common.addChild')}
              </Button>
            </CardContent>
          </Card>
        </AppShell>
      </ProtectedRoute>
    );
  }

  return (
    <ProtectedRoute>
      <AppShell>
        <Box>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
            <IconButton onClick={() => router.back()} sx={{ mr: 2 }}>
              <ArrowBack />
            </IconButton>
            <Typography variant="h4" fontWeight="600">
              {t('sleep.title')}
            </Typography>
          </Box>

          {error && (
            <Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
              {error}
            </Alert>
          )}

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
          >
            {/* Child Selector */}
            {children.length > 0 && (
              <Paper sx={{ p: 2, mb: 3 }}>
                <ChildSelector
                  children={children}
                  selectedChildIds={selectedChildIds}
                  onChange={(childIds) => {
                    setSelectedChildIds(childIds);
                    if (childIds.length > 0) {
                      dispatch(selectChild(childIds[0]));
                    }
                  }}
                  mode="single"
                  label={t('common.selectChild')}
                  required
                />
              </Paper>
            )}

            {/* Main Form */}
            <Paper sx={{ p: 3, mb: 3 }}>
              {/* Start Time */}
              <Box sx={{ mb: 3 }}>
                <Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }} id="start-time-label">
                  {t('sleep.startTime')}
                </Typography>
                <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
                  <TextField
                    fullWidth
                    type="datetime-local"
                    value={startTime}
                    onChange={(e) => setStartTime(e.target.value)}
                    InputLabelProps={{ shrink: true }}
                    required
                    inputProps={{
                      'aria-required': 'true',
                      'aria-labelledby': 'start-time-label',
                    }}
                  />
                  <Button variant="outlined" onClick={setStartNow} sx={{ minWidth: 100 }}>
                    {t('sleep.now')}
                  </Button>
                </Box>
              </Box>

              {/* Ongoing Checkbox */}
              <Box sx={{ mb: 3 }}>
                <FormControl fullWidth>
                  <InputLabel id="sleep-status-label">{t('sleep.status.title')}</InputLabel>
                  <Select
                    labelId="sleep-status-label"
                    value={isOngoing ? 'ongoing' : 'completed'}
                    onChange={(e) => setIsOngoing(e.target.value === 'ongoing')}
                    label={t('sleep.status.title')}
                    required
                    inputProps={{
                      'aria-required': 'true',
                    }}
                  >
                    <MenuItem value="completed">{t('sleep.status.completed')}</MenuItem>
                    <MenuItem value="ongoing">{t('sleep.status.ongoing')}</MenuItem>
                  </Select>
                </FormControl>
              </Box>

              {/* End Time */}
              {!isOngoing && (
                <Box sx={{ mb: 3 }}>
                  <Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }} id="end-time-label">
                    {t('sleep.endTime')}
                  </Typography>
                  <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
                    <TextField
                      fullWidth
                      type="datetime-local"
                      value={endTime}
                      onChange={(e) => setEndTime(e.target.value)}
                      InputLabelProps={{ shrink: true }}
                      required
                      inputProps={{
                        'aria-required': 'true',
                        'aria-labelledby': 'end-time-label',
                      }}
                    />
                    <Button variant="outlined" onClick={setEndNow} sx={{ minWidth: 100 }}>
                      {t('sleep.now')}
                    </Button>
                  </Box>
                </Box>
              )}

              {/* Duration Display */}
              {calculateDuration() && (
                <Box sx={{ mb: 3, textAlign: 'center' }}>
                  <Chip
                    label={`${t('sleep.duration')}: ${calculateDuration()}`}
                    color="primary"
                    sx={{ fontSize: '1rem', py: 3 }}
                  />
                </Box>
              )}

              {/* Sleep Quality */}
              <FormControl fullWidth sx={{ mb: 3 }}>
                <InputLabel id="sleep-quality-label">{t('sleep.quality')}</InputLabel>
                <Select
                  labelId="sleep-quality-label"
                  value={quality}
                  onChange={(e) => setQuality(e.target.value as 'excellent' | 'good' | 'fair' | 'poor')}
                  label={t('sleep.quality')}
                >
                  <MenuItem value="excellent">{t('sleep.qualities.excellent')}</MenuItem>
                  <MenuItem value="good">{t('sleep.qualities.good')}</MenuItem>
                  <MenuItem value="fair">{t('sleep.qualities.fair')}</MenuItem>
                  <MenuItem value="poor">{t('sleep.qualities.poor')}</MenuItem>
                </Select>
              </FormControl>

              {/* Location */}
              <FormControl fullWidth sx={{ mb: 3 }}>
                <InputLabel id="sleep-location-label">{t('sleep.location')}</InputLabel>
                <Select
                  labelId="sleep-location-label"
                  value={location}
                  onChange={(e) => setLocation(e.target.value)}
                  label={t('sleep.location')}
                >
                  <MenuItem value="crib">{t('sleep.locations.crib')}</MenuItem>
                  <MenuItem value="bed">{t('sleep.locations.bed')}</MenuItem>
                  <MenuItem value="stroller">{t('sleep.locations.stroller')}</MenuItem>
                  <MenuItem value="carrier">{t('sleep.locations.carrier')}</MenuItem>
                  <MenuItem value="other">{t('sleep.locations.other')}</MenuItem>
                </Select>
              </FormControl>

              {/* Common Notes Field */}
              <TextField
                fullWidth
                label={t('sleep.notes')}
                multiline
                rows={3}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                sx={{ mb: 3 }}
                placeholder={t('sleep.placeholders.notes')}
                inputProps={{
                  'aria-describedby': 'sleep-notes-helper',
                }}
                FormHelperTextProps={{
                  id: 'sleep-notes-helper',
                }}
              />

              {/* Submit Button */}
              <Button
                fullWidth
                type="button"
                variant="contained"
                size="large"
                startIcon={<Save />}
                onClick={handleSubmit}
                disabled={loading}
              >
                {loading ? t('sleep.logSleep') : t('sleep.logSleep')}
              </Button>
            </Paper>

            {/* Recent Sleeps */}
            <Paper sx={{ p: 3 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                <Typography variant="h6" fontWeight="600">
                  {t('sleep.recentSleeps')}
                </Typography>
                <IconButton onClick={loadRecentSleeps} disabled={sleepsLoading}>
                  <Refresh />
                </IconButton>
              </Box>

              {sleepsLoading ? (
                <ActivityListSkeleton count={3} />
              ) : recentSleeps.length === 0 ? (
                <Box sx={{ textAlign: 'center', py: 4 }}>
                  <Typography variant="body2" color="text.secondary">
                    {t('noEntries')}
                  </Typography>
                </Box>
              ) : (
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                  {recentSleeps.map((activity, index) => {
                    const data = activity.data as SleepData;
                    // Skip activities with invalid data structure
                    if (!data || !data.quality || !data.location) {
                      console.warn('[Sleep] Activity missing required fields:', activity);
                      return null;
                    }
                    return (
                      <motion.div
                        key={activity.id}
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.2, delay: index * 0.05 }}
                      >
                        <Card variant="outlined">
                          <CardContent>
                            <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2 }}>
                              <Box sx={{ mt: 0.5 }}>
                                {getLocationIcon(data.location)}
                              </Box>
                              <Box sx={{ flex: 1 }}>
                                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
                                  <Typography variant="body1" fontWeight="600">
                                    {t('sleep.title')}
                                  </Typography>
                                  <Chip
                                    label={data.quality.charAt(0).toUpperCase() + data.quality.slice(1)}
                                    size="small"
                                    color={getQualityColor(data.quality) as any}
                                  />
                                  <Chip
                                    label={formatDistanceToNow(new Date(activity.timestamp), { addSuffix: true })}
                                    size="small"
                                    variant="outlined"
                                  />
                                </Box>
                                <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                                  {getSleepDetails(activity)}
                                </Typography>
                                {activity.notes && (
                                  <Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>
                                    {activity.notes}
                                  </Typography>
                                )}
                              </Box>
                              <Box sx={{ display: 'flex', gap: 0.5 }}>
                                <IconButton
                                  size="small"
                                  color="error"
                                  onClick={() => handleDeleteClick(activity.id)}
                                  disabled={loading}
                                >
                                  <Delete />
                                </IconButton>
                              </Box>
                            </Box>
                          </CardContent>
                        </Card>
                      </motion.div>
                    );
                  })}
                </Box>
              )}
            </Paper>
          </motion.div>
        </Box>

        {/* Delete Confirmation Dialog */}
        <Dialog
          open={deleteDialogOpen}
          onClose={() => setDeleteDialogOpen(false)}
        >
          <DialogTitle>{t('deleteEntry')}</DialogTitle>
          <DialogContent>
            <DialogContentText>
              {t('confirmDelete')}
            </DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setDeleteDialogOpen(false)} disabled={loading}>
              {t('common.cancel')}
            </Button>
            <Button onClick={handleDeleteConfirm} color="error" disabled={loading}>
              {loading ? t('common.delete') : t('common.delete')}
            </Button>
          </DialogActions>
        </Dialog>

        {/* Success Snackbar */}
        <Snackbar
          open={!!successMessage}
          autoHideDuration={3000}
          onClose={() => setSuccessMessage(null)}
          message={successMessage}
        />
      </AppShell>
    </ProtectedRoute>
  );
}
