'use client';

import { useActionState } from 'react';
import Link from 'next/link';
import { login, signup, type AuthFormState } from '@/app/actions/auth';
import { Field, FormMessage, SubmitButton } from '@/components/ui/Field';
import { useMessages } from '@/i18n/client';

function withNext(path: string, next?: string) {
  return next ? `${path}?next=${encodeURIComponent(next)}` : path;
}

export function LoginForm({ next }: { next?: string }) {
  const t = useMessages().auth;
  const [state, action] = useActionState<AuthFormState | undefined, FormData>(login, undefined);

  return (
    <form action={action} className="space-y-5" noValidate>
      <input type="hidden" name="next" value={next ?? ''} />
      <FormMessage>{state?.message}</FormMessage>
      <Field
        label={t.fields.email}
        name="email"
        type="email"
        autoComplete="email"
        inputMode="email"
        required
        defaultValue={state?.values?.email}
        errors={state?.errors?.email}
      />
      <Field
        label={t.fields.password}
        name="password"
        type="password"
        autoComplete="current-password"
        required
        errors={state?.errors?.password}
      />
      <SubmitButton className="mt-2">{t.login.submit}</SubmitButton>
      <p className="text-center text-sm text-muted">
        {t.login.noAccount}{' '}
        <Link href={withNext('/daftar', next)} className="font-semibold text-ink hover:underline">
          {t.login.signup}
        </Link>
      </p>
    </form>
  );
}

export function SignupForm({ next }: { next?: string }) {
  const t = useMessages().auth;
  const [state, action] = useActionState<AuthFormState | undefined, FormData>(signup, undefined);

  return (
    <form action={action} className="space-y-5" noValidate>
      <input type="hidden" name="next" value={next ?? ''} />
      <FormMessage>{state?.message}</FormMessage>
      <Field
        label={t.fields.name}
        name="name"
        autoComplete="name"
        required
        defaultValue={state?.values?.name}
        errors={state?.errors?.name}
      />
      <Field
        label={t.fields.email}
        name="email"
        type="email"
        autoComplete="email"
        inputMode="email"
        required
        defaultValue={state?.values?.email}
        errors={state?.errors?.email}
      />
      <Field
        label={t.fields.password}
        name="password"
        type="password"
        autoComplete="new-password"
        required
        hint={t.fields.passwordHint}
        errors={state?.errors?.password}
      />
      <SubmitButton className="mt-2">{t.signup.submit}</SubmitButton>
      <p className="text-center text-sm text-muted">
        {t.signup.haveAccount}{' '}
        <Link href={withNext('/masuk', next)} className="font-semibold text-ink hover:underline">
          {t.signup.login}
        </Link>
      </p>
    </form>
  );
}
