hye i am working in nextjs app routing ts tailwind and in route /settings i will give you the backend and services i want you to update and extend my fronted nnextjs code ot support he logic and wokring and all aporpaite worjing s and sideeffects for this frontend cend code
"""
'use client'

import { useState, useEffect } from 'react'
import { z } from 'zod'
import { motion, AnimatePresence } from 'framer-motion'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Slider } from "@/components/ui/slider"
import { toast } from "../hooks/use-toast"
import { AlertCircle, CheckCircle2, Trash2, Plus, Save, RefreshCw } from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Progress } from "@/components/ui/progress"

const userSchema = z.object({
id: z.string(),
username: z.string().min(3).max(30),
email: z.string().email().max(100),
listOfUrls: z.array(z.string().url()).min(1, "At least one URL is required"),
timePeriod: z.enum(['30s', '1m', '3m', '5m', '10m', '1h']).default('5m'),
emailSend: z.boolean().default(false),
verified: z.boolean().default(false),
})

type User = z.infer

//const mockUser: User = {
// id: '1',
// username: 'johndoe',
// email: 'john@example.com',
// listOfUrls: ['https://example.com', 'https://google.com'],
// timePeriod: '5m',
// emailSend: true,
// verified: true,
// notificationThreshold: 80,
//}

export default function SettingsPage() {
const [user, setUser] = useState({
id: '',
username: '',
email: '',
listOfUrls: [],
timePeriod: '5m',
emailSend: false,
verified: false,
})
const [isMonitoring, setIsMonitoring] = useState(false)
const [monitoringStatus, setMonitoringStatus] = useState('')
const [errors, setErrors] = useState<Partial<Record<keyof User, string>>>({})
const [isSaving, setIsSaving] = useState(false)
const [showResetDialog, setShowResetDialog] = useState(false)

const validateForm = (): boolean => {
try {
userSchema.parse(user)
setErrors({})
return true
} catch (error) {
if (error instanceof z.ZodError) {
const newErrors: Partial<Record<keyof User, string>> = {}
error.errors.forEach((err) => {
if (err.path[0]) {
newErrors[err.path[0] as keyof User] = err.message
}
})
setErrors(newErrors)
}
return false
}
}

const handleUpdateSettings = async (e: React.FormEvent) => {
e.preventDefault()
if (!validateForm()) return


setIsSaving(true)
try {
  const response = await fetch('/api/user/settings', {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      listOfUrls: user.listOfUrls,
      timePeriod: user.timePeriod,
      emailSend: user.emailSend,
    }),
  })
  const data = await response.json()
  if (response.ok) {
    setUser({ ...user, ...data.user })
    toast({
      title: "Success",
      description: data.message,
      duration: 3000,
    })
  } else {
    throw new Error(data.message || 'An error occurred while updating settings')
  }
} catch (error: any) {
  toast({
    title: "Error",
    description: error.message,
    variant: "destructive",
    duration: 5000,
  })
} finally {
  setIsSaving(false)
}
}

const handleMonitoringToggle = async () => {
try {
setMonitoringStatus('Updating...')
const response = await fetch(/api/user/monitor/${isMonitoring ? 'stop' : 'start'}, {
method: 'POST',
})
const data = await response.json()
if (response.ok) {
setIsMonitoring(!isMonitoring)
toast({
title: isMonitoring ? "Monitoring Stopped" : "Monitoring Started",
description: data.message,
duration: 3000,
})
} else {
throw new Error(data.message)
}
} catch (error: any) {
toast({
title: "Error",
description: error.message || "An error occurred while updating monitoring status",
variant: "destructive",
duration: 5000,
})
} finally {
setMonitoringStatus('')
}
}

const handleUrlChange = (index: number, value: string) => {
const newUrls = [...user.listOfUrls]
newUrls[index] = value
setUser({ ...user, listOfUrls: newUrls })
}

const addUrl = () => {
setUser({ ...user, listOfUrls: [...user.listOfUrls, ''] })
}

const removeUrl = (index: number) => {
const newUrls = user.listOfUrls.filter((_, i) => i !== index)
setUser({ ...user, listOfUrls: newUrls })
}

const resetSettings = () => {
//setUser(mockUser)
setUser({
id: '',
username: '',
email: '',
listOfUrls: [],
timePeriod: '5m',
emailSend: false,
verified: false,
})
setShowResetDialog(false)
toast({
title: "Settings Reset",
description: "Your settings have been reset to default values.",
duration: 3000,
})
}

return (


<motion.h1
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="text-4xl font-bold mb-6"
>
Account Settings
</motion.h1>


Monitoring
Account




Monitoring Settings
Configure your website monitoring preferences.




Check Interval
<Select
value={user.timePeriod}
onValueChange={(value) => setUser({ ...user, timePeriod: value as User['timePeriod'] })}
>




Every 30 seconds
Every 1 minute
Every 3 minutes
Every 5 minutes
Every 10 minutes
Every 1 hour




URLs to Monitor

{user.listOfUrls.map((url, index) => (
<motion.div
key={index}
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.2 }}
className="flex space-x-2 mb-2"
>
<Input
value={url}
onChange={(e) => handleUrlChange(index, e.target.value)}
placeholder="https://example.com"
className={errors.listOfUrls ? 'border-red-500' : ''}
/>
<Button type="button" variant="destructive" size="icon" onClick={() => removeUrl(index)}>


</motion.div>
))}

{errors.listOfUrls &&
{errors.listOfUrls}

}

Add URL











Account Information
Manage your account details and preferences.




Username
{user.username}



Email
{user.email}



<Switch
id="email-notifications"
checked={user.emailSend}
onCheckedChange={(checked) => setUser({ ...user, emailSend: checked })}
/>
Receive email notifications










Reset to Defaults




Are you sure you want to reset?

This action will reset all your settings to their default values. This cannot be undone.



<Button variant="outline" onClick={() => setShowResetDialog(false)}>Cancel
Reset




{isSaving ? (
<>
Saving...
</>
) : (
<>
Save Changes
</>
)}


{isSaving && (



)}

)
}"""
"""
// services/api.ts
import axios from 'axios'
const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api', // Adjust accordingly
headers: {
'Content-Type': 'application/json',
},
})

// Add response interceptor for error handling
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.data) {
return Promise.reject(error.response.data)
}
return Promise.reject(error)
}
)

export default api

"""
"""
// services/auth.service.ts
import api from './api';

interface SignupResponse {
message: string;
token: string;
user: {
id: string;
username: string;
email: string;
verified: boolean;
};
}

interface LoginResponse {
message: string;
token: string;
user: {
id: string;
username: string;
email: string;
verified: boolean;
};
}

interface VerificationResponse {
message: string;
verified?: boolean; // Optional, depending on backend response
}

interface ResendVerificationResponse {
message: string;
}

export const authService = {
signup: async (data: {
username: string;
email: string;
password: string;
}): Promise => {
const response = await api.post('/auth/signup', data);
return response.data;
},

login: async (identifier: string, password: string): Promise => {
const response = await api.post('/auth/login', { identifier, password });
return response.data;
},

checkVerification: async (userId: string, token: string): Promise => {
const response = await api.get(/auth/check-verification/${userId}, {
headers: {
'Authorization': Bearer ${token},
},
});
return response.data;
},

resendVerificationEmail: async (email: string): Promise => {
const response = await api.post('/auth/resend-verification', { email });
return response.data;
},

verifyEmail: async (token: string): Promise => {
const response = await api.post('/auth/verify-email', { token });
return response.data;
},

getToken: (): string | null => {
return localStorage.getItem('token');
},

logout: (): void => {
localStorage.removeItem('token');
window.location.href = '/login'; // Redirect to login page
},

};
"""
"""
// services/analytics.service.ts

import api from './api';
import { AnalyticsData } from '../types/api.types';
import { authService } from './auth.service';

export const analyticsService = {
getAnalytics: async (params: Record<string, any>): Promise => {
const token = authService.getToken();


if (!token) {
  // If no token is found, redirect to login
  authService.logout();
  throw new Error('No token found');
}

try {
  const response = await api.get<{ analytics: AnalyticsData }>('/user/analytics', {
    headers: {
      Authorization: `Bearer ${token}`,
    },
    params, // Axios automatically serializes this as query parameters
  });
  return response.data.analytics;
} catch (error: any) {
  if (error.response && (error.response.status === 403 || error.response.status === 401)) {
    // Handle unauthorized or forbidden response by logging out
    authService.logout();
  }
  throw error;
}
},
};
"""
"""
export interface ApiError {
message: string;
errors?: Array<{
field: string;
message: string;
}>;
}

export interface VerificationState {
status: 'loading' | 'success' | 'error';
message: string;
}

export interface PageProps {
params: Promise<{ token: string }>;
}

// src/types/analytics.types.ts

export interface StatusCodeDistribution {
statusCode: number;
count: number;
percentage: number; // Now a number instead of a string
}

export interface UptimePerUrl {
url: string;
successCount: number;
totalCount: number;
uptimePercentage: number; // Now a number instead of a string
}

export interface ChecksOverTime {
period: string;
count: number;
averageResponseTime: number; // Now a number representing milliseconds
}

export interface ResponseTimeDistribution {
range: string;
count: number;
averageResponseTime: number; // Now a number representing milliseconds
}

export interface TopSlowestUrl {
url: string;
averageResponseTime: number; // Now a number representing milliseconds
totalChecks: number;
}

export interface RecentIssue {
url: string;
statusCode: number;
checkedAt: string; // ISO date string
screenshotUrl?: string;
responseTime: number; // Now a number representing milliseconds
}

export interface AnalyticsData {
totalChecks: number;
successfulChecks: number;
successPercentage: number;
failedChecks: number;
failurePercentage: number;
statusCodeDistribution: StatusCodeDistribution[];
uptimePerUrl: UptimePerUrl[];
checksOverTime: ChecksOverTime[];
responseTimeDistribution: ResponseTimeDistribution[];
topSlowestUrls: TopSlowestUrl[];
recentIssues: RecentIssue[];
}
export interface DateRange {
from: Date;
to: Date;
}

"""
""
make it comeplte nad perfect bhy understnad ing hte backend
"""
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
username: { type: String, unique: true, sparse: true, minlength: 3, maxlength: 30 },
email: { type: String, unique: true, sparse: true, maxlength: 100 },
password: { type: String, required: true, minlength: 6 },
listOfUrls: { type: [String], default: [] },
timePeriod: {
type: String,
enum: ['30s', '1m', '3m', '5m', '10m', '1h'],
default: '5m'
},
emailSend: { type: Boolean, default: false },
verificationToken: { type: String },
verified: { type: Boolean, default: false },
}, { timestamps: true });

// Adding indexes for sparse unique fields
userSchema.index({ username: 1 }, { unique: true, sparse: true });
userSchema.index({ email: 1 }, { unique: true, sparse: true });

module.exports = mongoose.model('User', userSchema);
"""
"""
exports.updateSettings = async (req, res) => {
try {
// Validate input data against the schema
const parsedData = updateSettingsSchema.parse(req.body);


    // Update the user's settings in the database
    const updatedUser = await User.findByIdAndUpdate(
        req.user.id,
        { $set: parsedData },
        { new: true, runValidators: true, context: 'query' }
    );

    if (!updatedUser) {
        return res.status(404).json({ message: 'User not found' });
    }

    // If the user is verified, restart the monitoring service with the new settings
    if (updatedUser.verified) {
        try {
            monitorService.restartMonitoring(updatedUser);
        } catch (monitorError) {
            // Log the error and send a response if restarting monitoring fails
            logger.error('Restart Monitoring Error:', monitorError);
            return res.status(400).json({ message: monitorError.message });
        }
    } else {
        // If the user is not verified, log a warning and inform the user
        logger.warn(`User ${updatedUser.username} is not verified. Monitoring not started.`);
        return res.status(403).json({ message: 'Email not verified. Please verify your email to start monitoring.' });
    }

    // Send a success response with the updated user data
    res.status(200).json({ message: 'Settings updated successfully', user: updatedUser });
} catch (error) {
    if (error instanceof z.ZodError) {
        // If validation fails, send a 400 response with error details
        return res.status(400).json({ errors: error.errors });
    }
    // Handle duplicate key errors (e.g., unique email or username constraints)
    if (error.code === 11000) {
        const field = Object.keys(error.keyValue)[0];
        return res.status(400).json({ message: `${field.charAt(0).toUpperCase() + field.slice(1)} already exists` });
    }
    // Log unexpected errors and send a 500 response
    logger.error('Update Settings Error:', error);
    res.status(500).json({ message: 'Server Error' });
}
};

"""
"""



"""
/**
 * Start Monitoring
 * Route: POST /api/user/monitor/start
 *
 * Initiates the monitoring service for the user based on their settings.
 */
