'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';

import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
import type { AccountWithParams } from '@kit/accounts/types/accounts';
import { Button } from '@kit/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@kit/ui/form';
import { Input } from '@kit/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@kit/ui/select';
import { toast } from '@kit/ui/sonner';
import { Trans } from '@kit/ui/trans';

import {
  AccountSettings,
  accountSettingsSchema,
} from '../_lib/account-settings.schema';
import { updatePersonalAccountAction } from '../_lib/server/actions';

export default function AccountSettingsForm({
  account,
}: {
  account: AccountWithParams | null;
}) {
  const revalidateUserDataQuery = useRevalidatePersonalAccountDataQuery();

  const form = useForm({
    resolver: zodResolver(accountSettingsSchema),
    defaultValues: {
      firstName: account?.name,
      lastName: account?.last_name ?? '',
      email: account?.email,
      phone: account?.phone ?? '',
      accountParams: {
        height: account?.accountParams?.height,
        weight: account?.accountParams?.weight,
        isSmoker: account?.accountParams?.isSmoker,
      },
    },
  });

  const { handleSubmit } = form;

  const onSubmit = async (data: AccountSettings) => {
    if (!account?.id) {
      return toast.error(<Trans i18nKey="account:updateAccountError" />);
    }

    const result = await updatePersonalAccountAction({
      accountId: account.id,
      data,
    });

    if (result.success) {
      revalidateUserDataQuery(account.primary_owner_user_id);
      return toast.success(<Trans i18nKey="account:updateAccountSuccess" />);
    }
    return toast.error(<Trans i18nKey="account:updateAccountError" />);
  };

  if (!account) return null;

  return (
    <Form {...form}>
      <form
        className="flex flex-col gap-6 text-left"
        onSubmit={handleSubmit(onSubmit)}
      >
        <FormField
          name={'firstName'}
          render={({ field }) => {
            return (
              <FormItem>
                <FormLabel>
                  <Trans i18nKey={'common:formField.firstName'} />
                </FormLabel>

                <FormControl>
                  <Input {...field} />
                </FormControl>

                <FormMessage />
              </FormItem>
            );
          }}
        />

        <FormField
          name={'lastName'}
          render={({ field }) => {
            return (
              <FormItem>
                <FormLabel>
                  <Trans i18nKey={'common:formField.lastName'} />
                </FormLabel>

                <FormControl>
                  <Input {...field} />
                </FormControl>

                <FormMessage />
              </FormItem>
            );
          }}
        />

        <div className="grid grid-cols-2 gap-4">
          <FormField
            name={'accountParams.height'}
            render={({ field }) => {
              return (
                <FormItem>
                  <FormLabel>
                    <Trans i18nKey={'common:formField.height'} />
                  </FormLabel>

                  <FormControl>
                    <Input placeholder="cm" type="number" {...field} />
                  </FormControl>

                  <FormMessage />
                </FormItem>
              );
            }}
          />

          <FormField
            name={'accountParams.weight'}
            render={({ field }) => {
              return (
                <FormItem>
                  <FormLabel>
                    <Trans i18nKey={'common:formField.weight'} />
                  </FormLabel>

                  <FormControl>
                    <Input placeholder="kg" type="number" {...field} />
                  </FormControl>

                  <FormMessage />
                </FormItem>
              );
            }}
          />
        </div>

        <FormField
          name={'phone'}
          render={({ field }) => {
            return (
              <FormItem>
                <FormLabel>
                  <Trans i18nKey={'common:formField.phone'} />
                </FormLabel>

                <FormControl>
                  <Input {...field} />
                </FormControl>

                <FormMessage />
              </FormItem>
            );
          }}
        />
        <FormField
          name={'email'}
          render={({ field }) => {
            return (
              <FormItem>
                <FormLabel>
                  <Trans i18nKey={'common:formField.email'} />
                </FormLabel>

                <FormControl>
                  <Input {...field} />
                </FormControl>

                <FormMessage />
              </FormItem>
            );
          }}
        />

        <div className="space-y-4">
          <h2 className="text-xl font-semibold text-gray-900">
            <Trans i18nKey="account:myHabits" />
          </h2>

          <FormField
            name="accountParams.isSmoker"
            render={({ field }) => (
              <FormItem>
                <FormLabel>
                  <Trans i18nKey={'common:formField.smoking'} />
                </FormLabel>

                <FormControl>
                  <Select
                    value={
                      field.value === true
                        ? 'yes'
                        : field.value === false
                          ? 'no'
                          : 'preferNotToAnswer'
                    }
                    onValueChange={(value) => {
                      if (value === 'yes') {
                        field.onChange(true);
                      } else if (value === 'no') {
                        field.onChange(false);
                      } else {
                        field.onChange(null);
                      }
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="yes">
                        <Trans i18nKey="common:yes" />
                      </SelectItem>
                      <SelectItem value="no">
                        <Trans i18nKey="common:no" />
                      </SelectItem>
                      <SelectItem value="preferNotToAnswer">
                        <Trans i18nKey="common:preferNotToAnswer" />
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </FormControl>
              </FormItem>
            )}
          />
        </div>

        <Button type="submit" className="w-36">
          <Trans i18nKey="account:updateProfileSubmitLabel" />
        </Button>
      </form>
    </Form>
  );
}
