'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 { formatDistanceToNow, format } from 'date-fns';

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 [children, setChildren] = useState<Child[]>([]);
  const [selectedChild, setSelectedChild] = 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 [childrenLoading, setChildrenLoading] = useState(true);
  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 familyId = user?.families?.[0]?.familyId;

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

  // Load children
  useEffect(() => {
    if (familyId) {
      loadChildren();
    }
  }, [familyId]);

  // Load recent diapers when child is selected
  useEffect(() => {
    if (selectedChild) {
      loadRecentDiapers();
    }
  }, [selectedChild]);

  // 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 loadChildren = async () => {
    if (!familyId) return;

    try {
      setChildrenLoading(true);
      const childrenData = await childrenApi.getChildren(familyId);
      setChildren(childrenData);
      if (childrenData.length > 0) {
        setSelectedChild(childrenData[0].id);
      }
    } catch (err: any) {
      console.error('Failed to load children:', err);
      setError(err.response?.data?.message || 'Failed to load children');
    } finally {
      setChildrenLoading(false);
    }
  };

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

    try {
      setDiapersLoading(true);
      const activities = await trackingApi.getActivities(selectedChild, '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) {
      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, {
        type: 'diaper',
        timestamp,
        data,
        notes: notes || undefined,
      });

      setSuccessMessage('Diaper change logged successfully!');

      // 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('Diaper change deleted successfully');
      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 = data.diaperType.charAt(0).toUpperCase() + data.diaperType.slice(1);
    const conditionsLabel = data.conditions.join(', ');

    let details = `${typeLabel} - ${conditionsLabel}`;

    if (data.hasRash) {
      details += ` - Rash (${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';
    }
  };

  if (childrenLoading) {
    return (
      <ProtectedRoute>
        <AppShell>
          <Box>
            <Typography variant="h4" fontWeight="600" sx={{ mb: 3 }}>
              Track Diaper Change
            </Typography>
            <Paper sx={{ p: 3, mb: 3 }}>
              <FormSkeleton />
            </Paper>
            <Typography variant="h6" fontWeight="600" sx={{ mb: 2 }}>
              Recent Diaper Changes
            </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>
                No Children Added
              </Typography>
              <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
                You need to add a child before you can track diaper changes
              </Typography>
              <Button
                variant="contained"
                startIcon={<Add />}
                onClick={() => router.push('/children')}
              >
                Add Child
              </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">
              Track Diaper Change
            </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 > 1 && (
              <Paper sx={{ p: 2, mb: 3 }}>
                <FormControl fullWidth>
                  <InputLabel>Select Child</InputLabel>
                  <Select
                    value={selectedChild}
                    onChange={(e) => setSelectedChild(e.target.value)}
                    label="Select Child"
                  >
                    {children.map((child) => (
                      <MenuItem key={child.id} value={child.id}>
                        {child.name}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </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 }}>
                  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 }}>
                    Now
                  </Button>
                </Box>
              </Box>

              {/* Diaper Type */}
              <Box sx={{ mb: 3 }}>
                <Typography variant="subtitle1" fontWeight="600" sx={{ mb: 2 }}>
                  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">Wet</Typography>
                    </Box>
                  </ToggleButton>
                  <ToggleButton value="dirty" sx={{ py: 2 }}>
                    <Box sx={{ textAlign: 'center' }}>
                      <Typography variant="h5">💩</Typography>
                      <Typography variant="body2">Dirty</Typography>
                    </Box>
                  </ToggleButton>
                  <ToggleButton value="both" sx={{ py: 2 }}>
                    <Box sx={{ textAlign: 'center' }}>
                      <Typography variant="h5">💧💩</Typography>
                      <Typography variant="body2">Both</Typography>
                    </Box>
                  </ToggleButton>
                  <ToggleButton value="dry" sx={{ py: 2 }}>
                    <Box sx={{ textAlign: 'center' }}>
                      <Typography variant="h5">✨</Typography>
                      <Typography variant="body2">Dry</Typography>
                    </Box>
                  </ToggleButton>
                </ToggleButtonGroup>
              </Box>

              {/* Condition Selector */}
              <Box sx={{ mb: 3 }}>
                <Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
                  Condition (select all that apply)
                </Typography>
                <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                  {availableConditions.map((condition) => (
                    <Chip
                      key={condition}
                      label={condition.charAt(0).toUpperCase() + condition.slice(1)}
                      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>Diaper Rash?</InputLabel>
                <Select
                  value={hasRash ? 'yes' : 'no'}
                  onChange={(e) => setHasRash(e.target.value === 'yes')}
                  label="Diaper Rash?"
                >
                  <MenuItem value="no">No</MenuItem>
                  <MenuItem value="yes">Yes</MenuItem>
                </Select>
              </FormControl>

              {/* Rash Severity */}
              {hasRash && (
                <Box sx={{ mb: 3 }}>
                  <Alert severity="warning" sx={{ mb: 2 }}>
                    <Typography variant="body2" sx={{ mb: 1 }}>
                      Diaper rash detected. Consider applying diaper rash cream and consulting your pediatrician if it persists.
                    </Typography>
                  </Alert>
                  <FormControl fullWidth>
                    <InputLabel>Rash Severity</InputLabel>
                    <Select
                      value={rashSeverity}
                      onChange={(e) => setRashSeverity(e.target.value as 'mild' | 'moderate' | 'severe')}
                      label="Rash Severity"
                    >
                      <MenuItem value="mild">Mild</MenuItem>
                      <MenuItem value="moderate">Moderate</MenuItem>
                      <MenuItem value="severe">Severe</MenuItem>
                    </Select>
                  </FormControl>
                </Box>
              )}

              {/* Notes Field */}
              <TextField
                fullWidth
                label="Notes (optional)"
                multiline
                rows={3}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                sx={{ mb: 3 }}
                placeholder="Color, consistency, or any concerns..."
              />

              {/* Submit Button */}
              <Button
                fullWidth
                type="button"
                variant="contained"
                size="large"
                startIcon={<Save />}
                onClick={handleSubmit}
                disabled={loading}
              >
                {loading ? 'Saving...' : 'Save Diaper Change'}
              </Button>
            </Paper>

            {/* Recent Diapers */}
            <Paper sx={{ p: 3 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                <Typography variant="h6" fontWeight="600">
                  Recent Diaper Changes
                </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">
                    No diaper changes yet
                  </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">
                                    Diaper Change
                                  </Typography>
                                  <Chip
                                    label={data.diaperType.charAt(0).toUpperCase() + data.diaperType.slice(1)}
                                    size="small"
                                    sx={{
                                      bgcolor: getDiaperTypeColor(data.diaperType),
                                      color: 'white'
                                    }}
                                  />
                                  {data.hasRash && (
                                    <Chip
                                      icon={<Warning sx={{ fontSize: 16 }} />}
                                      label={`Rash: ${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>Delete Diaper Change?</DialogTitle>
          <DialogContent>
            <DialogContentText>
              Are you sure you want to delete this diaper change? This action cannot be undone.
            </DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setDeleteDialogOpen(false)} disabled={loading}>
              Cancel
            </Button>
            <Button onClick={handleDeleteConfirm} color="error" disabled={loading}>
              {loading ? 'Deleting...' : 'Delete'}
            </Button>
          </DialogActions>
        </Dialog>

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