"use client";

import { useState } from "react";
import type { Dictionary } from "@/i18n/get-dictionary";
import { submitJobApplication } from "@/lib/actions/job-application";
import { errorMessage } from "@/lib/forms/error-message";
import { useFormAction } from "@/lib/forms/use-form-action";
import { validateApplication } from "@/lib/forms/validation";
import { FormFailure } from "@/components/shared/form-failure";
import { FormFooter } from "@/components/shared/form-footer";
import { FormSuccess } from "@/components/shared/form-success";
import { HiddenLabelInput } from "@/components/shared/hidden-label-input";
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldError, FieldLabel } from "@/components/ui/field";
import { Textarea } from "@/components/ui/textarea";
import { CvUpload } from "./cv-upload";
import { FormGroup } from "./form-group";

type ApplicationFormProps = {
  t: Dictionary["apply"]["form"];
  formText: Dictionary["forms"];
  /** Slug of the job applied for; empty for the general application. */
  job?: string;
};

/**
 * "Candidate information" card (Figma Job Application): personal details, profile + CV, the application texts,
 * the consent box, then Cancel / Send Application. Cancel clears everything (including the file and the box).
 */
export function ApplicationForm({ t, formText, job }: ApplicationFormProps) {
  const { errors, onSubmit, onChange, clear, reset, pending, sent, failed, sendAgain } = useFormAction(submitJobApplication, validateApplication);
  const [formKey, setFormKey] = useState(0);
  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} />;
  }

  const textarea = (name: string, label: string) => (
    <Field>
      <FieldLabel htmlFor={`application-${name}`} className="sr-only">
        {label}
      </FieldLabel>
      <Textarea id={`application-${name}`} name={name} placeholder={label} />
    </Field>
  );

  return (
    <form key={formKey} onSubmit={onSubmit} onChange={onChange} noValidate>
      {job && <input type="hidden" name="job" value={job} />}
      <div className="flex flex-col gap-10 p-5">
        <FormGroup title={t.personal}>
          <div className="grid grid-cols-2 gap-5">
            <HiddenLabelInput name="fullName" label={t.fullName} required autoComplete="name" error={err("fullName")} />
            <HiddenLabelInput name="email" label={t.email} type="email" required autoComplete="email" error={err("email")} />
            <HiddenLabelInput name="phone" label={t.phone} type="tel" required autoComplete="tel" error={err("phone")} />
            <HiddenLabelInput name="location" label={t.location} required autoComplete="address-level2" error={err("location")} />
          </div>
          {textarea("message", t.message)}
        </FormGroup>

        <FormGroup title={t.profile}>
          <div className="grid grid-cols-2 gap-5">
            <HiddenLabelInput name="linkedin" label={t.linkedin} type="url" autoComplete="url" error={err("linkedin")} />
            <HiddenLabelInput name="portfolio" label={t.portfolio} type="url" error={err("portfolio")} />
          </div>
          <CvUpload labels={{ upload: t.cvUpload, drag: t.cvDrag, hint: t.cvHint, remove: t.cvRemove }} error={err("cv")} />
        </FormGroup>

        <FormGroup title={t.application}>
          {textarea("why", t.whyInterested)}
          {textarea("coverLetter", t.coverLetter)}
        </FormGroup>

        <Field orientation="horizontal" data-invalid={err("consent") ? true : undefined} className="items-start gap-3 border-t border-white/7 pt-5">
          <Checkbox
            id="application-consent"
            name="consent"
            value="yes"
            onCheckedChange={() => clear("consent")}
            aria-invalid={err("consent") ? true : undefined}
            aria-describedby={err("consent") ? "application-consent-error" : undefined}
            className="mt-1"
          />
          <div className="flex flex-col gap-1">
            <FieldLabel htmlFor="application-consent" className="text-xs leading-6 font-normal text-soft">
              {t.consent}
            </FieldLabel>
            {err("consent") && (
              <FieldError id="application-consent-error" className="text-xs leading-4">
                {err("consent")}
              </FieldError>
            )}
          </div>
        </Field>

        {failed && <FormFailure message={formText.status.failed} />}
      </div>

      <FormFooter
        cancelLabel={t.cancel}
        submitLabel={pending ? t.sending : t.submit}
        pending={pending}
        onCancel={() => {
          reset();
          setFormKey((k) => k + 1);
        }}
      />
    </form>
  );
}
