import {
	MQTTBrokerInfo,
	deleteMQTTBroker,
	getMQTTBrokers,
} from '@/api/mqttBrokers'
import { DataTable } from '@/components/DataTable'
import { useConfirmModal } from '@/contexts/ConfirmModalsContext'
import { EditIcon, PlusIcon, TrashIcon } from '@/icons'
import { UserLayout } from '@/layouts/UserLayout/UserLayout'
import { useState } from 'preact/hooks'
import { useMutation, useQuery, useQueryClient } from 'react-query'
import { MQTTBrokerFormModal } from './components/MQTTBrokerFormModal'
import { NoMQTTBrokers } from './components/NoMQTTBrokers'

export const MqttBrokersPage = () => {
	const brokers = useQuery(['/mqtt/brokers'], getMQTTBrokers)
	const queryClient = useQueryClient()

	const deleteMutation = useMutation(deleteMQTTBroker, {
		onSuccess: () => queryClient.invalidateQueries(['/mqtt/brokers']),
	})

	const [showNew, setShowNew] = useState(false)
	const [edited, setEdited] = useState<MQTTBrokerInfo>()

	const deleteConfirm = useConfirmModal({
		content: (deleted: MQTTBrokerInfo) =>
			`Are you sure you want to delete sensor ${deleted.name}?`,
		onConfirm: (deleted) => deleteMutation.mutate(deleted.id),
	})

	return (
		<UserLayout className="sensors-page">
			<div className="section-title">
				<h2>Sensors</h2>
				<button onClick={() => setShowNew(true)}>
					<PlusIcon /> Add MQTT Broker
				</button>
			</div>

			<div className="box-shadow">
				<DataTable
					query={brokers}
					emptyMessage={<NoMQTTBrokers />}
					columns={[
						{ key: 'name', title: 'Name', render: (c) => c.name, scale: 1 },
						{
							key: 'address',
							title: 'Address',
							render: (c) => c.address,
							scale: 1,
						},
						{
							key: 'actions',
							title: 'Actions',
							width: '15rem',
							className: 'actions',
							render: (c) => (
								<div>
									<button
										className="danger-variant"
										onClick={() => deleteConfirm.show(c)}
									>
										<TrashIcon /> Delete
									</button>
									<button onClick={() => setEdited(c)}>
										<EditIcon /> Edit
									</button>
								</div>
							),
						},
					]}
				/>
			</div>

			{(showNew || edited) && (
				<MQTTBrokerFormModal
					open
					mqttBroker={edited}
					onClose={() => {
						setShowNew(false)
						setEdited(undefined)
					}}
				/>
			)}
		</UserLayout>
	)
}
