'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Button,
  Paper,
  TextField,
  FormControl,
  FormLabel,
  RadioGroup,
  FormControlLabel,
  Radio,
  IconButton,
  Alert,
  Chip,
} from '@mui/material';
import {
  ArrowBack,
  PlayArrow,
  Stop,
  Save,
  Mic,
} from '@mui/icons-material';
import { useRouter } from 'next/navigation';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { motion } from 'framer-motion';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';

const feedingSchema = z.object({
  type: z.enum(['breast_left', 'breast_right', 'breast_both', 'bottle', 'solid']),
  amount: z.number().min(0).optional(),
  unit: z.enum(['ml', 'oz']).optional(),
  notes: z.string().optional(),
});

type FeedingFormData = z.infer<typeof feedingSchema>;

export default function FeedingTrackPage() {
  const router = useRouter();
  const [isTimerRunning, setIsTimerRunning] = useState(false);
  const [duration, setDuration] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm<FeedingFormData>({
    resolver: zodResolver(feedingSchema),
    defaultValues: {
      type: 'breast_left',
      unit: 'ml',
    },
  });

  const feedingType = watch('type');

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

  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 onSubmit = async (data: FeedingFormData) => {
    setError(null);

    try {
      // TODO: Call API to save feeding data
      console.log('Feeding data:', { ...data, duration });
      setSuccess(true);
      setTimeout(() => router.push('/'), 2000);
    } catch (err: any) {
      setError(err.message || 'Failed to log feeding');
    }
  };

  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 Feeding
            </Typography>
          </Box>

          {success && (
            <Alert severity="success" sx={{ mb: 3 }}>
              Feeding logged successfully!
            </Alert>
          )}

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

          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
          >
            <Paper sx={{ p: 3, mb: 3 }}>
              {/* Timer Section */}
              <Box sx={{ textAlign: 'center', mb: 4 }}>
                <Typography variant="h2" fontWeight="600" sx={{ mb: 2 }}>
                  {formatDuration(duration)}
                </Typography>
                <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
                  {!isTimerRunning ? (
                    <Button
                      variant="contained"
                      size="large"
                      startIcon={<PlayArrow />}
                      onClick={() => setIsTimerRunning(true)}
                    >
                      Start Timer
                    </Button>
                  ) : (
                    <Button
                      variant="contained"
                      color="error"
                      size="large"
                      startIcon={<Stop />}
                      onClick={() => setIsTimerRunning(false)}
                    >
                      Stop Timer
                    </Button>
                  )}
                </Box>
              </Box>

              <Box component="form" onSubmit={handleSubmit(onSubmit)}>
                {/* Feeding Type */}
                <FormControl component="fieldset" sx={{ mb: 3, width: '100%' }}>
                  <FormLabel component="legend" sx={{ mb: 2 }}>
                    Feeding Type
                  </FormLabel>
                  <RadioGroup row>
                    <FormControlLabel
                      value="breast_left"
                      control={<Radio {...register('type')} />}
                      label="Left Breast"
                    />
                    <FormControlLabel
                      value="breast_right"
                      control={<Radio {...register('type')} />}
                      label="Right Breast"
                    />
                    <FormControlLabel
                      value="breast_both"
                      control={<Radio {...register('type')} />}
                      label="Both"
                    />
                    <FormControlLabel
                      value="bottle"
                      control={<Radio {...register('type')} />}
                      label="Bottle"
                    />
                    <FormControlLabel
                      value="solid"
                      control={<Radio {...register('type')} />}
                      label="Solid Food"
                    />
                  </RadioGroup>
                </FormControl>

                {/* Amount (for bottle/solid) */}
                {(feedingType === 'bottle' || feedingType === 'solid') && (
                  <Box sx={{ display: 'flex', gap: 2, mb: 3 }}>
                    <TextField
                      fullWidth
                      label="Amount"
                      type="number"
                      {...register('amount', { valueAsNumber: true })}
                      error={!!errors.amount}
                      helperText={errors.amount?.message}
                    />
                    <FormControl sx={{ minWidth: 120 }}>
                      <RadioGroup row>
                        <FormControlLabel
                          value="ml"
                          control={<Radio {...register('unit')} />}
                          label="ml"
                        />
                        <FormControlLabel
                          value="oz"
                          control={<Radio {...register('unit')} />}
                          label="oz"
                        />
                      </RadioGroup>
                    </FormControl>
                  </Box>
                )}

                {/* Notes */}
                <TextField
                  fullWidth
                  label="Notes (optional)"
                  multiline
                  rows={3}
                  {...register('notes')}
                  sx={{ mb: 3 }}
                />

                {/* Voice Input Button */}
                <Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
                  <Chip
                    icon={<Mic />}
                    label="Use Voice Input"
                    onClick={() => {/* TODO: Implement voice input */}}
                    sx={{ cursor: 'pointer' }}
                  />
                </Box>

                {/* Submit Button */}
                <Button
                  fullWidth
                  type="submit"
                  variant="contained"
                  size="large"
                  startIcon={<Save />}
                >
                  Save Feeding
                </Button>
              </Box>
            </Paper>
          </motion.div>
        </Box>
      </AppShell>
    </ProtectedRoute>
  );
}
