import _ from "lodash";
import moment from "moment";
import React, { Component } from "react";
import { DropdownButton, MenuItem } from "react-bootstrap";
import FontAwesome from "react-fontawesome";
import { withRouter } from "react-router";
import { connect } from "react-redux";
import { jobsLoaded, jobsUpdate } from "../actions";
import { PlussCore } from "../feature.config";
import { maintenanceActions, userActions } from "../apis";
import { values } from "../values.config";

const { Actions, Components, Helper, Session, Colours, Apis } = PlussCore;

class AddJob extends Component {
	constructor(props) {
		super(props);
		this.imageInput = null;
		this.customImageInputs = {};
		this.customDocumentInputs = {};
		this.state = {
			jobId: Helper.safeReadParams(this.props, "jobId")
				? this.props.match.params.jobId
				: null,
			job: null,
			showingSelector: false,
			updating: false,
			connected: false,
			types: [],
			users: [],
			images: [],
			userSearch: "",
			userFilterOpen: false,
			selectedUser: null,
			id: null,
			userID: "",
			userName: "",
			room: "",
			phone: "",
			location: this.props.auth.site,
			title: "",
			description: "",
			isHome: false,
			homeText: "",
			prevType: "General",
			type: "General",
			image: null,
			thumbnail: null,
			showWarnings: false,
			success: false,
			prevCustomFileds: [],
			customFields: [],
			showDate: {},
		};
	}

	UNSAFE_componentWillMount() {
		Session.checkLoggedIn(this, this.props.auth);
	}

	componentDidMount() {
		this.getJobTypes();
		this.getUsers();
		if (this.state.jobId) this.getJob();
		this.props.addRecentlyCreated(values.featureKey);
	}

	getJob = async () => {
		try {
			const res = await maintenanceActions.getJob(
				this.props.auth.site,
				this.state.jobId,
			);
			res.data.location = res.data.site;
			const { userID, userName, userProfilePic, type, customFields } = res.data;
			this.setState({
				...res.data,
				prevType: type,
				prevCustomFileds: customFields,
				type,
				customFields,
				selectedUser: {
					userId: userID,
					displayName: userName,
					profilePic: userProfilePic,
				},
			});
			this.checkSetImages(this.imageInput, res.data.images);
			if (customFields) {
				customFields.forEach((field, index) => {
					if (field.type === "image" && field.answer) {
						this.checkSetImages(this.customImageInputs[index], field.answer);
					}
				});
			}
		} catch (error) {
			console.error("getJob", error);
		}
	};

	checkSetImages(imageRef, images) {
		if (imageRef) {
			if (!_.isEmpty(images)) {
				imageRef.setValue(images);
			}
		} else {
			setTimeout(() => {
				this.checkSetImages(images);
			}, 100);
		}
	}

	getJobTypes = async () => {
		try {
			const res = await maintenanceActions.getJobTypes(this.props.auth.site);
			this.setState({ types: res.data });
			this.getDefaultJob();
		} catch (error) {
			console.error("getJobTypes", error);
		}
	};

	getUsers = async () => {
		try {
			const res = await userActions.fetchUsers(this.props.auth.site);
			if (res.userFetchFail) return;
			if (res.data != null && !_.isEmpty(res.data.results.Items)) {
				let items = res.data.results.Items;
				if (this.props.optionOnlyForResidents) {
					items = _.filter(items, (u) => u.category === "resident");
				}
				this.setState({
					users: _.sortBy(items, (u) => {
						return (u.displayName || "").toLowerCase();
					}),
				});
			}
		} catch (error) {
			console.error("getUsers", error);
		}
	};

	getDefaultJob = () => {
		const { types, jobId } = this.state;
		if (jobId == null) {
			if (types.length !== 0) {
				const defaultType = types[0];
				this.setState({
					type: defaultType.typeName,
					customFields:
						defaultType.hasCustomFields && defaultType.customFields.length > 0
							? defaultType.customFields
							: [],
				});
			} else if (values.forceCustomFields) {
				this.setState({ noTypes: true });
			} else {
				this.setState({ type: "General" });
			}
		}
	};

