"use client";

import {useRouter} from "next/navigation";
import {useForm} from "react-hook-form";
import {z} from "zod";
import {zodResolver} from "@hookform/resolvers/zod";
import {Button} from "@/components/ui/button";
import {CalendarIcon, ChevronLeft} from "lucide-react";
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card";
import {Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage} from "@/components/ui/form";
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
import {Input} from "@/components/ui/input";
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
import {cn} from "@/lib/utils";
import {format} from "date-fns";
import {Calendar} from "@/components/ui/calendar";
import {
    MultiSelector,
    MultiSelectorContent,
    MultiSelectorInput, MultiSelectorItem, MultiSelectorList,
    MultiSelectorTrigger
} from "@/components/ui/select-multiple";
import {
    titlesOptions,
    languageOptions,
    skillsOptions,
    AddClientFormSchema
} from "@/app/(admin)/admin/manage-clients/_components/data";
import {createClientProfile} from "@/lib/backend/api";
import {toast} from "@/components/ui/use-toast";
import {ADMIN_MANAGE_CLIENT_URL} from "@/lib/constants";


export default function AddClientForm() {

    const router = useRouter()

    const form = useForm<z.infer<typeof AddClientFormSchema>>({
        resolver: zodResolver(AddClientFormSchema),
        defaultValues: {
            title: "Mr",
            first_name: "",
            last_name: "",
            physical_address: "",
            specialized_skills: [],
            languages: []
        }
    })

    async function onSubmit(data: z.infer<typeof AddClientFormSchema>) {

        const response = await createClientProfile({
            title: data.title,
            first_name: data.first_name,
            last_name: data.last_name,
            email: data.email,
            phone_number: data.phone_number,
            emergency_contact: data.emergency_contact,
            physical_address: data.physical_address,
            dob: data.dob,
            specialized_skills: data.specialized_skills,
            languages: data.languages,
            nursing_licence_number: data.nursing_licence_number,
            qualification_earned: data.qualification_earned,
            nursing_school: data.nursing_school,
            graduation_date: data.graduation_date
        })

        if (response.code !== 200) {
            form.setError("email", {
                message: "Failed to add new client."
            })

            toast({
                variant: "destructive",
                title: "Operation Failed",
                description: `Failed to add new client: ${response.message}`,
            })

        } else {
            toast({
                title: "Operation Successful",
                description: `Client added successfully: ${data.first_name}`,
            })
            await router.push(ADMIN_MANAGE_CLIENT_URL)
        }

    }


    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">

                {/* top header */}
                <div className="flex items-center gap-4">
                    <Button variant="outline" size="icon" className="h-7 w-7" onClick={() => {
                        router.back()
                    }}>
                        <ChevronLeft className="h-4 w-4"/>
                        <span className="sr-only">Back</span>
                    </Button>
                    <div className="hidden items-center gap-2 md:ml-auto md:flex">
                        <Button variant="outline" size="sm">
                            Discard
                        </Button>
                        <Button size="sm" type={"submit"}>Save Client</Button>
                    </div>
                </div>


                <div className="grid lg:grid-cols-[1fr_450px] auto-rows-max items-start  gap-4 py-4">
                    {/* client personal information */}
                    <Card>
                        <CardHeader>
                            <CardTitle>Personal Information</CardTitle>
                            <CardDescription>
                                Fill in client personal information.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="grid md:grid-cols-2 gap-6">

                                <div className={"flex gap-x-4"}>

                                    {/* title */}
                                    <FormField
                                        control={form.control}
                                        name="title"
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>Title*</FormLabel>
                                                <FormControl>
                                                    <Select value={field.value} onValueChange={field.onChange}>
                                                        <SelectTrigger className="w-[100px]">
                                                            <SelectValue placeholder="Mr" {...field}/>
                                                        </SelectTrigger>
                                                        <SelectContent>
                                                            {titlesOptions.map((titleOption, index) => {
                                                                return (
                                                                    <SelectItem value={titleOption.value} key={index}>
                                                                        {titleOption.label}
                                                                    </SelectItem>
                                                                )
                                                            })}
                                                        </SelectContent>
                                                    </Select>
                                                </FormControl>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />

                                    {/* first name */}
                                    <FormField
                                        control={form.control}
                                        name="first_name"
                                        render={({field}) => (
                                            <FormItem className={"flex-1"}>
                                                <FormLabel>First Name*</FormLabel>
                                                <FormControl>
                                                    <Input placeholder="John" {...field} />
                                                </FormControl>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />
                                </div>

                                {/* last name */}
                                <FormField
                                    control={form.control}
                                    name="last_name"
                                    render={({field}) => (
                                        <FormItem className={"flex-1"}>
                                            <FormLabel>Last Name*</FormLabel>
                                            <FormControl>
                                                <Input placeholder="Doe" {...field} />
                                            </FormControl>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />

                                {/* email address */}
                                <FormField
                                    control={form.control}
                                    name="email"
                                    render={({field}) => (
                                        <FormItem>
                                            <FormLabel>Email Address*</FormLabel>
                                            <FormControl>
                                                <Input placeholder="johndoe@gmail.com" {...field} />
                                            </FormControl>
                                            <FormDescription>
                                                This email will be used to receive credentials for the client.
                                            </FormDescription>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />


                                {/* date of birth */}
                                <FormField
                                    control={form.control}
                                    name="dob"
                                    render={({field}) => (
                                        <FormItem className="flex flex-col">
                                            <FormLabel className={"mb-2"}>Date of birth*</FormLabel>
                                            <Popover>
                                                <PopoverTrigger asChild>
                                                    <FormControl>
                                                        <Button
                                                            variant={"outline"}
                                                            className={cn(
                                                                "w-[240px] pl-3 text-left font-normal",
                                                                !field.value && "text-muted-foreground"
                                                            )}
                                                        >
                                                            {field.value ? (
                                                                format(field.value, "PPP")
                                                            ) : (
                                                                <span>Pick a date</span>
                                                            )}
                                                            <CalendarIcon className="ml-auto h-4 w-4 opacity-50"/>
                                                        </Button>
                                                    </FormControl>
                                                </PopoverTrigger>
                                                <PopoverContent className="w-auto p-0" align="start">
                                                    <Calendar
                                                        mode="single"
                                                        selected={field.value}
                                                        onSelect={field.onChange}
                                                        disabled={(date) =>
                                                            date > new Date() || date < new Date("1900-01-01")
                                                        }
                                                        initialFocus
                                                    />
                                                </PopoverContent>
                                            </Popover>
                                            <FormDescription>
                                                Your date of birth is used to calculate your age.
                                            </FormDescription>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />


                                {/* phone number */}
                                <FormField
                                    control={form.control}
                                    name="phone_number"
                                    render={({field}) => (
                                        <FormItem>
                                            <FormLabel>Phone Number*</FormLabel>
                                            <FormControl>
                                                <Input placeholder="+26876------" {...field} />
                                            </FormControl>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />


                                {/* emergency contact */}
                                <FormField
                                    control={form.control}
                                    name="emergency_contact"
                                    render={({field}) => (
                                        <FormItem>
                                            <FormLabel>Emergency Contact</FormLabel>
                                            <FormControl>
                                                <Input type={'tel'} placeholder="+26876------" {...field} />
                                            </FormControl>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />

                                {/* physical address */}
                                <FormField
                                    control={form.control}
                                    name="physical_address"
                                    render={({field}) => (
                                        <FormItem className={"col-span-2"}>
                                            <FormLabel>Physical Address</FormLabel>
                                            <FormControl>
                                                <Input {...field} />
                                            </FormControl>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />

                            </div>
                        </CardContent>
                    </Card>


                    {/* Skills and Competencies */}
                    <Card>
                        <CardHeader>
                            <CardTitle>Skills and Competencies</CardTitle>
                            <CardDescription>
                                Client's skills, specializations and competencies.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="grid gap-3">
                                {/* skills and specializations */}
                                <div>
                                    <FormField
                                        control={form.control}
                                        name="specialized_skills"
                                        render={({field}) => (
                                            <FormItem className={"col-span-2"}>
                                                <FormLabel>Specialized skills*</FormLabel>
                                                <MultiSelector
                                                    values={field.value || []}
                                                    onValuesChange={field.onChange} loop={false}>
                                                    <MultiSelectorTrigger>
                                                        <MultiSelectorInput
                                                            placeholder="Select specialized skills"/>
                                                    </MultiSelectorTrigger>
                                                    <MultiSelectorContent>
                                                        <MultiSelectorList>
                                                            {skillsOptions.map((option, i) => (
                                                                <MultiSelectorItem key={i} value={option.value}>
                                                                    {option.label}
                                                                </MultiSelectorItem>
                                                            ))}
                                                        </MultiSelectorList>
                                                    </MultiSelectorContent>
                                                </MultiSelector>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />
                                </div>


                                {/* languages */}
                                <div>
                                    <FormField
                                        control={form.control}
                                        name="languages"
                                        render={({field}) => (
                                            <FormItem className={"col-span-2"}>
                                                <FormLabel>Languages Spoken*</FormLabel>
                                                <MultiSelector
                                                    values={field.value}
                                                    onValuesChange={field.onChange} loop={false}>
                                                    <MultiSelectorTrigger>
                                                        <MultiSelectorInput placeholder="Select languages spoken"/>
                                                    </MultiSelectorTrigger>
                                                    <MultiSelectorContent>
                                                        <MultiSelectorList>
                                                            {languageOptions.map((option, i) => (
                                                                <MultiSelectorItem key={i} value={option.value}>
                                                                    {option.label}
                                                                </MultiSelectorItem>
                                                            ))}
                                                        </MultiSelectorList>
                                                    </MultiSelectorContent>
                                                </MultiSelector>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />
                                </div>


                            </div>
                        </CardContent>
                    </Card>


                    {/* client professional information */}
                    <Card>
                        <CardHeader>
                            <CardTitle>Professional Information</CardTitle>
                            <CardDescription>
                                Fill in client's professional information.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>

                            <div className="grid md:grid-cols-2 gap-6">

                                {/* nursingLicenceNumber */}
                                <FormField
                                    control={form.control}
                                    name="nursing_licence_number"
                                    render={({field}) => (
                                        <FormItem>
                                            <FormLabel>Nursing licence number*</FormLabel>
                                            <FormControl>
                                                <Input {...field} />
                                            </FormControl>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />

                                {/* qualificationEarned */}
                                <FormField
                                    control={form.control}
                                    name="qualification_earned"
                                    render={({field}) => (
                                        <FormItem>
                                            <FormLabel>Highest qualification earned*</FormLabel>
                                            <FormControl>
                                                <Input {...field} />
                                            </FormControl>
                                            <FormDescription>
                                                The most recent, highest qualification earned by client.
                                            </FormDescription>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />


                                {/* graduationDate */}
                                <FormField
                                    control={form.control}
                                    name="graduation_date"
                                    render={({field}) => (
                                        <FormItem className="flex flex-col">
                                            <FormLabel>Graduation date*</FormLabel>
                                            <Popover>
                                                <PopoverTrigger asChild>
                                                    <FormControl>
                                                        <Button
                                                            variant={"outline"}
                                                            className={cn(
                                                                "w-[240px] pl-3 text-left font-normal",
                                                                !field.value && "text-muted-foreground"
                                                            )}
                                                        >
                                                            {field.value ? (
                                                                format(field.value, "PPP")
                                                            ) : (
                                                                <span>Pick a date</span>
                                                            )}
                                                            <CalendarIcon className="ml-auto h-4 w-4 opacity-50"/>
                                                        </Button>
                                                    </FormControl>
                                                </PopoverTrigger>
                                                <PopoverContent className="w-auto p-0" align="start">
                                                    <Calendar
                                                        mode="single"
                                                        selected={field.value}
                                                        onSelect={field.onChange}
                                                        disabled={(date) =>
                                                            date > new Date() || date < new Date("1900-01-01")
                                                        }
                                                        initialFocus
                                                    />
                                                </PopoverContent>
                                            </Popover>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />


                                {/* nursingSchool */}
                                <FormField
                                    control={form.control}
                                    name="nursing_school"
                                    render={({field}) => (
                                        <FormItem>
                                            <FormLabel>Nursing school attended*</FormLabel>
                                            <FormControl>
                                                <Input {...field} />
                                            </FormControl>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />

                            </div>
                        </CardContent>
                    </Card>


                </div>

            </form>
        </Form>
    )
}