"use client"
import { useState } from "react"
import { useFieldArray, useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
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 { DateTimePicker } from "@/components/ui/date-time-picker"
import { useUpdateUserMutation } from "@/pages/users/update/queries"
import { userUpdateSchema, type UserUpdate } from "@/pages/users/update/schema"
import PageAddUserSelections from "../selections/addPage"

const UserForm = ({ refetchTable, initData, selectedUuid }: { refetchTable: () => void, initData: UserUpdate, selectedUuid: string }) => {

    const form = useForm<UserUpdate>({
        resolver: zodResolver(userUpdateSchema),
        defaultValues: {
            expiryStarts: initData.expiryStarts,
            expiryEnds: initData.expiryEnds,
            isConfirmed: initData.isConfirmed,
            isNotificationSend: initData.isNotificationSend,
            tag: initData.tag,
            email: initData.email,
            phone: initData.phone,
        },
    })

    const { handleSubmit } = form

    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 mutation = useUpdateUserMutation();
    function onSubmit(values: UserUpdate) { mutation.mutate({ data: values as any || initData, uuid: selectedUuid, selectedBuildIDS, selectedCompanyIDS, defaultSelection, refetchTable }); setTimeout(() => refetchTable(), 400) }

    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 }