exports.startMonitoring = async (req, res) => {
    try {
        const user = await User.findById(req.user.id);

        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }

        if (!user.verified) {
            return res.status(403).json({ message: 'Email not verified. Please verify your email to start monitoring.' });
        }

        if (!user.listOfUrls || user.listOfUrls.length === 0) {
            return res.status(400).json({ message: 'No URLs configured for monitoring. Please add URLs to your settings.' });
        }

        // Check if monitoring is already active for the user
        const isMonitoringActive = monitorService.isMonitoringActive(user._id.toString());
        if (isMonitoringActive) {
            return res.status(400).json({ message: 'Monitoring is already active for your account.' });
        }

        // Start monitoring using the monitorService
        monitorService.startMonitoring(user);

        // Send a success response
        res.status(200).json({ message: 'Monitoring started successfully.' });
    } catch (error) {
        // Log unexpected errors and send a 500 response
        logger.error('Start Monitoring Error:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
};

/**
 * Stop Monitoring
 * Route: POST /api/user/monitor/stop
 *
 * Stops the monitoring service for the user.
 */
exports.stopMonitoring = async (req, res) => {
    try {
        const user = await User.findById(req.user.id);

        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }

        // Check if monitoring is active for the user
        const isMonitoringActive = monitorService.isMonitoringActive(user._id.toString());
        if (!isMonitoringActive) {
            return res.status(400).json({ message: 'Monitoring is not active for your account.' });
        }

        // Stop monitoring using the monitorService
        monitorService.stopMonitoring(user);

        // Send a success response
        res.status(200).json({ message: 'Monitoring stopped successfully.' });
    } catch (error) {
        // Log unexpected errors and send a 500 response
        logger.error('Stop Monitoring Error:', error);
        res.status(500).json({ message: 'Internal server error' });
    }
};
router.put('/settings', authenticate, ensureVerified, userController.updateSettings);
// **New Routes for Monitoring Control**
router.post('/monitor/start', authenticate, ensureVerified, userController.startMonitoring);
router.post('/monitor/stop', authenticate, ensureVerified, userController.stopMonitoring);


