"use client"
import { useState, useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { userAddSchema, type UserAdd } from "./schema"
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Separator } from "@/components/ui/separator"
import { useAddUserMutation } from "./queries"
import { DateTimePicker } from "@/components/ui/date-time-picker"
import PageAddUserSelections from "../selections/addPage"

const UserForm = ({ refetchTable }: { refetchTable: () => void }) => {
    const form = useForm<UserAdd>({
        resolver: zodResolver(userAddSchema),
        defaultValues: {
            expiryStarts: "",
            expiryEnds: "",
            isConfirmed: false,
            isNotificationSend: false,
            password: "",
            rePassword: "",
            tag: "",
            email: "",
            phone: ""
        },
    })

    const [defaultSelection, setDefaultSelection] = useState<string>("")
    const [selectedBuildIDS, setSelectedBuildIDS] = useState<string[]>([])
    const [selectedCompanyIDS, setSelectedCompanyIDS] = useState<string[]>([])

    const appendBuildID = (id: string) => setSelectedBuildIDS((prev) => (id && !selectedBuildIDS.includes(id) ? [...prev, id] : prev))
    const appendCompanyID = (id: string) => setSelectedCompanyIDS((prev) => (id && !selectedCompanyIDS.includes(id) ? [...prev, id] : prev))

    const removeBuildID = (id: string) => setSelectedBuildIDS((prev) => prev.filter((item) => item !== id))
    const removeCompanyID = (id: string) => setSelectedCompanyIDS((prev) => prev.filter((item) => item !== id))

    const { handleSubmit } = form
    const mutation = useAddUserMutation();
    function onSubmit(values: UserAdd) { mutation.mutate({ data: values as any, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }); }

    return (
        <div>
            <PageAddUserSelections
                selectedCompanyIDS={selectedCompanyIDS} selectedBuildingIDS={selectedBuildIDS} appendCompanyID={appendCompanyID} appendBuildingID={appendBuildID}
                removeCompanyID={removeCompanyID} removeBuildingID={removeBuildID} defaultSelection={defaultSelection} setDefaultSelection={setDefaultSelection}
            />
            <Form {...form}>
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-6 p-4">
                    {/* BASIC INFO */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <FormField
                            control={form.control}
                            name="email"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Email</FormLabel>
                                    <FormControl>
                                        <Input placeholder="user@example.com" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="phone"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Phone</FormLabel>
                                    <FormControl>
                                        <Input placeholder="+901234567" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    </div>

                    {/* PASSWORD / TAG */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <FormField
                            control={form.control}
                            name="password"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Password</FormLabel>
                                    <FormControl>
                                        <Input type="password" placeholder="•••••••" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="rePassword"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Re-Password</FormLabel>
                                    <FormControl>
                                        <Input type="password" placeholder="•••••••" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="tag"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Tag</FormLabel>
                                    <FormControl>
                                        <Input placeholder="User tag..." {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        {/* SWITCHES */}
                        <div className="flex items-center gap-6">
                            <FormField
                                control={form.control}
                                name="isConfirmed"
                                render={({ field }) => (
                                    <FormItem className="flex items-center gap-2">
                                        <FormControl>
                                            <Checkbox
                                                checked={field.value}
                                                onCheckedChange={field.onChange}
                                            />
                                        </FormControl>
                                        <FormLabel className="mt-0!">Confirmed</FormLabel>
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="isNotificationSend"
                                render={({ field }) => (
                                    <FormItem className="flex items-center gap-2">
                                        <FormControl>
                                            <Checkbox
                                                checked={field.value}
                                                onCheckedChange={field.onChange}
                                            />
                                        </FormControl>
                                        <FormLabel className="mt-0!">Send Notification</FormLabel>
                                    </FormItem>
                                )}
                            />
                        </div>
                    </div>

                    {/* DATES */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <FormField
                            control={form.control}
                            name="expiryStarts"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Expiry Starts</FormLabel>
                                    <FormControl>
                                        <DateTimePicker {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="expiryEnds"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Expiry Ends</FormLabel>
                                    <FormControl>
                                        <DateTimePicker {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    </div>

                    <Separator />
                    <Button type="submit" className="w-full">Create User</Button>
                </form>
            </Form>
        </div>
    )
}

export { UserForm }
