import { useAppForm } from '@hooks/use-app-form';
import { m } from '@paraglide/messages';
import { Locale, setLocale } from '@paraglide/runtime';
import { GearIcon } from '@phosphor-icons/react';
import { settingQueries } from '@service/queries';
import { updateUserSettings } from '@service/setting.api';
import { UserSettingInput, userSettingSchema } from '@service/setting.schema';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from '@ui/card';
import { Field, FieldGroup } from '@ui/field';
import { Skeleton } from '@ui/skeleton';
import { useEffect } from 'react';
import { toast } from 'sonner';

const defaultValues: UserSettingInput = {
  language: '',
};

const UserSettingsForm = () => {
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery(settingQueries.listUser());

  const { mutate: updateMutation, isPending } = useMutation({
    mutationFn: updateUserSettings,
    onSuccess: (_, variables) => {
      setLocale(variables.data.language as Locale);
      queryClient.invalidateQueries({
        queryKey: [...settingQueries.all, 'listUser'],
      });
      toast.success(m.settings_messages_update_success(), {
        richColors: true,
      });
    },
    onError: (error: ReturnError) => {
      console.error(error);
      const code = error.code as Parameters<
        typeof m.backend_message
      >[0]['code'];
      toast.error(m.backend_message({ code }), {
        richColors: true,
      });
    },
  });

  const form = useAppForm({
    defaultValues,
    validators: {
      onSubmit: userSettingSchema,
      onChange: userSettingSchema,
    },
    onSubmit: ({ value }) => {
      updateMutation({ data: value as UserSettingInput });
    },
  });

  useEffect(() => {
    if (data?.value?.language) {
      setTimeout(() => {
        form.setFieldValue('language', data.value.language);
      }, 0);
    }
  }, [data, form]);

  if (isLoading)
    return (
      <div>
        <Skeleton className="h-40 w-full" />
      </div>
    );

  return (
    <Card className="@container/card col-span-1 @xl/main:col-span-2">
      <CardHeader>
        <CardTitle className="text-xl flex items-center gap-2">
          <GearIcon size={20} />
          {m.settings_ui_title()}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <form
          id="user-settings-form"
          onSubmit={(e) => {
            e.preventDefault();
            e.stopPropagation();
            form.handleSubmit();
          }}
        >
          <FieldGroup>
            <form.AppField name="language">
              {(field) => (
                <field.Select
                  label={m.settings_form_language()}
                  placeholder={m.settings_form_select_language()}
                  values={[
                    { value: 'en', label: 'English' },
                    { value: 'vi', label: 'Tiếng Việt' },
                  ]}
                />
              )}
            </form.AppField>
            <Field>
              <form.AppForm>
                <form.SubscribeButton
                  label={m.ui_update_btn()}
                  disabled={isPending}
                />
              </form.AppForm>
            </Field>
          </FieldGroup>
        </form>
      </CardContent>
    </Card>
  );
};

export default UserSettingsForm;
