import {
	ContactPointInfo,
	deleteContactPoint,
	getContactPoints,
} from '@/api/contactPoints'
import { useState } from 'preact/hooks'
import { useMutation, useQuery } from 'react-query'
import { ContactPointFormModal } from './components/ContactPointFormModal'
import { DataTable } from '@/components/DataTable'
import { ConfirmModal } from '@/components/ConfirmModal'
import { PlusIcon } from '@/icons'

export const ContactPointsTable = () => {
	const contactPoints = useQuery('/contact-points', () => getContactPoints())

	const deleteMutation = useMutation(deleteContactPoint, {
		onSuccess: () => {
			contactPoints.refetch()
			setShowDelete(undefined)
		},
	})

	const [showNew, setShowNew] = useState(false)
	const [edited, setEdited] = useState<ContactPointInfo>()
	const [showDelete, setShowDelete] = useState<ContactPointInfo>()

	return (
		<div className="contact-points">
			<div className="section-title">
				<h2>Contact Points</h2>
				<button onClick={() => setShowNew(true)}>
					<PlusIcon /> Add contact point
				</button>
			</div>

			<div className="box-shadow">
				<DataTable
					data={contactPoints.data ?? []}
					columns={[
						{ key: 'name', title: 'Name', render: (c) => c.name, scale: 1 },
						{
							key: 'type',
							title: 'Type',
							render: (c) => c.type,
							width: '5rem',
						},
						{
							key: 'actions',
							title: 'Actions',
							width: '10rem',
							className: 'actions',
							render: (c) => (
								<div>
									<button onClick={() => setEdited(c)}>Edit</button>
									<button onClick={() => setShowDelete(c)}>Delete</button>
								</div>
							),
						},
					]}
				/>
			</div>

			{(showNew || edited) && (
				<ContactPointFormModal
					open
					contactPoint={edited}
					onClose={() => {
						setShowNew(false)
						setEdited(undefined)
					}}
				/>
			)}

			{showDelete && (
				<ConfirmModal
					open
					onConfirm={() => deleteMutation.mutate(showDelete.id)}
					onCancel={() => setShowDelete(undefined)}
					confirmText="Delete"
				>
					Do you want to delete {showDelete.name} contact point?
				</ConfirmModal>
			)}
		</div>
	)
}
