import {
	MQTTBrokerInfo,
	createMQTTBroker,
	updateMQTTBroker,
} from '@/api/mqttBrokers'
import { FormField } from '@/components/FormField'
import { Modal } from '@/components/Modal'
import { useForm } from '@/utils/hooks/useForm'
import { useMutation, useQueryClient } from 'react-query'

type Props = {
	open: boolean
	onClose: () => void
	mqttBroker?: MQTTBrokerInfo
}

export const MQTTBrokerFormModal = ({ open, onClose, mqttBroker }: Props) => {
	const queryClient = useQueryClient()
	const createMutation = useMutation(createMQTTBroker)
	const updateMutation = useMutation(updateMQTTBroker)

	const { handleSubmit, register } = useForm({
		defaultValue: () => ({
			name: mqttBroker?.name ?? '',
			address: mqttBroker?.address ?? '',
			clientId: mqttBroker?.clientId ?? '',
			username: mqttBroker?.username ?? '',
			password: mqttBroker?.password ?? '',
		}),
		onSubmit: async (v) => {
			if (isLoading) {
				return
			}

			const data = {
				name: v.name,
				address: v.address,
				clientId: v.clientId,
				username: v.username,
				password: v.password,
			}

			if (mqttBroker) {
				await updateMutation.mutateAsync({
					id: mqttBroker.id,
					...data,
				})
			} else {
				await createMutation.mutateAsync(data)
			}

			queryClient.invalidateQueries(['/mqtt/brokers'])

			onClose()
		},
	})

	const isLoading = createMutation.isLoading || updateMutation.isLoading

	return (
		<Modal onClose={onClose} open={open}>
			<form onSubmit={handleSubmit}>
				<div className="input">
					<label>Name</label>
					<input
						type="text"
						minLength={1}
						required
						autoFocus
						{...register('name')}
					/>
				</div>

				<FormField
					name="address"
					label="MQTT Broker Address"
					hint="Example: tcp://10.10.1.1:1883"
				>
					<input required {...register('address')} />
				</FormField>
				<FormField name="clientId" label="Client ID">
					<input {...register('clientId')} />
				</FormField>
				<FormField name="username" label="Username">
					<input {...register('username')} />
				</FormField>
				<FormField name="password" label="Password">
					<input type="password" {...register('password')} />
				</FormField>

				<div className="actions">
					<button className="cancel" type="button" onClick={onClose}>
						Cancel
					</button>
					<button disabled={isLoading}>Save</button>
				</div>
			</form>
		</Modal>
	)
}
