import {
	Box,
	Button,
	TextField,
	Typography,
	makeStyles,
	useTheme,
} from "@material-ui/core";
import { Autocomplete } from "@material-ui/lab";
import { unwrapResult } from "@reduxjs/toolkit";
import * as React from "react";
import { useDispatch, useSelector } from "react-redux";
import {
	buzzOneGetUserAsync,
	logOut,
} from "../../../auth/SignInScreen/SigninStore/signinSlice";
import { isValidToken } from "../../../auth/utils/jwtValidator";
import BuzzLabel from "../../../components/BuzzLabel/BuzzLabel";
import BuzzSelect from "../../../components/BuzzSelect/BuzzSelect";
import useResponsive from "../../../hooks/useResponsive";
import useToast from "../../../hooks/useToast";
import {
	saveOtherDetailsAsync,
	searchSchoolAsync,
} from "../OnboardingStore/onboardingSlice";

const generalStyle = {
	inputWidth: {
		width: 400,
	},
};

const useStyles = makeStyles((theme) => ({
	overAll: {
		width: "100vw",
		height: "100vh",
		backgroundColor: theme.palette.buzzPurple,
	},
	card: {
		width: 500,
		height: 550,
		padding: "50px 0",
		backgroundColor: theme.palette.buzzContainerColor,
	},
	title: {
		fontSize: "2rem",
		textAlign: "center",
	},
	option: {
		width: generalStyle.inputWidth.width,
		padding: 5,
		borderBottom: `1px solid ${theme.palette.buzzBorder}`,
		...theme.typography.body1,
		color: theme.palette.buzzGreyColor,
	},
	greyText: {
		color: theme.palette.buzzGreyColor,
	},
	smallText: {
		...theme.typography.body2,
	},
	verticalSpace: {
		margin: "50px 0",
	},
	dropdownContainer: {
		width: generalStyle.inputWidth.width,
		border: `1px solid ${theme.palette.buzzBorder}`,
	},
	button: {
		width: generalStyle.inputWidth.width,
		height: 50,
		backgroundColor: theme.palette.primary.main,
		color: theme.palette.buzzFadeLite,
		fontSize: 10,
	},
}));