// server.js

const express = require('express');
const dotenv = require('dotenv');
const helmet = require('helmet');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const path = require('path');
const connectDB = require('./config/db');
const errorHandler = require('./middlewares/errorHandler');
const authRoutes = require('./routes/authRoutes');
const userRoutes = require('./routes/userRoutes');
const monitorService = require('./services/monitorService');
const logger = require('./utils/logger');
// Load environment variables
dotenv.config();

// Initialize Express
const app = express();

// Connect to MongoDB
connectDB();

// Middleware
app.use(express.json());
app.use(helmet());
app.use(cors({
    origin: [process.env.FRONTEND_URL],
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    credentials: true,
}));

// Rate Limiting
const authLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100, // limit each IP to 100 requests per windowMs
    message: 'Too many requests from this IP, please try again after 15 minutes',
});

app.use('/api/auth/signup', authLimiter);
app.use('/api/auth/login', authLimiter);
app.use('/api/user/settings', authLimiter);
app.use('/api/user/logs', authLimiter);

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/user', userRoutes);

// Global Error Handler
app.use(errorHandler);

// Start Monitoring for Existing Users
monitorService.initializeMonitoring();



// Start Server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    logger.info(`Server is running on port ${PORT}`);
});

// Handle graceful shutdown
const gracefulShutdown = () => {
    logger.info('Received shutdown signal. Shutting down gracefully...');
    monitorService.gracefulShutdown();

    setTimeout(() => {
        logger.info('Shutdown complete. Exiting process.');
        process.exit(0);
    }, 1000);
};

process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);