"use client";
import React, { useCallback } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { FormProvider } from "react-hook-form";
import { FormReset } from "@/components/form/form-reset";
import { FormSubmit } from "@/components/form/form-submit";
import { EditorLayout, EditorLayoutContent } from "@/components/layout/editor";
import { useProfileForm, ProfileForm, ProfileFormValues } from "@/components/dashboard/profile/forms/profile.form";
import { api } from "@/lib/trpc/client";
import type { AppRouterOutput } from "@/lib/trpc/router";
import { Routes } from "@/config/routes";

type Profile = NonNullable<AppRouterOutput["profile"]["get"]>;

type Props =
    | {
        mode: "create";
        id?: undefined;
    }
    | {
        mode: "edit";
        id: string;
        profile: Profile;
    };

export const ProfileEditor: React.FC<Props> = (props) => {
    const router = useRouter();
    const t = useTranslations("dashboard.profile");

    const createMutation = api.profile.create.useMutation({
        onSuccess(profile) {
            router.replace(Routes.DASHBOARD.PROFILE_EDIT(profile.id));
        }
    });

    const updateMutation = api.profile.update.useMutation();

    const form = useProfileForm({
        values: props.mode === "edit" ? props.profile : undefined
    });

    const handleSubmit = useCallback(async (data: ProfileFormValues) => {
        switch(props.mode) {
            case "create":
                await createMutation.mutateAsync({
                    data: data
                });
                break;

            case "edit":
                await updateMutation.mutateAsync({
                    id: props.id,
                    data: data
                });
                break;
        }
    }, [createMutation, updateMutation, props.mode, props.id]);

    return (
        <FormProvider {...form}>
            <EditorLayout>
                <EditorLayoutContent>
                    <ProfileForm
                      id="profile-editor"
                      formControl={form}
                      className="contents"
                      values={props.mode === "edit" ? props.profile : undefined}
                      onSubmit={handleSubmit} />

                    <div className="flex justify-end gap-2 px-4 pt-5">
                        {props.mode === "edit" && (
                            <FormReset>{t("actions.cancel")}</FormReset>
                        )}

                        <FormSubmit form="profile-editor">
                            {props.mode === "create" ? t("actions.create") : t("actions.update")}
                        </FormSubmit>
                    </div>
                </EditorLayoutContent>
            </EditorLayout>
        </FormProvider>
    );
};
