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<typeof userSchema>

//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<User>({
    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 (
    <div className="container mx-auto py-10">
      <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>
      <Tabs defaultValue="monitoring" className="space-y-4">
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="monitoring">Monitoring</TabsTrigger>
          <TabsTrigger value="account">Account</TabsTrigger>
        </TabsList>
        <TabsContent value="monitoring">
          <Card>
            <CardHeader>
              <CardTitle>Monitoring Settings</CardTitle>
              <CardDescription>Configure your website monitoring preferences.</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleUpdateSettings} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="time-period">Check Interval</Label>
                  <Select
                    value={user.timePeriod}
                    onValueChange={(value) => setUser({ ...user, timePeriod: value as User['timePeriod'] })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select interval" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="30s">Every 30 seconds</SelectItem>
                      <SelectItem value="1m">Every 1 minute</SelectItem>
                      <SelectItem value="3m">Every 3 minutes</SelectItem>
                      <SelectItem value="5m">Every 5 minutes</SelectItem>
                      <SelectItem value="10m">Every 10 minutes</SelectItem>
                      <SelectItem value="1h">Every 1 hour</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>URLs to Monitor</Label>
                  <AnimatePresence>
                    {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)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </motion.div>
                    ))}
                  </AnimatePresence>
                  {errors.listOfUrls && <p className="text-red-500 text-sm">{errors.listOfUrls}</p>}
                  <Button type="button" onClick={addUrl} className="w-full">
                    <Plus className="h-4 w-4 mr-2" /> Add URL
                  </Button>
                </div>
                <div className="flex items-center space-x-2">
                  <Switch
                    id="monitoring-active"
                    checked={isMonitoring}
                    onCheckedChange={handleMonitoringToggle}
                    disabled={!!monitoringStatus}
                  />
                  <Label htmlFor="monitoring-active">
                    {monitoringStatus || (isMonitoring ? 'Monitoring Active' : 'Monitoring Inactive')}
                  </Label>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>
        <TabsContent value="account">
          <Card>
            <CardHeader>
              <CardTitle>Account Information</CardTitle>
              <CardDescription>Manage your account details and preferences.</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleUpdateSettings} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="username">Username</Label>
                  <Input
                    id="username"
                    value={user.username}
                    disabled
                    className="bg-gray-100 text-gray-500"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="email">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    value={user.email}
                    disabled
                    className="bg-gray-100 text-gray-500"
                  />
                </div>
                <div className="flex items-center space-x-2">
                  <Switch
                    id="email-notifications"
                    checked={user.emailSend}
                    onCheckedChange={(checked) => setUser({ ...user, emailSend: checked })}
                  />
                  <Label htmlFor="email-notifications">Receive email notifications</Label>
                </div>
              </form>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
      <div className="mt-6 flex justify-between">
        <Dialog open={showResetDialog} onOpenChange={setShowResetDialog}>
          <DialogTrigger asChild>
            <Button variant="outline">
              <RefreshCw className="h-4 w-4 mr-2" /> Reset to Defaults
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Are you sure you want to reset?</DialogTitle>
              <DialogDescription>
                This action will reset all your settings to their default values. This cannot be undone.
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <Button variant="outline" onClick={() => setShowResetDialog(false)}>Cancel</Button>
              <Button variant="destructive" onClick={resetSettings}>Reset</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
        <Button onClick={handleUpdateSettings} disabled={isSaving}>
          {isSaving ? (
            <>
              <RefreshCw className="h-4 w-4 mr-2 animate-spin" /> Saving...
            </>
          ) : (
            <>
              <Save className="h-4 w-4 mr-2" /> Save Changes
            </>
          )}
        </Button>
      </div>
      {isSaving && (
        <div className="mt-4">
          <Progress value={66} className="w-full" />
        </div>
      )}
    </div>
  )
}"""
"""
// 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<SignupResponse> => {
    const response = await api.post<SignupResponse>('/auth/signup', data);
    return response.data;
  },

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

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

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

  verifyEmail: async (token: string): Promise<VerificationResponse> => {
    const response = await api.post<VerificationResponse>('/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<AnalyticsData> => {
    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' });
    }
};

"""
"""