	onSelectType = (key, e) => {
		const { types, prevType, prevCustomFileds } = this.state;
		const selectedType = types.find((t) => t.typeName === key);
		// If selected type had previously saved custom fields, use the previous version
		const hasPrevCustomFields =
			prevType === selectedType.typeName &&
			prevCustomFileds &&
			prevCustomFileds.length > 0;
		const update = {
			type: selectedType.typeName,
			customFields: hasPrevCustomFields
				? prevCustomFileds
				: selectedType.hasCustomFields
					? selectedType.customFields
					: [],
		};

		if (
			!_.isEmpty(update.customFields) &&
			!_.some(update.customFields, "isTitle")
		) {
			update.title = this.state.selectedUser
				? this.state.selectedUser.displayName
				: "";
		}

		this.setState(update);
	};

	renderTypeOptions() {
		const { types, type } = this.state;
		return types.map((ev) => {
			if (ev != null) {
				return (
					<MenuItem
						key={ev.typeName}
						eventKey={ev.typeName}
						active={type === ev.typeName}
					>
						{ev.typeName}
					</MenuItem>
				);
			}
			return null;
		});
	}

	onHandleChange = (event) => {
		var stateChange = {};
		stateChange[event.target.getAttribute("id")] = event.target.value;
		this.setState(stateChange);
	};

	onOpenUserSelector = () => {
		this.setState({ userFilterOpen: true });
	};

	onCloseUserSelector = () => {
		this.setState({ userFilterOpen: false });
	};

	onSelectUser = (user) => {
		const update = {
			selectedUser: user,
			userID: user.userId,
			userName: user.displayName,
			userFilterOpen: false,
		};
		if (
			!_.isEmpty(this.state.customFields) &&
			!_.some(this.state.customFields, "isTitle")
		) {
			update.title = user.displayName;
		}

		// Update UI immediately (non-blocking)
		this.setState(update);

		// PC-1255: Auto-populate contact details when staff create requests on behalf of residents
		// Requires userManagement permission - gracefully falls back to manual entry if denied
		// Fetch in background to avoid blocking UI
		userActions
			.fetchUser(this.props.auth.site, user.userId)
			.then((response) => {
				if (response.data && response.data.user) {
					const contactUpdate = {};
					// Auto-populate phone and room from user profile
					if (response.data.user.phoneNumber) {
						contactUpdate.phone = response.data.user.phoneNumber;
					}
					if (response.data.user.unit) {
						contactUpdate.room = response.data.user.unit;
					}
					// Update contact fields when data arrives
					if (Object.keys(contactUpdate).length > 0) {
						this.setState(contactUpdate);
					}
				}
			})
			.catch((error) => {
				// Permission denied (403) or other error - continue without auto-population
				// Staff can still create the request, just need to enter contact details manually
				console.log("Could not fetch user details for auto-population:", error);
			});
	};

	onUnselectUser = () => {
		const update = {
			selectedUser: null,
			userID: "",
			userName: "",
			phone: "",
			room: "",
		};
		if (
			!_.isEmpty(this.state.customFields) &&
			!_.some(this.state.customFields, "isTitle")
		) {
			update.title = "";
		}
		this.setState(update);
	};

	onChangeAnswer = (qId, answer) => {
		const update = { customFields: _.cloneDeep(this.state.customFields) };
		const field = update.customFields[qId];
		field.answer = answer;
		if (field.isTitle) update.title = field.answer;
		this.setState(update);
	};

	onChangeToggleAnswer = (qId, answer) => {
		const update = { customFields: _.cloneDeep(this.state.customFields) };
		const field = update.customFields[qId];
		field.answer = field.answer === answer ? undefined : answer;
		if (field.isTitle) update.title = field.answer;
		this.setState(update);
	};

	onChangeCheckboxAnswer = (qId, answer) => {
		const update = { customFields: _.cloneDeep(this.state.customFields) };
		const field = update.customFields[qId];
		field.answer = _.xor(field.answer || [], [answer]);
		if (field.isTitle) update.title = field.answer.join(", ");
		this.setState(update);
	};

	onChangeDateAnswer = (qId, answer, togglePicker = true) => {
		const update = { customFields: _.cloneDeep(this.state.customFields) };
		const field = update.customFields[qId];
		field.answer = answer;
		if (field.isTitle)
			update.title = moment(field.answer, "YYYY-MM-DD").format("DD-MMM-YYYY");
		this.setState(update);

		if (togglePicker) this.onToggleDatePicker(qId);
	};

