import * as React from "react";
import { useForm, Controller, SubmitHandler } from "react-hook-form";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
// import Checkbox from '@mui/material/Checkbox';
// import CssBaseline from '@mui/material/CssBaseline';
import Divider from "@mui/material/Divider";
// import FormControlLabel from '@mui/material/FormControlLabel';
import FormLabel from "@mui/material/FormLabel";
import FormControl from "@mui/material/FormControl";
import Link from "@mui/material/Link";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import MuiCard from "@mui/material/Card";
import { styled } from "@mui/material/styles";
import AppTheme from "../../../shared-theme/AppTheme.tsx";
// import { GoogleIcon, FacebookIcon, SitemarkIcon } from './CustomIcons.tsx';
import ColorModeSelect from "../../../shared-theme/ColorModeSelect.tsx";
import MuiPhoneNumber from "mui-phone-number";
import { useDispatch } from "react-redux";
import { registerUser } from "../../../redux/slices/authSlice.ts";
import { toast } from "sonner";
import { InputLabel, MenuItem, Select } from "@mui/material";
import { useNavigate } from "react-router-dom";

const Card = styled(MuiCard)(({ theme }) => ({
	display: "flex",
	flexDirection: "column",
	alignSelf: "center",
	width: "100%",
	padding: theme.spacing(4),
	gap: theme.spacing(2),
	margin: "auto",
	boxShadow:
		"hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px",
	[theme.breakpoints.up("sm")]: {
		width: "450px",
	},
	...theme.applyStyles("dark", {
		boxShadow:
			"hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px",
	}),
}));

const SignUpContainer = styled(Stack)(({ theme }) => ({
	height: "calc((1 - var(--template-frame-height, 0)) * 100dvh)",
	minHeight: "100%",
	padding: theme.spacing(2),
	[theme.breakpoints.up("sm")]: {
		padding: theme.spacing(4),
	},
	"&::before": {
		content: '""',
		display: "block",
		position: "absolute",
		zIndex: -1,
		inset: 0,
		backgroundImage:
			"radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))",
		backgroundRepeat: "no-repeat",
		...theme.applyStyles("dark", {
			backgroundImage:
				"radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))",
		}),
	},
}));
interface IRegisterForm {
	name: string;
	email: string;
	password: string;
	phone: string; // Changed to string to handle formatted phone numbers
	role: string;
}

