"use client"

import * as yup from "yup";
import {ArrowLeft} from "lucide-react";
import {Button} from "@/components/ui/button";
import {StepOne} from "@/app/(auth)/onboarding/_patients/step_one";
import {useFormik} from "formik";
import {useState} from "react";
import {StepTwo} from "@/app/(auth)/onboarding/_patients/step_two";
import {cn} from "@/lib/utils";
import {StepThree} from "@/app/(auth)/onboarding/_patients/step_three";
import {AppriteActionReturnStatus, PatientProfile} from "@/lib/backend/appwrite_types";
import {useRouter} from "next/navigation";
import {PATIENT_DASHBOARD_URL} from "@/lib/constants";


export type PatientStepOneOnboardingValues = {
    age: string;
    gender: string;
    location: string;
}

export type PatientStepTwoOnboardingValues = {
    employment_status: string;
    relationship_status: string;
}


export type PatientStepThreeOnboardingValues = {
    current_medication_specify: boolean;
    current_medication: string;

    medical_conditions_specify: boolean;
    medical_conditions: string;

    preferred_language_specify: boolean;
    preferred_language: string;
}

export default function PatientOnboarding(
    {
        updatePatientProfile,
        userId
    }: { updatePatientProfile: (props: Partial<PatientProfile>, userId: string) => Promise<AppriteActionReturnStatus>, userId: string }
) {

    const router = useRouter();
    const [progress, setProgress] = useState<number>(1);
    const [updateError, setUpdateError] = useState<boolean>(false);

    const stepOneFormik = useFormik<PatientStepOneOnboardingValues>({
        initialValues: {
            age: '', gender: '', location: ''
        },
        validationSchema: yup.object({
            age: yup.string().required("Age required."),
            gender: yup.string().required("Gender required"),
            location: yup.string().required("Location is required."),
        }),
        onSubmit: async (values) => {
            setProgress(2)
        }
    })
    const stepTwoFormik = useFormik<PatientStepTwoOnboardingValues>({
        initialValues: {
            relationship_status: '', employment_status: ''
        },
        validationSchema: yup.object({
            relationship_status: yup.string().required("Field required."),
            employment_status: yup.string().required("Field required"),
        }),
        onSubmit: async (values) => {
            setProgress(3)
        }
    })
    const stepThreeFormik = useFormik<PatientStepThreeOnboardingValues>({
        initialValues: {
            current_medication: '', medical_conditions: '', preferred_language: 'english',
            current_medication_specify: false,
            medical_conditions_specify: false,
            preferred_language_specify: false
        },
        validationSchema: yup.object({
            current_medication_specify: yup.boolean(),
            medical_conditions_specify: yup.boolean(),
            preferred_language_specify: yup.boolean(),

            current_medication: yup.string().when("current_medication_specify", {
                is: (val) => {
                    return val
                },
                then: (s) => s.required("Field is required.")
            }),
            medical_conditions: yup.string().when("medical_conditions_specify", {
                is: (val) => {
                    return val
                },
                then: (s) => s.required("Field is required.")
            }),
            preferred_language: yup.string().required("Field is required.")
        }),
        onSubmit: async (values) => {
            setUpdateError(false)

            let _current_medication = null
            let _medical_conditions = null

            if (values.current_medication_specify) {
                _current_medication = values.current_medication
            }
            if (values.medical_conditions_specify) {
                _medical_conditions = values.medical_conditions
            }

            const response = await updatePatientProfile({
                userId: userId,
                age: stepOneFormik.values.age,
                gender: stepOneFormik.values.gender,
                location: stepOneFormik.values.location,
                employmentStatus: stepTwoFormik.values.employment_status,
                relationshipStatus: stepTwoFormik.values.relationship_status,
                currentMedication: _current_medication,
                medicalConditions: _medical_conditions,
                preferredLanguage: values.preferred_language
            }, userId)

            if (response.code === 200) {
                await router.replace(PATIENT_DASHBOARD_URL)
            } else {
                setUpdateError(true)
                stepThreeFormik.setFieldError("preferred_language", response.message)
            }
        }
    })


    return (
        <div
            className="my-4 container-auto w-full max-w-md p-4 bg-white border border-gray-200 rounded-lg shadow sm:p-6 md:p-8 dark:bg-gray-800 dark:border-gray-700">
            <div className="space-y-6">

                <div className="flex flex-col space-y-2">
                    <p className="text-xs font-bold text-gray-600">Step {progress} of 3</p>
                    <div className="w-full grid grid-cols-3 space-x-2">
                        <span className={cn("rounded-lg h-1 border-[3px] border-gray-300", {
                            "border-primary": progress >= 1
                        })}/>
                        <span className={cn("rounded-lg h-1 border-[3px] border-gray-300", {
                            "border-primary": progress >= 2
                        })}/>
                        <span className={cn("rounded-lg h-1 border-[3px] border-gray-300", {
                            "border-primary": progress >= 3
                        })}/>
                    </div>

                    {
                        progress > 1 &&
                        <div className="flex items-center space-x-1">
                            <ArrowLeft size={"16"} className="text-primary"/>
                            <Button variant={"ghost"} size={"sm"} className="p-2 text-primary" onClick={() => {
                                setProgress(prevState => prevState - 1)
                            }}>
                                Back
                            </Button>
                        </div>
                    }
                </div>

                {
                    progress === 1 &&
                    <StepOne formik={stepOneFormik}/>
                }

                {
                    progress === 2 &&
                    <StepTwo formik={stepTwoFormik}/>
                }

                {
                    progress === 3 &&
                    <StepThree formik={stepThreeFormik}/>
                }

                {
                    updateError &&
                    <p className={"text-sm text-red-500"}>
                        Failed to update user details (code 500). Try again or contact
                        the server administrator.
                    </p>
                }

            </div>
        </div>
    )
}