	onChangeTimeAnswer = (qId, answer) => {
		const update = { customFields: _.cloneDeep(this.state.customFields) };
		const field = update.customFields[qId];
		field.answer = answer;
		if (field.isTitle)
			update.title = moment(field.answer, "HH:mm").format("h:mm a");
		this.setState(update);
	};

	onChangeImageAnswer = (qId, answer) => {
		const update = { customFields: _.cloneDeep(this.state.customFields) };
		const field = update.customFields[qId];
		field.answer = answer;
		this.setState(update);
	};

	onRemoveDocumentAnswer = (qId, document) => {
		const update = { customFields: _.cloneDeep(this.state.customFields) };
		const field = update.customFields[qId];
		field.answer = _.filter(field.answer, (d) => d.url !== document.url);
		this.setState(update);
	};

	onHandlePDFFileChange = (event, qId) => {
		const file = event.target.files[0];
		if (!file) return;

		const update = { customFields: _.cloneDeep(this.state.customFields) };
		const field = update.customFields[qId];
		const attachments = field.answer || [];
		const [name, ext] = file.name.split(".");
		const newAttachment = {
			uploading: true,
			name,
			ext: ext.toLowerCase(),
		};
		attachments.push(newAttachment);
		field.answer = attachments;
		this.setState(update);

		Apis.fileActions
			.uploadMediaAsync(file, file.name)
			.then((fileRes) => {
				newAttachment.url = fileRes;
				delete newAttachment.uploading;
				this.setState(update);
			})
			.catch((uploadErrorRes) => {
				console.log(uploadErrorRes);
				delete newAttachment.uploading;
				this.setState(update);
			});
		event.target.value = "";
	};

	onToggleDatePicker = (qId) => {
		const showDate = { ...this.state.showDate };
		showDate[qId] = !showDate[qId];
		this.setState({ showDate });
	};

	onSave = () => {
		this.setState({ showWarnings: false });
		if (!this.validateForm()) {
			this.setState({ showWarnings: true });
			return;
		}
		if (this.state.updating) return;
		this.setState({ updating: true });

		const job = {
			id: this.state.id,
			userID: this.state.userID,
			userName: this.state.userName,
			room: this.state.room,
			phone: this.state.phone,
			location: this.state.location,
			title: this.state.title,
			description: this.state.description,
			isHome: this.state.isHome,
			homeText: this.state.homeText,
			type: this.state.type,
			date: null,
			images: this.state.images,
			customFields: this.state.customFields,
		};

		if (this.state.id != null) {
			maintenanceActions
				.editJob(job, this.props.auth.site)
				.then((res) => {
					this.setState({
						success: true,
						updating: false,
					});
					this.props.jobsLoaded([job]);
				})
				.catch((res) => {
					this.setState({ updating: false });
					alert("Something went wrong with the request. Please try again.");
				});
		} else {
			// Create New Job
			maintenanceActions
				.createJob(job)
				.then((res) => {
					this.setState({
						success: true,
						updating: false,
					});
					this.props.jobsUpdate(this.props.auth.site);
				})
				.catch((res) => {
					this.setState({ updating: false });
					alert("Something went wrong with the request. Please try again.");
				});
		}
	};

	renderSuccess() {
		if (!this.state.success) return null;

		const title =
			this.props.strings[`${values.featureKey}_textTitleRequests`] ||
			values.textTitleRequests;
		return (
			<Components.SuccessPopup
				text={`${values.textEntityName} has been ${this.state.id != null ? "edited" : "added"}`}
				buttons={[
					{
						type: "outlined",
						onClick: () => {
							window.history.back();
						},
						text: `Back to ${title}`,
					},
				]}
			/>
		);
	}

	isFieldValid = (field) => {
		const { mandatory, type, answer } = field;
		if (["staticTitle", "staticText"].includes(type)) return true;

		const checkMandatory = () => {
			if (!mandatory) return true;
			switch (type) {
				case "yn":
					return _.isBoolean(answer);
				case "image":
				case "document":
				case "checkbox":
					return _.isArray(answer) && answer.length > 0;
				default:
					return !_.isNil(answer) && !_.isEmpty(answer);
			}
		};
		const checkFormat = () => {
			if (_.isNil(answer) || _.isEmpty(answer)) return true;
			switch (type) {
				case "email":
					return Helper.isEmail(answer);
				case "date":
					return moment(answer, "YYYY-MM-DD", true).isValid();
				case "time":
					return moment(answer, "HH:mm", true).isValid();
				default:
					return true;
			}
		};

		const valid = checkMandatory() && checkFormat();
		return valid;
	};

