"use client";

import type { Dictionary } from "@/i18n/get-dictionary";
import { submitContactRequest } from "@/lib/actions/contact";
import { errorMessage } from "@/lib/forms/error-message";
import { useFormAction } from "@/lib/forms/use-form-action";
import { validateRequest } from "@/lib/forms/validation";
import { ArrowUpRightIcon } from "@/components/icons";
import { Button } from "@/components/ui/button";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Textarea } from "@/components/ui/textarea";
import { FormFailure } from "@/components/shared/form-failure";
import { FormSuccess } from "@/components/shared/form-success";
import { HiddenLabelInput } from "@/components/shared/hidden-label-input";
import { ServicePicker } from "@/components/shared/service-picker";

type FormText = Dictionary["home"]["contact"]["form"];

export function ContactForm({ t, formText }: { t: FormText; formText: Dictionary["forms"] }) {
  const { errors, onSubmit, onChange, pending, sent, failed, sendAgain } = useFormAction(submitContactRequest, validateRequest);
  const err = (field: string) => errorMessage(errors, formText.errors, field);

  if (sent) {
    const { sentTitle, sendAnother } = formText.status;
    return <FormSuccess title={sentTitle} message={t.success} againLabel={sendAnother} onAgain={sendAgain} className="w-full" />;
  }

  return (
    <form onSubmit={onSubmit} onChange={onChange} noValidate className="flex w-full flex-col items-center gap-5 md:gap-10">
      <FieldGroup>
        <div className="grid grid-cols-2 gap-5">
          <HiddenLabelInput name="fullName" label={t.fullName} required autoComplete="name" error={err("fullName")} />
          <HiddenLabelInput name="company" label={t.company} autoComplete="organization" />
          <HiddenLabelInput name="phone" label={t.phone} type="tel" required autoComplete="tel" error={err("phone")} />
          <HiddenLabelInput name="email" label={t.email} type="email" required autoComplete="email" error={err("email")} />
        </div>

        <ServicePicker name="service" legend={t.selectService} labels={t.services} />

        <Field>
          <FieldLabel htmlFor="contact-idea" className="sr-only">
            {t.idea}
          </FieldLabel>
          <Textarea id="contact-idea" name="idea" placeholder={t.idea} />
        </Field>

      </FieldGroup>

      {failed && <FormFailure message={formText.status.failed} className="w-full" />}

      <Button type="submit" variant="white" size="pill" disabled={pending} className="h-[50px] text-text-dark max-md:w-full md:max-lg:h-10 md:max-lg:text-sm">
        {pending ? t.sending : t.submit}
        <ArrowUpRightIcon data-icon="inline-end" className="rtl:-scale-x-100" />
      </Button>
    </form>
  );
}