const SelectSchool = ({ history }) => {
	const theme = useTheme();
	const [schoolName, setSchoolName] = React.useState(null);
	const [designation, setDesignation] = React.useState("");
	const [staffStrength, setStaffStrength] = React.useState("");
	const classes = useStyles();
	const { isWeb, isMobile } = useResponsive();

	const { ErrorToast } = useToast();

	const dispatch = useDispatch();
	const { searchSchool } = useSelector(({ onboardingReducer }) => {
		return {
			signUpCreds: onboardingReducer.signUpCreds,
			loading: onboardingReducer.loading,
			searchSchool: onboardingReducer.searchSchool,
			select_school: onboardingReducer.select_school,
		};
	});

	const designations = [
		{ position: "Principal" },
		{ position: "Dean" },
		{ position: "Center Co-ordinator" },
		{ position: "Head of IT" },
		{ position: "Head of Human Resources" },
		{ position: "Other" },
	];

	const strengths = [
		{ strength: "Less than 50" },
		{ strength: "50 - 100" },
		{ strength: "101-200" },
		{ strength: "201-500" },
		{ strength: "501 +" },
	];

	const updateNewUser = () => {
		if (schoolName && staffStrength.length > 0 && designation.length > 0) {
			dispatch(
				saveOtherDetailsAsync({
					searchTerms: schoolName.schoolName,
					staffStrength: staffStrength,
					designation: designation,
				})
			)
				.then(unwrapResult)
				.then((res) => {
					if (res.status === 200) {
						schoolName._id && localStorage.setItem("schoolId", schoolName._id);
						localStorage.setItem("schoolName", schoolName.schoolName);
						if (isValidToken()) {
							dispatch(buzzOneGetUserAsync())
								.then(unwrapResult)
								.then(() => {
									if (schoolName._id) {
										if (isWeb) {
											history.push(
												`/school-management/view-branch-details/${schoolName._id}`
											);
										} else {
											history.push(
												`/school-management/view-branch-details/${schoolName._id}/${schoolName.schoolName}/kyc`
											);
										}
									} else history.push("/");
								});
						} else {
							dispatch(logOut());
						}
					}
				});
		} else {
			ErrorToast("All fields are mandatory to continue!");
		}
	};

	return isWeb ? (
		<Box
			display="flex"
			justifyContent={"center"}
			alignItems={"center"}
			className={classes.overAll}
		>
			<Box
				display="flex"
				flexDirection="column"
				justifyContent={"space-around"}
				alignItems={"center"}
				className={classes.card}
			>
				<Box flex={"1 1 0%"}>
					<Typography
						variant={"h3"}
						className={`${classes.greyText} ${classes.title}`}
					>
						Create school account
					</Typography>
					<Typography className={`${classes.greyText} ${classes.smallText}`}>
						Give us these additional details to setup your dashboard
					</Typography>
				</Box>

				<Box m={6} width={generalStyle.inputWidth.width}>
					<BuzzLabel label={"School Name"} />
					<Autocomplete
						freeSolo
						disablePortal
						id="combo-box-demo"
						options={searchSchool}
						getOptionLabel={(option) => option.schoolName}
						sx={{
							width: "70%",
							"& .MuiOutlinedInput-root": {
								padding: "6px",
								"& .MuiAutocomplete-input": {
									padding: "0px 4px 0px 6px",
								},
							},
						}}
						renderInput={(params) => (
							<TextField
								sx={{
									"& .css-14s5rfu-MuiFormLabel-root-MuiInputLabel-root": {
										top: -9,
									},
								}}
								{...params}
								onChange={(e) => {
									e.target.value.length >= 3 &&
										dispatch(searchSchoolAsync(e.target.value));
									setSchoolName({ schoolName: e.target.value });
								}}
								value={schoolName && schoolName.schoolName}
							/>
						)}
						onChange={(event, school) => setSchoolName(school)}
					/>
				</Box>

				<BuzzSelect
					size="small"
					width={generalStyle.inputWidth.width}
					name="designationId"
					labelKey="position"
					valueKey="position"
					options={designations}
					// mt={2}
					value={designation}
					onChange={(e) => setDesignation(e.target.value)}
					label="Designation"
				/>

				<BuzzSelect
					size="small"
					width={generalStyle.inputWidth.width}
					name="staffStrengthId"
					labelKey="strength"
					valueKey="strength"
					options={strengths}
					// mt={2}
					value={staffStrength}
					onChange={(e) => setStaffStrength(e.target.value)}
					label="Student strength"
				/>

				<Button
					className={classes.button}
					color="primary"
					variant="contained"
					onClick={updateNewUser}
				>
					Go to dashboard
				</Button>
			</Box>
		</Box>
	) : (
		<Box
			display="flex"
			justifyContent={"center"}
			alignItems={"center"}
			className={classes.overAll}
		>
			<Box
				display="flex"
				flexDirection="column"
				justifyContent={"space-around"}
				alignItems={"center"}
				width={isMobile ? "85vw" : "80vw"}
				bgcolor={theme.palette.buzzContainerColor}
				py={isMobile ? 3 : 6}
				px={isMobile ? 2 : 5}
				height={500}
			>
				<Box flex={"1 1 0%"}>
					<Typography
						variant={"h3"}
						className={`${classes.greyText} ${classes.title}`}
					>
						Create school account
					</Typography>
					<Typography className={`${classes.greyText} ${classes.smallText}`}>
						Give us these additional details to setup your dashboard
					</Typography>
				</Box>

				<Box my={6} mx={2} width={"100%"}>
					<BuzzLabel label={"School Name"} />
					<Autocomplete
						freeSolo
						disablePortal
						id="combo-box-demo"
						options={searchSchool}
						getOptionLabel={(option) => option.schoolName}
						sx={{
							width: "70%",
							"& .MuiOutlinedInput-root": {
								padding: "6px",
								"& .MuiAutocomplete-input": {
									padding: "0px 4px 0px 6px",
								},
							},
						}}
						renderInput={(params) => (
							<TextField
								sx={{
									"& .css-14s5rfu-MuiFormLabel-root-MuiInputLabel-root": {
										top: -9,
									},
								}}
								{...params}
								onChange={(e) => {
									e.target.value.length >= 3 &&
										dispatch(searchSchoolAsync(e.target.value));
									setSchoolName({ schoolName: e.target.value });
								}}
								value={schoolName && schoolName.schoolName}
							/>
						)}
						onChange={(event, school) => setSchoolName(school)}
					/>
				</Box>

				<BuzzSelect
					size="small"
					width={"100%"}
					name="designationId"
					labelKey="position"
					valueKey="position"
					options={designations}
					// mt={2}
					value={designation}
					onChange={(e) => setDesignation(e.target.value)}
					label="Designation"
				/>

				<BuzzSelect
					size="small"
					width={"100%"}
					name="staffStrengthId"
					labelKey="strength"
					valueKey="strength"
					options={strengths}
					// mt={2}
					value={staffStrength}
					onChange={(e) => setStaffStrength(e.target.value)}
					label="Student strength"
				/>

				<Button
					// className={classes.button}
					style={{
						width: "100%",
						height: 50,
						backgroundColor: theme.palette.primary.main,
						color: theme.palette.buzzFadeLite,
						fontSize: 10,
					}}
					color="primary"
					variant="contained"
					onClick={updateNewUser}
				>
					Go to dashboard
				</Button>
			</Box>
		</Box>
	);
};

export default SelectSchool;