	validateCustomFields() {
		const { customFields } = this.state;
		if (!customFields || customFields.length === 0) return true;

		return customFields.every((field) => {
			const isValid = this.isFieldValid(field);
			return isValid;
		});
	}

	validateForm() {
		if (_.isEmpty(this.state.userID)) return false;
		if (_.isEmpty(this.state.userName)) return false;
		if (_.isEmpty(this.state.room)) return false;
		if (_.isEmpty(this.state.title)) return false;
		if (this.state.isHome && _.isEmpty(this.state.homeText)) return false;
		if (!this.validateCustomFields()) return false;
		return true;
	}

	getFieldContainerClass = (isValid = true) => {
		const showError = this.state.showWarnings && !isValid;
		return `genericInputContainer ${isValid ? "genericInput-valid" : ""} ${showError ? "genericInput-error" : ""}`.trim();
	};

	renderSubmit() {
		if (this.state.updating) {
			return (
				<Components.Button buttonType="secondary">Saving...</Components.Button>
			);
		}

		return (
			<div>
				<Components.Button
					inline
					buttonType="tertiary"
					onClick={() => this.props.history.push(values.routeRequestsHub)}
					isActive
					style={{ marginRight: 16 }}
				>
					Cancel
				</Components.Button>
				<Components.Button
					inline
					buttonType="primary"
					onClick={this.onSave}
					isActive={this.validateForm()}
				>
					Save
				</Components.Button>
			</div>
		);
	}

	renderSelectUser() {
		const { showWarnings, selectedUser } = this.state;
		const isValid = !_.isNil(selectedUser);
		return (
			<div className={this.getFieldContainerClass(isValid)}>
				<div style={styles.userLabelContainer}>
					<div className="fieldLabel">User</div>
					{showWarnings && !isValid ? (
						<div className="fieldLabel fieldLabel-warning">Required</div>
					) : null}
				</div>
				<div style={styles.fieldContainer}>
					<div className="inputRequired " />
					{selectedUser ? (
						<Components.Tag
							className="marginRight-10"
							rightIcon="close"
							rightClick={this.onUnselectUser}
						>
							<Components.UserListing
								size={15}
								user={selectedUser}
								textClass="tag_text"
							/>
						</Components.Tag>
					) : (
						<Components.Tag
							onClick={this.onOpenUserSelector}
							text="Select User"
						/>
					)}
				</div>
			</div>
		);
	}

	renderDefaultFields() {
		return (
			<div>
				<Components.GenericInput
					id="title"
					label="Title for the work required"
					type="textarea"
					placeholder="Title for the work required"
					value={this.state.title}
					onChange={(e) => this.onHandleChange(e)}
					inputStyle={{
						height: 80,
					}}
					isRequired
					isValid={() => {
						return !_.isEmpty(this.state.title);
					}}
					showError={() => {
						return this.state.showWarnings && _.isEmpty(this.state.title);
					}}
					alwaysShowLabel
				/>
				<Components.GenericInput
					id="description"
					label="Description of work required"
					type="textarea"
					placeholder="Description of work required"
					value={this.state.description}
					onChange={(e) => this.onHandleChange(e)}
					inputStyle={{
						height: 80,
					}}
					alwaysShowLabel
				/>
				<div className="marginBottom-16">
					<Components.Text type="formLabel" className="marginBottom-4">
						Images
					</Components.Text>
					<Components.ImageInput
						ref={(ref) => {
							this.imageInput = ref;
						}}
						multiple
						refreshCallback={(images) => {
							this.setState({ images });
						}}
					/>
				</div>
				<Components.RadioButton
					label="Person must be home during work?"
					isActive={this.state.isHome}
					options={[
						{
							Label: "No",
							Value: false,
							onChange: () => this.setState({ isHome: false }),
						},
						{
							Label: "Yes",
							Value: true,
							onChange: () => this.setState({ isHome: true }),
						},
					]}
				/>
				{this.state.isHome && (
					<Components.GenericInput
						style={{ marginTop: 16 }}
						label="Description of person's available times"
						id="homeText"
						type="textarea"
						placeholder="Description of person's available times"
						value={this.state.homeText}
						onChange={(e) => this.onHandleChange(e)}
						inputStyle={{
							height: 80,
						}}
						isRequired
						isValid={() => {
							return !_.isEmpty(this.state.homeText);
						}}
						showError={() => {
							return this.state.showWarnings && _.isEmpty(this.state.homeText);
						}}
						alwaysShowLabel
					/>
				)}
			</div>
		);
	}

