'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Button,
  Paper,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  IconButton,
  Alert,
  Tabs,
  Tab,
  CircularProgress,
  Card,
  CardContent,
  Divider,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Chip,
  Snackbar,
} from '@mui/material';
import {
  ArrowBack,
  PlayArrow,
  Stop,
  Refresh,
  Save,
  Restaurant,
  LocalCafe,
  Fastfood,
  Delete,
  Edit,
  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 { UnitInput } from '@/components/forms/UnitInput';
import { convertVolume, getUnitSymbol } from '@/lib/utils/unitConversion';
import { MeasurementSystem } from '@/hooks/useLocale';
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 FeedingData {
  feedingType: 'breast' | 'bottle' | 'solid';
  side?: 'left' | 'right' | 'both';
  duration?: number;
  amount?: number;
  bottleType?: 'formula' | 'breastmilk' | 'other';
  foodDescription?: string;
  amountDescription?: string;
}

function FeedingTrackPage() {
  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[]>([]);
  const [feedingType, setFeedingType] = useState<'breast' | 'bottle' | 'solid'>('breast');

  // Breastfeeding state
  const [side, setSide] = useState<'left' | 'right' | 'both'>('left');
  const [duration, setDuration] = useState<number>(0);
  const [isTimerRunning, setIsTimerRunning] = useState(false);
  const [timerSeconds, setTimerSeconds] = useState(0);

  // Bottle feeding state
  const [amount, setAmount] = useState<number>(0); // Stored in ml (metric)
  const [bottleType, setBottleType] = useState<'formula' | 'breastmilk' | 'other'>('formula');

  // Solid food state
  const [foodDescription, setFoodDescription] = useState<string>('');
  const [amountDescription, setAmountDescription] = useState<string>('');

  // Common state
  const [notes, setNotes] = useState<string>('');
  const [recentFeedings, setRecentFeedings] = useState<Activity[]>([]);
  const [loading, setLoading] = useState(false);
  const [feedingsLoading, setFeedingsLoading] = 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 feedings when child is selected
  useEffect(() => {
    if (selectedChild?.id) {
      loadRecentFeedings();
    }
  }, [selectedChild?.id]);

  // Timer effect
  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (isTimerRunning) {
      interval = setInterval(() => {
        setTimerSeconds((prev) => prev + 1);
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [isTimerRunning]);

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

    try {
      setFeedingsLoading(true);
      const activities = await trackingApi.getActivities(selectedChild.id, 'feeding');
      // 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);
      setRecentFeedings(sorted);
    } catch (err: any) {
      console.error('Failed to load recent feedings:', err);
    } finally {
      setFeedingsLoading(false);
    }
  };

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const startTimer = () => {
    setIsTimerRunning(true);
  };

  const stopTimer = () => {
    setIsTimerRunning(false);
    setDuration(Math.floor(timerSeconds / 60));
  };

  const resetTimer = () => {
    setIsTimerRunning(false);
    setTimerSeconds(0);
    setDuration(0);
  };

  const handleSubmit = async () => {
    if (!selectedChild?.id) {
      setError(t('common.selectChild'));
      return;
    }

    // Validation
    if (feedingType === 'breast' && duration === 0 && timerSeconds === 0) {
      setError(t('feeding.validation.durationRequired'));
      return;
    }

    if (feedingType === 'bottle' && !amount) {
      setError(t('feeding.validation.amountRequired'));
      return;
    }

    if (feedingType === 'solid' && !foodDescription) {
      setError(t('feeding.validation.foodRequired'));
      return;
    }

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

      const data: FeedingData = {
        feedingType,
      };

      if (feedingType === 'breast') {
        data.side = side;
        data.duration = duration || Math.floor(timerSeconds / 60);
      } else if (feedingType === 'bottle') {
        data.amount = amount; // Already in ml (metric)
        data.bottleType = bottleType;
      } else if (feedingType === 'solid') {
        data.foodDescription = foodDescription;
        data.amountDescription = amountDescription;
      }

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

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

      // Reset form
      resetForm();

      // Reload recent feedings
      await loadRecentFeedings();
    } catch (err: any) {
      console.error('Failed to save feeding:', err);
      setError(err.response?.data?.message || t('feeding.error.saveFailed'));
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setSide('left');
    setDuration(0);
    setTimerSeconds(0);
    setIsTimerRunning(false);
    setAmount(0);
    setBottleType('formula');
    setFoodDescription('');
    setAmountDescription('');
    setNotes('');
  };

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

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

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

  const getFeedingTypeIcon = (type: string) => {
    switch (type) {
      case 'breast':
        return <LocalCafe />;
      case 'bottle':
        return <Restaurant />;
      case 'solid':
        return <Fastfood />;
      default:
        return <Restaurant />;
    }
  };

  const getFeedingDetails = (activity: Activity) => {
    const data = activity.data as FeedingData;

    if (data.feedingType === 'breast') {
      return `${data.side?.toUpperCase()} - ${data.duration || 0} min`;
    } else if (data.feedingType === 'bottle') {
      // Convert amount based on user preference
      const measurementSystem: MeasurementSystem =
        (user?.preferences?.measurementUnit as MeasurementSystem) || 'metric';
      const converted = convertVolume(data.amount || 0, measurementSystem);
      const roundedValue = Math.round(converted.value * 10) / 10; // Round to 1 decimal
      return `${roundedValue} ${converted.unit} - ${data.bottleType}`;
    } else if (data.feedingType === 'solid') {
      return `${data.foodDescription}${data.amountDescription ? ` - ${data.amountDescription}` : ''}`;
    }
    return '';
  };

  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('feeding.title')}
            </Typography>
            <Paper sx={{ p: 3, mb: 3 }}>
              <FormSkeleton />
            </Paper>
            <Typography variant="h6" fontWeight="600" sx={{ mb: 2 }}>
              {t('feeding.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" sx={{ flex: 1 }}>
              {t('feeding.title')}
            </Typography>
            <VoiceInputButton
              onTranscript={(transcript) => {
                console.log('[Feeding] Voice transcript:', transcript);
              }}
              onClassifiedIntent={(result) => {
                if (result.intent === 'feeding' && result.structuredData) {
                  const data = result.structuredData;
                  // Auto-fill form with voice data
                  if (data.type === 'bottle' && data.amount) {
                    setFeedingType('bottle');
                    setAmount(typeof data.amount === 'number' ? data.amount : parseFloat(data.amount));
                  } else if (data.type?.includes('breast')) {
                    setFeedingType('breast');
                    if (data.side) setSide(data.side);
                    if (data.duration) setDuration(data.duration.toString());
                  } else if (data.type === 'solid') {
                    setFeedingType('solid');
                  }
                }
              }}
              size="medium"
            />
          </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 }}>
              {/* Feeding Type Tabs */}
              <Tabs
                value={feedingType}
                onChange={(_, newValue) => setFeedingType(newValue)}
                sx={{ mb: 3 }}
                variant="fullWidth"
              >
                <Tab label={t('feeding.types.breast')} value="breast" icon={<LocalCafe />} iconPosition="start" />
                <Tab label={t('feeding.types.bottle')} value="bottle" icon={<Restaurant />} iconPosition="start" />
                <Tab label={t('feeding.types.solid')} value="solid" icon={<Fastfood />} iconPosition="start" />
              </Tabs>

              {/* Breastfeeding Form */}
              {feedingType === 'breast' && (
                <Box>
                  {/* Timer Display */}
                  <Box sx={{ textAlign: 'center', mb: 4 }}>
                    <Typography variant="h2" fontWeight="600" sx={{ mb: 2 }}>
                      {formatDuration(timerSeconds)}
                    </Typography>
                    <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
                      {!isTimerRunning ? (
                        <Button
                          variant="contained"
                          size="large"
                          startIcon={<PlayArrow />}
                          onClick={startTimer}
                        >
                          {t('feeding.startTime')}
                        </Button>
                      ) : (
                        <Button
                          variant="contained"
                          color="error"
                          size="large"
                          startIcon={<Stop />}
                          onClick={stopTimer}
                        >
                          {t('feeding.endTime')}
                        </Button>
                      )}
                      <Button
                        variant="outlined"
                        size="large"
                        startIcon={<Refresh />}
                        onClick={resetTimer}
                      >
                        {t('feeding.reset')}
                      </Button>
                    </Box>
                  </Box>

                  {/* Side Selector */}
                  <FormControl fullWidth sx={{ mb: 3 }}>
                    <InputLabel id="side-select-label">{t('feeding.side')}</InputLabel>
                    <Select
                      labelId="side-select-label"
                      value={side}
                      onChange={(e) => setSide(e.target.value as 'left' | 'right' | 'both')}
                      label={t('feeding.side')}
                      required
                      inputProps={{
                        'aria-required': 'true',
                      }}
                    >
                      <MenuItem value="left">{t('feeding.sides.left')}</MenuItem>
                      <MenuItem value="right">{t('feeding.sides.right')}</MenuItem>
                      <MenuItem value="both">{t('feeding.sides.both')}</MenuItem>
                    </Select>
                  </FormControl>

                  {/* Manual Duration Input */}
                  <TextField
                    fullWidth
                    label={`${t('feeding.duration')} (${t('feeding.units.minutes')})`}
                    type="number"
                    value={duration || ''}
                    onChange={(e) => setDuration(parseInt(e.target.value) || 0)}
                    sx={{ mb: 3 }}
                    helperText={t('feeding.placeholders.duration')}
                    inputProps={{
                      'aria-describedby': 'duration-helper',
                      min: 0,
                    }}
                    FormHelperTextProps={{
                      id: 'duration-helper',
                    }}
                  />
                </Box>
              )}

              {/* Bottle Form */}
              {feedingType === 'bottle' && (
                <Box>
                  <UnitInput
                    fullWidth
                    label={t('feeding.amount')}
                    type="volume"
                    value={amount}
                    onChange={(metricValue) => setAmount(metricValue)}
                    sx={{ mb: 3 }}
                  />

                  <FormControl fullWidth sx={{ mb: 3 }}>
                    <InputLabel id="bottle-type-label">{t('feeding.bottleType')}</InputLabel>
                    <Select
                      labelId="bottle-type-label"
                      value={bottleType}
                      onChange={(e) => setBottleType(e.target.value as 'formula' | 'breastmilk' | 'other')}
                      label={t('feeding.bottleType')}
                      required
                      inputProps={{
                        'aria-required': 'true',
                      }}
                    >
                      <MenuItem value="formula">{t('feeding.bottleTypes.formula')}</MenuItem>
                      <MenuItem value="breastmilk">{t('feeding.bottleTypes.breastmilk')}</MenuItem>
                      <MenuItem value="other">{t('feeding.bottleTypes.other')}</MenuItem>
                    </Select>
                  </FormControl>
                </Box>
              )}

              {/* Solid Food Form */}
              {feedingType === 'solid' && (
                <Box>
                  <TextField
                    fullWidth
                    label={t('feeding.foodDescription')}
                    value={foodDescription}
                    onChange={(e) => setFoodDescription(e.target.value)}
                    sx={{ mb: 3 }}
                    placeholder={t('feeding.placeholders.foodDescription')}
                    required
                    inputProps={{
                      'aria-required': 'true',
                      'aria-invalid': !foodDescription && error ? 'true' : 'false',
                    }}
                  />

                  <TextField
                    fullWidth
                    label={t('feeding.amountDescription')}
                    value={amountDescription}
                    onChange={(e) => setAmountDescription(e.target.value)}
                    sx={{ mb: 3 }}
                    placeholder={t('feeding.placeholders.amountDescription')}
                    inputProps={{
                      'aria-describedby': 'amount-description-helper',
                    }}
                    FormHelperTextProps={{
                      id: 'amount-description-helper',
                    }}
                  />
                </Box>
              )}

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

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

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

              {feedingsLoading ? (
                <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
                  <CircularProgress size={30} />
                </Box>
              ) : recentFeedings.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 }}>
                  {recentFeedings.map((activity, index) => {
                    const data = activity.data as FeedingData;
                    // Skip activities with invalid data structure
                    if (!data || !data.feedingType) {
                      console.warn('[Feeding] Activity missing feedingType:', 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 }}>
                                {getFeedingTypeIcon(data.feedingType)}
                              </Box>
                              <Box sx={{ flex: 1 }}>
                                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
                                  <Typography variant="body1" fontWeight="600">
                                    {data.feedingType.charAt(0).toUpperCase() + data.feedingType.slice(1)}
                                  </Typography>
                                  <Chip
                                    label={formatDistanceToNow(new Date(activity.timestamp), { addSuffix: true })}
                                    size="small"
                                    variant="outlined"
                                  />
                                </Box>
                                <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                                  {getFeedingDetails(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(FeedingTrackPage, 'form');
