'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,
  ToggleButtonGroup,
  ToggleButton,
  FormLabel,
} from '@mui/material';
import { FormSkeleton, ActivityListSkeleton } from '@/components/common/LoadingSkeletons';
import {
  ArrowBack,
  Refresh,
  Save,
  Delete,
  BabyChangingStation,
  Warning,
  CheckCircle,
  ChildCare,
  Add,
} from '@mui/icons-material';
import { useRouter, useSearchParams } 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 DiaperData {
  diaperType: 'wet' | 'dirty' | 'both' | 'dry';
  conditions: string[];
  hasRash: boolean;
  rashSeverity?: 'mild' | 'moderate' | 'severe';
}

export default function DiaperTrackPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  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[]>([]);

  // Diaper state
  const [timestamp, setTimestamp] = useState<string>(
    format(new Date(), "yyyy-MM-dd'T'HH:mm")
  );
  const [diaperType, setDiaperType] = useState<'wet' | 'dirty' | 'both' | 'dry'>('wet');
  const [conditions, setConditions] = useState<string[]>(['normal']);
  const [hasRash, setHasRash] = useState<boolean>(false);
  const [rashSeverity, setRashSeverity] = useState<'mild' | 'moderate' | 'severe'>('mild');

  // Common state
  const [notes, setNotes] = useState<string>('');
  const [recentDiapers, setRecentDiapers] = useState<Activity[]>([]);
  const [loading, setLoading] = useState(false);
  const [diapersLoading, setDiapersLoading] = 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);

  const availableConditions = [
    'normal',
    'soft',
    'hard',
    'watery',
    'mucus',
    'blood',
  ];

  // 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 diapers when child is selected
  useEffect(() => {
    if (selectedChild?.id) {
      loadRecentDiapers();
    }
  }, [selectedChild?.id]);

  // Pre-fill form from URL parameters (voice command)
  useEffect(() => {
    const type = searchParams.get('type');
    const timestampParam = searchParams.get('timestamp');
    const notesParam = searchParams.get('notes');
    const rashParam = searchParams.get('rash');
    const colorParam = searchParams.get('color');
    const consistencyParam = searchParams.get('consistency');

    if (type) {
      // Map backend type values to frontend diaperType
      const typeMap: Record<string, 'wet' | 'dirty' | 'both' | 'dry'> = {
        'wet': 'wet',
        'dirty': 'dirty',
        'both': 'both',
        'dry': 'dry',
      };
      if (type in typeMap) {
        setDiaperType(typeMap[type]);
      }
    }

    if (timestampParam) {
      try {
        const date = new Date(timestampParam);
        setTimestamp(format(date, "yyyy-MM-dd'T'HH:mm"));
      } catch (e) {
        console.warn('[Diaper] Invalid timestamp from URL:', timestampParam);
      }
    }

    if (notesParam) {
      setNotes(notesParam);
    }

    if (rashParam) {
      setHasRash(rashParam === 'true');
    }

    // Map color and consistency to conditions
    const newConditions: string[] = [];
    if (colorParam && availableConditions.includes(colorParam)) {
      newConditions.push(colorParam);
    }
    if (consistencyParam && availableConditions.includes(consistencyParam)) {
      newConditions.push(consistencyParam);
    }
    if (newConditions.length > 0) {
      setConditions(newConditions);
    }
  }, [searchParams]);

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

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

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

  const handleConditionToggle = (condition: string) => {
    setConditions((prev) => {
      if (prev.includes(condition)) {
        // Remove condition, but ensure at least one remains
        if (prev.length === 1) return prev;
        return prev.filter((c) => c !== condition);
      } else {
        return [...prev, condition];
      }
    });
  };

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

    // Validation
    if (!timestamp) {
      setError('Please enter timestamp');
      return;
    }

    if (conditions.length === 0) {
      setError('Please select at least one condition');
      return;
    }

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

      const data: DiaperData = {
        diaperType,
        conditions,
        hasRash,
      };

      if (hasRash) {
        data.rashSeverity = rashSeverity;
      }

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

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

      // Reset form
      resetForm();

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

  const resetForm = () => {
    setTimestamp(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
    setDiaperType('wet');
    setConditions(['normal']);
    setHasRash(false);
    setRashSeverity('mild');
    setNotes('');
  };

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

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

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

  const getDiaperTypeColor = (type: string) => {
    switch (type) {
      case 'wet':
        return '#2196f3'; // blue
      case 'dirty':
        return '#795548'; // brown
      case 'both':
        return '#ff9800'; // orange
      case 'dry':
        return '#4caf50'; // green
      default:
        return '#757575'; // grey
    }
  };

  const getDiaperTypeIcon = (type: string) => {
    switch (type) {
      case 'wet':
        return '💧';
      case 'dirty':
        return '💩';
      case 'both':
        return '💧💩';
      case 'dry':
        return '✨';
      default:
        return '🍼';
    }
  };

  const getDiaperDetails = (activity: Activity) => {
    const data = activity.data as DiaperData;
    const typeLabel = t(`diaper.types.${data.diaperType}`);
    const conditionsLabel = data.conditions?.map(c => t(`diaper.conditions.${c}`)).join(', ') || '';

    let details = typeLabel;
    if (conditionsLabel) {
      details += ` - ${conditionsLabel}`;
    }

    if (data.hasRash) {
      details += ` - ${t('diaper.rash.title')} (${t(`diaper.rash.severities.${data.rashSeverity}`)})`;
    }

    return details;
  };

  const getRashSeverityColor = (severity: string) => {
    switch (severity) {
      case 'mild':
        return 'warning';
      case 'moderate':
        return 'error';
      case 'severe':
        return 'error';
      default:
        return 'default';
    }
  };

  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('diaper.title')}
            </Typography>
            <Paper sx={{ p: 3, mb: 3 }}>
              <FormSkeleton />
            </Paper>
            <Typography variant="h6" fontWeight="600" sx={{ mb: 2 }}>
              {t('diaper.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('diaper.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 }}>
              {/* Icon Header */}
              <Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
                <BabyChangingStation sx={{ fontSize: 64, color: 'primary.main' }} />
              </Box>

              {/* Timestamp */}
              <Box sx={{ mb: 3 }}>
                <Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
                  {t('diaper.time')}
                </Typography>
                <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
                  <TextField
                    fullWidth
                    type="datetime-local"
                    value={timestamp}
                    onChange={(e) => setTimestamp(e.target.value)}
                    InputLabelProps={{ shrink: true }}
                  />
                  <Button variant="outlined" onClick={setTimeNow} sx={{ minWidth: 100 }}>
                    {t('diaper.now')}
                  </Button>
                </Box>
              </Box>

              {/* Diaper Type */}
              <Box sx={{ mb: 3 }}>
                <Typography variant="subtitle1" fontWeight="600" sx={{ mb: 2 }}>
                  {t('diaper.type')}
                </Typography>
                <ToggleButtonGroup
                  value={diaperType}
                  exclusive
                  onChange={(_, value) => {
                    if (value !== null) {
                      setDiaperType(value);
                    }
                  }}
                  fullWidth
                >
                  <ToggleButton value="wet" sx={{ py: 2 }}>
                    <Box sx={{ textAlign: 'center' }}>
                      <Typography variant="h5">💧</Typography>
                      <Typography variant="body2">{t('diaper.types.wet')}</Typography>
                    </Box>
                  </ToggleButton>
                  <ToggleButton value="dirty" sx={{ py: 2 }}>
                    <Box sx={{ textAlign: 'center' }}>
                      <Typography variant="h5">💩</Typography>
                      <Typography variant="body2">{t('diaper.types.dirty')}</Typography>
                    </Box>
                  </ToggleButton>
                  <ToggleButton value="both" sx={{ py: 2 }}>
                    <Box sx={{ textAlign: 'center' }}>
                      <Typography variant="h5">💧💩</Typography>
                      <Typography variant="body2">{t('diaper.types.both')}</Typography>
                    </Box>
                  </ToggleButton>
                  <ToggleButton value="dry" sx={{ py: 2 }}>
                    <Box sx={{ textAlign: 'center' }}>
                      <Typography variant="h5">✨</Typography>
                      <Typography variant="body2">{t('diaper.types.dry')}</Typography>
                    </Box>
                  </ToggleButton>
                </ToggleButtonGroup>
              </Box>

              {/* Condition Selector */}
              <Box sx={{ mb: 3 }}>
                <Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
                  {t('diaper.conditions.title')}
                </Typography>
                <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                  {availableConditions.map((condition) => (
                    <Chip
                      key={condition}
                      label={t(`diaper.conditions.${condition}`)}
                      onClick={() => handleConditionToggle(condition)}
                      color={conditions.includes(condition) ? 'primary' : 'default'}
                      variant={conditions.includes(condition) ? 'filled' : 'outlined'}
                      sx={{ cursor: 'pointer' }}
                    />
                  ))}
                </Box>
              </Box>

              {/* Rash Indicator */}
              <FormControl fullWidth sx={{ mb: 3 }}>
                <InputLabel>{t('diaper.rash.title')}</InputLabel>
                <Select
                  value={hasRash ? 'yes' : 'no'}
                  onChange={(e) => setHasRash(e.target.value === 'yes')}
                  label={t('diaper.rash.title')}
                >
                  <MenuItem value="no">{t('diaper.rash.no')}</MenuItem>
                  <MenuItem value="yes">{t('diaper.rash.yes')}</MenuItem>
                </Select>
              </FormControl>

              {/* Rash Severity */}
              {hasRash && (
                <Box sx={{ mb: 3 }}>
                  <Alert severity="warning" sx={{ mb: 2 }}>
                    <Typography variant="body2" sx={{ mb: 1 }}>
                      {t('diaper.rash.alert')}
                    </Typography>
                  </Alert>
                  <FormControl fullWidth>
                    <InputLabel>{t('diaper.rash.severity')}</InputLabel>
                    <Select
                      value={rashSeverity}
                      onChange={(e) => setRashSeverity(e.target.value as 'mild' | 'moderate' | 'severe')}
                      label={t('diaper.rash.severity')}
                    >
                      <MenuItem value="mild">{t('diaper.rash.severities.mild')}</MenuItem>
                      <MenuItem value="moderate">{t('diaper.rash.severities.moderate')}</MenuItem>
                      <MenuItem value="severe">{t('diaper.rash.severities.severe')}</MenuItem>
                    </Select>
                  </FormControl>
                </Box>
              )}

              {/* Notes Field */}
              <TextField
                fullWidth
                label={t('diaper.notes')}
                multiline
                rows={3}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                sx={{ mb: 3 }}
                placeholder={t('diaper.placeholders.notes')}
              />

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

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

              {diapersLoading ? (
                <ActivityListSkeleton count={3} />
              ) : recentDiapers.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 }}>
                  {recentDiapers.map((activity, index) => {
                    const data = activity.data as DiaperData;
                    // Skip activities with invalid data structure
                    if (!data || !data.diaperType) {
                      console.warn('[Diaper] Activity missing diaperType:', 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, fontSize: '2rem' }}>
                                {getDiaperTypeIcon(data.diaperType)}
                              </Box>
                              <Box sx={{ flex: 1 }}>
                                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
                                  <Typography variant="body1" fontWeight="600">
                                    {t('diaper.title')}
                                  </Typography>
                                  <Chip
                                    label={t(`diaper.types.${data.diaperType}`)}
                                    size="small"
                                    sx={{
                                      bgcolor: getDiaperTypeColor(data.diaperType),
                                      color: 'white'
                                    }}
                                  />
                                  {data.hasRash && (
                                    <Chip
                                      icon={<Warning sx={{ fontSize: 16 }} />}
                                      label={`${t('diaper.rash.title')}: ${t(`diaper.rash.severities.${data.rashSeverity}`)}`}
                                      size="small"
                                      color={getRashSeverityColor(data.rashSeverity || 'mild') 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 }}>
                                  {getDiaperDetails(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>
  );
}