	renderField(field, fieldId) {
		switch (field.type) {
			case "yn":
				return (
					<div
						key={fieldId}
						className={`visitorSignIn_question ${this.getFieldContainerClass(this.isFieldValid(field))}`}
						style={styles.fieldContainer}
					>
						{field.mandatory ? <div className="inputRequired " /> : null}
						<Components.RadioButton
							label={field.label}
							labelStyle={{ color: this.props.colour }}
							isActive={field.answer}
							noHoverHighlight
							highlightColour={this.props.colour}
							options={[
								{
									Label: "Yes",
									Value: true,
									onChange: this.onChangeToggleAnswer.bind(this, fieldId, true),
								},
								{
									Label: "No",
									Value: false,
									onChange: this.onChangeToggleAnswer.bind(
										this,
										fieldId,
										false,
									),
								},
							]}
						/>
					</div>
				);
			case "multichoice":
				return (
					<div
						key={fieldId}
						className={`visitorSignIn_question ${this.getFieldContainerClass(this.isFieldValid(field))}`}
						style={styles.fieldContainer}
					>
						{field.mandatory ? <div className="inputRequired " /> : null}
						<Components.RadioButton
							label={field.label}
							labelStyle={{ color: this.props.colour }}
							isActive={field.answer}
							noHoverHighlight
							highlightColour={this.props.colour}
							options={field.values.map((o) => {
								return {
									Label: o,
									Value: o,
									onChange: this.onChangeToggleAnswer.bind(this, fieldId, o),
								};
							})}
							rowStyle={{ flexDirection: "column" }}
							buttonStyle={{ marginTop: "5px", marginBottom: "5px" }}
						/>
					</div>
				);
			case "checkbox":
				return (
					<div
						key={fieldId}
						className={this.getFieldContainerClass(this.isFieldValid(field))}
						style={styles.fieldContainer}
					>
						{field.mandatory ? <div className="inputRequired " /> : null}
						<div className="visitorSignIn_question" style={{ flex: 1 }}>
							<div
								className="fieldLabel"
								style={{ marginBottom: "5px", color: this.props.colour }}
							>
								{field.label}
							</div>
							{field.values.map((option, optionIndex) => {
								return (
									<Components.CheckBox
										key={optionIndex}
										label={option}
										isActive={field.answer && field.answer.includes(option)}
										highlightColour={this.props.colour}
										noHoverHighlight
										onChange={() =>
											this.onChangeCheckboxAnswer(fieldId, option)
										}
									/>
								);
							})}
						</div>
					</div>
				);
			case "text":
			case "email":
			case "phone":
				return (
					<div key={fieldId}>
						<Components.GenericInput
							id={fieldId}
							type="text"
							label={field.label}
							placeholder={field.placeHolder}
							value={field.answer}
							onChange={(e) => this.onChangeAnswer(fieldId, e.target.value)}
							isRequired={field.mandatory}
							isValid={() => this.isFieldValid(field)}
							showError={() =>
								this.state.showWarnings && !this.isFieldValid(field)
							}
							errorMessage={
								field.type === "email" ? "Not a valid email" : undefined
							}
							alwaysShowLabel
						/>
					</div>
				);
			case "staticTitle":
				return (
					<p
						className="visitorSignIn_text-staticTitle"
						style={{ color: this.props.colour }}
						key={fieldId}
					>
						{field.label}
					</p>
				);
			case "staticText":
				return (
					<p className="visitorSignIn_text-staticText" key={fieldId}>
						{Helper.toParagraphed(field.label, { marginTop: 10 })}
					</p>
				);
			case "date":
				return (
					<div key={fieldId}>
						<Components.GenericInput
							id={fieldId}
							label={field.label}
							placeholder={"DD-MMM-YYYY"}
							value={
								field.answer
									? moment(field.answer, "YYYY-MM-DD").format("DD-MMM-YYYY")
									: ""
							}
							onClick={(e) => this.onToggleDatePicker(fieldId)}
							isRequired={field.mandatory}
							isValid={() => this.isFieldValid(field)}
							showError={() =>
								this.state.showWarnings && !this.isFieldValid(field)
							}
							errorMessage="Not a valid date"
							alwaysShowLabel
							readOnly
							rightContent={
								!_.isEmpty(field.answer) && (
									<Components.SVGIcon
										colour={Colours.COLOUR_DUSK_LIGHT}
										icon="close"
										className="timepicker_clear"
										onClick={() =>
											this.onChangeDateAnswer(fieldId, undefined, false)
										}
									/>
								)
							}
						/>
						{this.state.showDate[fieldId] && (
							<Components.DatePicker
								selectedDate={field.answer}
								selectDate={(date) => this.onChangeDateAnswer(fieldId, date)}
							/>
						)}
					</div>
				);
			case "time":
				return (
					<div key={fieldId}>
						<Components.GenericInput
							id={fieldId}
							label={field.label}
							placeholder={"--:-- --"}
							value={
								field.answer
									? moment(field.answer, "HH:mm").format("h:mm a")
									: ""
							}
							type="time"
							isRequired={field.mandatory}
							isValid={() => this.isFieldValid(field)}
							showError={() =>
								this.state.showWarnings && !this.isFieldValid(field)
							}
							errorMessage="Not a valid time"
							alwaysShowLabel
							inputComponent={
								<Components.TimePicker
									selectedTime={field.answer}
									selectTime={(time) => this.onChangeTimeAnswer(fieldId, time)}
									className="timepicker-condensed"
									callbackFormat="HH:mm"
									style={{ width: "100%" }}
								/>
							}
							rightContent={
								!_.isEmpty(field.answer) && (
									<Components.SVGIcon
										colour={Colours.COLOUR_DUSK_LIGHT}
										icon="close"
										className="timepicker_clear"
										onClick={() => this.onChangeTimeAnswer(fieldId, undefined)}
									/>
								)
							}
						/>
					</div>
				);
			case "image":
				return (
					<div
						key={fieldId}
						className={this.getFieldContainerClass(this.isFieldValid(field))}
						style={styles.fieldContainer}
					>
						{field.mandatory ? <div className="inputRequired " /> : null}
						<div className="visitorSignIn_question" style={{ flex: 1 }}>
							<Components.Text type="formLabel" className="marginBottom-4">
								{field.label}
							</Components.Text>
							<Components.ImageInput
								ref={(ref) => (this.customImageInputs[fieldId] = ref)}
								multiple
								refreshCallback={(images) =>
									this.onChangeImageAnswer(fieldId, images)
								}
							/>
						</div>
					</div>
				);
			case "document":
				const documents = field.answer || [];
				return (
					<div
						key={fieldId}
						className={this.getFieldContainerClass(this.isFieldValid(field))}
						style={styles.fieldContainer}
					>
						{field.mandatory ? <div className="inputRequired " /> : null}
						<div className="visitorSignIn_question" style={{ flex: 1 }}>
							<Components.Text type="formLabel" className="marginBottom-4">
								{field.label}
							</Components.Text>
							{documents.map((doc, index) => (
								<Components.Attachment
									key={index}
									uploading={doc.uploading}
									source={doc.url}
									title={doc.name}
									onRemove={() => this.onRemoveDocumentAnswer(fieldId, doc)}
								/>
							))}
							<input
								ref={(input) => (this.customDocumentInputs[fieldId] = input)}
								id={`documentInput-${fieldId}`}
								type="file"
								className="fileInput"
								onChange={(e) => this.onHandlePDFFileChange(e, fieldId)}
								accept="application/pdf"
							/>
							<div
								className="iconTextButton marginBottom-16"
								onClick={() => this.customDocumentInputs[fieldId].click()}
							>
								<FontAwesome className="iconTextButton_icon" name="paperclip" />
								<p className="iconTextButton_text">Add Attachment</p>
							</div>
						</div>
					</div>
				);
			default:
				return null;
		}
	}