//Eknoor singh and jaanvi
//date:- 13-Feb-2025
//Implemented SignUp functionality which was static initially
export default function SignUp(props: { disableCustomTheme?: boolean }) {
	const dispatch = useDispatch();
	const {
		control,
		handleSubmit,
		formState: { errors },
		setValue,
	} = useForm<IRegisterForm>({
		defaultValues: {
			name: "",
			email: "",
			password: "",
			role: "",
			phone: "",
		},
	});

	const navigate = useNavigate();
	const [phone, setPhone] = React.useState("");

	const roleOptions = [
		{ value: "admin", label: "Admin" },
		{ value: "user", label: "User" },
	];
	// Enhanced email validation regex
	const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

	const handlePhoneChange = (value: string) => {
		// Remove all non-numeric characters except + for country code
		const cleanedNumber = value.replace(/[^\d+]/g, "");
		setValue("phone", cleanedNumber);
	};

	const onSubmit: SubmitHandler<IRegisterForm> = async (data) => {
		try {
			// Validate email
			if (!emailRegex.test(data.email)) {
				toast.error("Please enter a valid email address");
				return;
			}

			// Validate phone number
			if (!data.phone || data.phone.length < 10) {
				toast.error("Please enter a valid phone number");
				return;
			}

			// Validate phone number
			const payload = {
				name: data.name.trim(),
				email: data.email.toLowerCase().trim(),
				password: data.password,
				phone: data.phone,
				role: data.role,
			};

			await dispatch(registerUser(payload)).unwrap();
			navigate("/login");
			toast.success("Registration successful!");
		} catch (error: any) {
			toast.error(error?.message || "Registration failed");
			console.error("Registration error:", error);
		}
	};

	return (
		<AppTheme {...props}>
			{/* <CssBaseline enableColorScheme /> */}
			<ColorModeSelect
				sx={{ position: "fixed", top: "1rem", right: "1rem" }}
			/>
			<SignUpContainer direction="column" justifyContent="space-between">
				<Card variant="outlined">
					Digi-EV
					<Typography
						component="h1"
						variant="h4"
						sx={{
							width: "100%",
							fontSize: "clamp(2rem, 10vw, 2.15rem)",
						}}
					>
						Sign up
					</Typography>
					<Box
						component="form"
						onSubmit={handleSubmit(onSubmit)}
						sx={{
							display: "flex",
							flexDirection: "column",
							gap: 2,
						}}
					>
						<FormControl>
							<FormLabel htmlFor="name">Full name</FormLabel>
							<Controller
								name="name"
								control={control}
								rules={{ required: "Name is required" }}
								render={({ field }) => (
									<TextField
										{...field}
										id="name"
										fullWidth
										placeholder="Jon Snow"
										error={!!errors.name}
										helperText={errors.name?.message}
									/>
								)}
							/>
						</FormControl>

						<FormControl>
							<FormLabel htmlFor="email">Email</FormLabel>
							<Controller
								name="email"
								control={control}
								rules={{
									required: "Email is required",
									pattern: {
										value: /\S+@\S+\.\S+/,
										message:
											"Please enter a valid email address.",
									},
								}}
								render={({ field }) => (
									<TextField
										{...field}
										id="email"
										fullWidth
										placeholder="your@email.com"
										error={!!errors.email}
										helperText={errors.email?.message}
									/>
								)}
							/>
						</FormControl>

						<FormControl>
							<FormLabel htmlFor="password">Password</FormLabel>
							<Controller
								name="password"
								control={control}
								rules={{
									required: "Password is required",
									minLength: {
										value: 6,
										message:
											"Password must be at least 6 characters long",
									},
								}}
								render={({ field }) => (
									<TextField
										{...field}
										id="password"
										fullWidth
										type="password"
										placeholder="••••••"
										error={!!errors.password}
										helperText={errors.password?.message}
									/>
								)}
							/>
						</FormControl>

						<FormControl>
							<FormLabel htmlFor="phone">Phone Number</FormLabel>
							<MuiPhoneNumber
								defaultCountry="in"
								onChange={(value) => handlePhoneChange(value as string)}
								value={control._formValues.phone}
								required
								error={!!errors.phone}
								helperText={errors.phone?.message}
							/>
						</FormControl>

						<FormControl fullWidth>
							<InputLabel id="role-select-label">Role</InputLabel>
							<Controller
								name="role"
								control={control}
								rules={{ required: "Role is required" }}
								render={({ field }) => (
									<Select
										{...field}
										labelId="role-select-label"
										id="role-select"
										value={field.value}
										onChange={(e) =>
											setValue("role", e.target.value)
										}
										error={!!errors.role}
									>
										{roleOptions.map((option) => (
											<MenuItem
												key={option.value}
												value={option.value}
											>
												{option.label}
											</MenuItem>
										))}
									</Select>
								)}
							/>
							{errors.role && (
								<Typography color="error" variant="caption">
									{errors.role.message}
								</Typography>
							)}
						</FormControl>

						{/* <FormControlLabel
              control={
                <Controller
                  name="allowExtraEmails"
                  control={control}
                  render={({ field }) => (
                    <Checkbox {...field} color="primary" />
                  )}
                />
              }
              label="I want to receive updates via email."
            /> */}

						<Button type="submit" fullWidth variant="contained">
							Sign up
						</Button>
					</Box>
					{/* <Divider>
            <Typography sx={{ color: 'text.secondary' }}>or</Typography>
          </Divider> */}
					{/* <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <Button
              fullWidth
              variant="outlined"
              onClick={() => alert('Sign up with Google')}
              startIcon={<GoogleIcon />}
            >
              Sign up with Google
            </Button>
            <Button
              fullWidth
              variant="outlined"
              onClick={() => alert('Sign up with Facebook')}
              startIcon={<FacebookIcon />}
            >
              Sign up with Facebook
            </Button>
            <Typography sx={{ textAlign: 'center' }}>
              Already have an account?{' '}
              <Link
                href="/"
                variant="body2"
                sx={{ alignSelf: 'center' }}
              >
                Sign in
              </Link>
            </Typography>
          </Box> */}
					<Divider>or</Divider>
					<Box
						sx={{
							display: "flex",
							flexDirection: "column",
							gap: 2,
						}}
					>
						<Typography sx={{ textAlign: "center" }}>
							Already have an account? &nbsp;
							<Link
								href="/login"
								variant="body2"
								sx={{ alignSelf: "center" }}
							>
								Sign in
							</Link>
						</Typography>
					</Box>
				</Card>
			</SignUpContainer>
		</AppTheme>
	);
}
