'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 {
  ArrowBack,
  Save,
  TrendingUp,
  Delete,
  Refresh,
  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 { withErrorBoundary } from '@/components/common/ErrorFallbacks';
import { useAuth } from '@/lib/auth/AuthContext';
import { trackingApi, Activity } from '@/lib/api/tracking';
import { childrenApi, Child } from '@/lib/api/children';
import { VoiceInputButton } from '@/components/voice/VoiceInputButton';
import { FormSkeleton, ActivityListSkeleton } from '@/components/common/LoadingSkeletons';
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';
import { UnitInput } from '@/components/forms/UnitInput';
import { useErrorMessage } from '@/components/common/ErrorMessage';
import { formatErrorMessage } from '@/lib/utils/errorHandler';

interface GrowthData {
  weight?: number; // in kg
  height?: number; // in cm
  headCircumference?: number; // in cm
  measurementType: 'weight' | 'height' | 'head' | 'all';
}

function GrowthTrackPage() {
  const router = useRouter();
  const { user } = useAuth();
  const { t } = useTranslation('tracking');
  const { formatDistanceToNow } = 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[]>([]);

  // Growth state
  const [measurementType, setMeasurementType] = useState<'weight' | 'height' | 'head' | 'all'>('weight');
  const [weight, setWeight] = useState<number>(0);
  const [height, setHeight] = useState<number>(0);
  const [headCircumference, setHeadCircumference] = useState<number>(0);

  // Common state
  const [notes, setNotes] = useState<string>('');
  const [recentGrowth, setRecentGrowth] = useState<Activity[]>([]);
  const [loading, setLoading] = useState(false);
  const [growthLoading, setGrowthLoading] = useState(false);
  const { error, showError, clearError, hasError } = useErrorMessage();
  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 growth when child is selected
  useEffect(() => {
    if (selectedChild?.id) {
      loadRecentGrowth();
    }
  }, [selectedChild?.id]);


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

    try {
      setGrowthLoading(true);
      const activities = await trackingApi.getActivities(selectedChild.id, 'growth');
      const sorted = activities.sort((a, b) =>
        new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
      ).slice(0, 10);
      setRecentGrowth(sorted);
    } catch (err: any) {
      console.error('Failed to load recent growth:', err);
    } finally {
      setGrowthLoading(false);
    }
  };

  const handleSubmit = async () => {
    if (!selectedChild?.id) {
      showError({ message: t('common.selectChild'), code: 'NO_CHILD_SELECTED' });
      return;
    }

    // Validation
    if (measurementType === 'weight' && weight === 0) {
      showError({ message: 'Please enter weight', code: 'VALIDATION_ERROR' });
      return;
    }
    if (measurementType === 'height' && height === 0) {
      showError({ message: 'Please enter height', code: 'VALIDATION_ERROR' });
      return;
    }
    if (measurementType === 'head' && headCircumference === 0) {
      showError({ message: 'Please enter head circumference', code: 'VALIDATION_ERROR' });
      return;
    }
    if (measurementType === 'all' && (weight === 0 || height === 0 || headCircumference === 0)) {
      showError({ message: 'Please enter all measurements', code: 'VALIDATION_ERROR' });
      return;
    }

    try {
      setLoading(true);
      clearError();

      const data: GrowthData = {
        measurementType,
        ...(measurementType === 'weight' || measurementType === 'all' ? { weight } : {}),
        ...(measurementType === 'height' || measurementType === 'all' ? { height } : {}),
        ...(measurementType === 'head' || measurementType === 'all' ? { headCircumference } : {}),
      };

      await trackingApi.createActivity(selectedChild.id, {
        type: 'growth',
        timestamp: new Date().toISOString(),
        data,
        notes: notes || undefined,
      });

      setSuccessMessage('Growth measurement logged successfully!');

      // Reset form
      resetForm();

      // Reload recent growth
      await loadRecentGrowth();
    } catch (err: any) {
      console.error('Failed to save growth:', err);
      showError(err);
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setWeight(0);
    setHeight(0);
    setHeadCircumference(0);
    setMeasurementType('weight');
    setNotes('');
  };

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

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

    try {
      setLoading(true);
      await trackingApi.deleteActivity(activityToDelete);
      setSuccessMessage('Growth measurement deleted successfully');
      setDeleteDialogOpen(false);
      setActivityToDelete(null);
      await loadRecentGrowth();
    } catch (err: any) {
      console.error('Failed to delete growth:', err);
      showError(err);
    } finally {
      setLoading(false);
    }
  };

  const getGrowthDetails = (activity: Activity) => {
    const data = activity.data as GrowthData;
    const details: string[] = [];

    if (data.weight) {
      const measurementSystem = (user?.preferences?.measurementUnit as 'metric' | 'imperial') || 'metric';
      if (measurementSystem === 'imperial') {
        const lbs = (data.weight * 2.20462).toFixed(1);
        details.push(`Weight: ${lbs} lbs`);
      } else {
        details.push(`Weight: ${data.weight} kg`);
      }
    }

    if (data.height) {
      const measurementSystem = (user?.preferences?.measurementUnit as 'metric' | 'imperial') || 'metric';
      if (measurementSystem === 'imperial') {
        const inches = (data.height * 0.393701).toFixed(1);
        details.push(`Height: ${inches} in`);
      } else {
        details.push(`Height: ${data.height} cm`);
      }
    }

    if (data.headCircumference) {
      const measurementSystem = (user?.preferences?.measurementUnit as 'metric' | 'imperial') || 'metric';
      if (measurementSystem === 'imperial') {
        const inches = (data.headCircumference * 0.393701).toFixed(1);
        details.push(`Head: ${inches} in`);
      } else {
        details.push(`Head: ${data.headCircumference} cm`);
      }
    }

    return details.join(' | ');
  };

  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('activities.growth')}
            </Typography>
            <Paper sx={{ p: 3, mb: 3 }}>
              <FormSkeleton />
            </Paper>
            <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" sx={{ flex: 1 }}>
              {t('activities.growth')}
            </Typography>
            <VoiceInputButton
              onTranscript={(transcript) => {
                console.log('[Growth] Voice transcript:', transcript);
              }}
              onClassifiedIntent={(result) => {
                console.log('[Growth] Intent:', result);
              }}
              size="medium"
            />
          </Box>

          {hasError && (
            <Alert severity="error" sx={{ mb: 3 }} onClose={clearError}>
              {formatErrorMessage(error)}
            </Alert>
          )}

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
          >
            {/* Child Selector */}
            {children.length > 1 && (
              <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 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
                <TrendingUp sx={{ fontSize: 36, color: '#7B1FA2', mr: 2 }} />
                <Typography variant="h6" fontWeight="600">
                  Growth Measurement
                </Typography>
              </Box>

              <FormControl fullWidth sx={{ mb: 3 }}>
                <InputLabel>Measurement Type</InputLabel>
                <Select
                  value={measurementType}
                  onChange={(e) => setMeasurementType(e.target.value as 'weight' | 'height' | 'head' | 'all')}
                  label="Measurement Type"
                >
                  <MenuItem value="weight">Weight Only</MenuItem>
                  <MenuItem value="height">Height Only</MenuItem>
                  <MenuItem value="head">Head Circumference Only</MenuItem>
                  <MenuItem value="all">All Measurements</MenuItem>
                </Select>
              </FormControl>

              {(measurementType === 'weight' || measurementType === 'all') && (
                <UnitInput
                  fullWidth
                  label="Weight"
                  type="weight"
                  value={weight}
                  onChange={(metricValue) => setWeight(metricValue)}
                  required
                  sx={{ mb: 3 }}
                />
              )}

              {(measurementType === 'height' || measurementType === 'all') && (
                <UnitInput
                  fullWidth
                  label="Height"
                  type="length"
                  value={height}
                  onChange={(metricValue) => setHeight(metricValue)}
                  required
                  sx={{ mb: 3 }}
                />
              )}

              {(measurementType === 'head' || measurementType === 'all') && (
                <UnitInput
                  fullWidth
                  label="Head Circumference"
                  type="length"
                  value={headCircumference}
                  onChange={(metricValue) => setHeadCircumference(metricValue)}
                  required
                  sx={{ mb: 3 }}
                />
              )}

              <TextField
                fullWidth
                label={t('feeding.notes')}
                multiline
                rows={3}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                sx={{ mb: 3 }}
                placeholder="Add any notes about this measurement..."
              />

              <Button
                fullWidth
                type="button"
                variant="contained"
                size="large"
                startIcon={<Save />}
                onClick={handleSubmit}
                disabled={loading}
              >
                {loading ? t('common.loading') : 'Log Growth Measurement'}
              </Button>
            </Paper>

            {/* Recent Growth */}
            <Paper sx={{ p: 3 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                <Typography variant="h6" fontWeight="600">
                  Recent Growth Measurements
                </Typography>
                <IconButton onClick={loadRecentGrowth} disabled={growthLoading}>
                  <Refresh />
                </IconButton>
              </Box>

              {growthLoading ? (
                <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
                  <CircularProgress size={30} />
                </Box>
              ) : recentGrowth.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 }}>
                  {recentGrowth.map((activity, index) => (
                    <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 }}>
                              <TrendingUp color="secondary" />
                            </Box>
                            <Box sx={{ flex: 1 }}>
                              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
                                <Typography variant="body1" fontWeight="600">
                                  Growth Measurement
                                </Typography>
                                <Chip
                                  label={formatDistanceToNow(new Date(activity.timestamp), { addSuffix: true })}
                                  size="small"
                                  variant="outlined"
                                />
                              </Box>
                              <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                                {getGrowthDetails(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.loading') : t('common.delete')}
            </Button>
          </DialogActions>
        </Dialog>

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

export default withErrorBoundary(GrowthTrackPage, 'form');