	renderCustomFields() {
		const { customFields } = this.state;
		if (!customFields || customFields.length === 0) return null;

		return (
			<div>
				{customFields.map((field, i) => {
					return this.renderField(field, i);
				})}
			</div>
		);
	}

	renderMain() {
		const { customFields } = this.state;

		return (
			<div style={{ marginBottom: 15 }}>
				<div className="padding-60 paddingVertical-40 bottomDivideBorder">
					<Components.Text type="formTitleLarge" className="marginBottom-24">
						{this.state.infoId == null ? "New" : "Edit"}{" "}
						{values.textSingularName}
					</Components.Text>
					{/* Resident Information */}
					{this.renderSelectUser()}
					<Components.GenericInput
						id="phone"
						type="text"
						label="Contact number"
						placeholder="04XX XXX XXX"
						value={this.state.phone}
						// showError={this.state.showWarnings && !this.validateImage()}
						onChange={(e) => this.onHandleChange(e)}
						alwaysShowLabel
					/>
					<Components.GenericInput
						id="room"
						type="text"
						label="Address"
						placeholder="Insert address here"
						value={this.state.room}
						onChange={(e) => this.onHandleChange(e)}
						isRequired
						alwaysShowLabel
						isValid={() => {
							return !_.isEmpty(this.state.room);
						}}
						showError={() => {
							return this.state.showWarnings && _.isEmpty(this.state.room);
						}}
					/>
					<div style={{ marginBottom: 15 }}>
						<Components.Text type="formLabel">
							{values.textJobType}
						</Components.Text>
						<DropdownButton
							style={{ minWidth: 80 }}
							bsStyle="default"
							title={this.state.type}
							id="typeSelect"
							onSelect={this.onSelectType}
						>
							{this.renderTypeOptions()}
						</DropdownButton>
					</div>
					{!_.isEmpty(customFields) || values.forceCustomFields
						? this.renderCustomFields()
						: this.renderDefaultFields()}
				</div>
			</div>
		);
	}

