'use client'
import { OrderTableList } from '@/app/components/OrderTableList'
import { useParams } from 'next/navigation'
import { useState } from 'react'
import DatePicker from 'react-datepicker'
import useAsyncEffect from 'use-async-effect'

import { useOrderStore } from '@/app/providers/OrderProvider'
import "react-datepicker/dist/react-datepicker.css"

const OrderTable = () => {
	const {page, filter} = useParams()

	console.log(filter)
	
	const [tempOrderer, setTempOrderer] = useState("")
	const [tempDateDue, setTempDateDue] = useState("")
	const [tempDatePlaced, setTempDatePlaced] = useState("")
	
	const [orderer, setOrderer] = useState("")
	const [dateDue, setDateDue] = useState("")
	const [datePlaced, setDatePlaced] = useState("")
	
	const orderStore = useOrderStore((state) => state)

	const [shouldPushUpdates, setShouldPushUpdates] = useState(false)

	const [shouldPushNewOrder, setShouldPushNewOrder] = useState(false)

	const [newOrderOrderer, setNewOrderOrderer] = useState("")
	const [newOrderDue, setNewOrderDue] = useState<Date | null>(null)
	useAsyncEffect(async () => {
		if(shouldPushUpdates) {
			setOrderer(tempOrderer)
			setDateDue(tempDateDue)
			setDatePlaced(tempDatePlaced)
			setShouldPushUpdates(false)
		}
	}, [shouldPushUpdates])

	useAsyncEffect(async () => {
		if(shouldPushNewOrder) {
			if(newOrderDue)
				orderStore.createOrder(newOrderOrderer, newOrderDue.toISOString())
			setShouldPushNewOrder(false)
		}
	}, [shouldPushNewOrder])
	return (
		<>
			<h1 className="text-xl font-bold mt-5">Search</h1>
			<input type='text' placeholder="orderer" onChange={(e) => {
				console.log(e.currentTarget.value)
				setTempOrderer(e.currentTarget.value)
			}} />
			<input type='text' placeholder="date due" onChange={(e) => {
				setTempDateDue(e.currentTarget.value)
			}} />
			<input type='text' placeholder="date placed" onChange={(e) => {
				setTempDatePlaced(e.currentTarget.value)
			}} />
			<br />
			<button className="border border-white p-1 mt-3 mb-5" onClick={() => {
				setShouldPushUpdates(true)
			}}>Search</button>

			<hr className="mb-5"/>
			<OrderTableList page={parseInt(page as string)} filter={parseInt(filter as string)} orderer={orderer} dateDue={dateDue} datePlaced={datePlaced}/>

			<h1 className="text-xl font-bold">Create new order</h1>
			<div className="inline-block w-100">
				<input className="inline-block w-20" placeholder="orderer" onChange={(e) => {
					setNewOrderOrderer(e.currentTarget.value)
				}}/>
				<DatePicker
					selected={newOrderDue}
					onChange={(date: Date | null) => setNewOrderDue(date)}
					dateFormat="MM/dd/yyyy" // Example format
					placeholderText="Due date"
					/>
				<br />
				<button onClick={() => {
					setShouldPushNewOrder(true)
				}}>Create</button>
			</div>
		</>
	)
}

export default OrderTable