	renderUserFilterPopup() {
		const { userFilterOpen, userSearch, users } = this.state;
		if (!userFilterOpen) return null;
		return (
			<Components.Popup
				title="Select Requestor"
				maxWidth={600}
				minWidth={400}
				maxHeight={600}
				minHeight={600}
				hasPadding
				onClose={this.onCloseUserSelector}
				buttons={[
					{
						type: "tertiary",
						onClick: this.onCloseUserSelector,
						isActive: true,
						text: "Cancel",
					},
				]}
			>
				<Components.GenericInput
					id="userSearch"
					type="text"
					label="Search User"
					placeholder="Search name"
					value={userSearch}
					onChange={(e) => this.onHandleChange(e)}
					alwaysShowLabel
				/>
				{_.sortBy(users, (u) => u.displayName.toUpperCase())
					.filter((u) => {
						if (_.isEmpty(userSearch)) return true;
						return (
							u.displayName.toUpperCase().indexOf(userSearch.toUpperCase()) > -1
						);
					})
					.map((user) => {
						return (
							<Components.UserListing
								key={user.userId}
								user={user}
								onClick={() => this.onSelectUser(user)}
							/>
						);
					})}
			</Components.Popup>
		);
	}

	render() {
		const { success } = this.state;

		return (
			<Components.OverlayPage>
				<Components.OverlayPageContents noBottomButtons={success}>
					<Components.OverlayPageSection className="pageSectionWrapper--newPopup">
						<div>
							{this.renderSuccess()}
							{!success && this.renderMain()}
						</div>
						{this.renderUserFilterPopup()}
					</Components.OverlayPageSection>
				</Components.OverlayPageContents>
				<Components.OverlayPageBottomButtons>
					{this.renderSubmit()}
				</Components.OverlayPageBottomButtons>
			</Components.OverlayPage>
		);
	}
}

const styles = {
	userLabelContainer: {
		display: "flex",
		flexDirection: "row",
		alignItems: "center",
		marginBottom: 0,
		justifyContent: "space-between",
	},
	fieldContainer: {
		display: "flex",
		flexDirection: "row",
		alignItems: "center",
	},
};

const mapStateToProps = (state) => {
	const { auth } = state;
	return {
		auth,
		strings: (state.strings && state.strings.config) || {},
		optionOnlyForResidents: Helper.getSiteSettingFromState(
			state,
			values.optionOnlyForResidents,
		),
	};
};

export default connect(mapStateToProps, {
	jobsUpdate,
	jobsLoaded,
	addRecentlyCreated: Actions.addRecentlyCreated,
})(withRouter(AddJob));
