"use client";

import { FormServerErrors } from "@/components/form-common/form-server-errors";
import { FormSubmit } from "@/components/form-common/form-submit";
import { RegionSelect } from "@/components/form-fields/region-select";
import { NextLink } from "@/components/next-link";
import {
  fieldItemProps,
  fieldLabelProps,
  fieldMessageProps,
  formInputProps,
  formSelectProps,
} from "@/components/tanstack-form-utils";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useLocaleFunction } from "@/hooks/use-localed";
import { client } from "@/lib/api-client";
import {
  industries,
  unknownIndustry,
  updateUserSettings,
  type Industry,
  type User,
} from "@/lib/api/labs";
import { handleFormElementSubmitEvent, handleSubmitErrors } from "@/lib/form";
import { useForm } from "@tanstack/react-form";
import { useRouter } from "next/navigation";
import * as React from "react";
import { useId, useTransition } from "react";
import { z } from "zod";

export default function CompleteProfileForm({
  completed,
  completeRedirectTo,
  user,
}: {
  user: User;
  completed: boolean;
  completeRedirectTo: string | undefined;
}) {
  const router = useRouter();
  const [transitioning, startTransition] = useTransition();
  const t = useLocaleFunction();

  const id = useId();
  const disabled = transitioning;
  const schema = React.useMemo(
    () =>
      z.object({
        name: z.string(),
        organization: z.string(),
        job_role: z.string(),
        country: z.string(),
        industry: z
          .string()
          .refine((value) => isIndustry(value), {
            message: t("profile.form.industry.invalid"),
          }),
      }),
    [t]
  );

  const form = useForm({
    validators: {
      onChange: schema,
      onSubmit: schema,
      onBlur: schema,
    },
    defaultValues: {
      name: user.name ?? "",
      organization: user.organization ?? "",
      job_role: user.job_role ?? "",
      country: user.country ?? "",
      industry:
        user.industry && user.industry !== unknownIndustry ? user.industry : "",
    },
    async onSubmit({ value, formApi }) {
      await handleSubmitErrors(formApi, async () => {
        const { industry, ...rest } = value;
        if (!isIndustry(industry)) {
          throw new Error("Invalid industry");
        }
        await updateUserSettings({
          language_code: user.language_code,
          ...rest,
          industry,
        }).finally(() => {
          client.refetchQueries({
            queryKey: ["user.me"],
          });
        });
      });
      startTransition(() => {
        if (
          completeRedirectTo &&
          isSafeCompleteRedirectTo(completeRedirectTo)
        ) {
          router.push(completeRedirectTo);
        }
        router.refresh();
      });
    },
  });

  return (
    <form
      className="space-y-6 p-4 rounded-lg md:border md:bg-card md:shadow-lg"
      onSubmit={handleFormElementSubmitEvent(form)}
    >
      <h2 className="text-2xl font-semibold">{t("profile.form-title")}</h2>
      <form.Field name="name">
        {(field) => (
          <div className="space-y-2">
            <Label {...fieldLabelProps(field, id)}>
              {t("profile.form.name")}
            </Label>
            <Input
              {...fieldItemProps(field, id)}
              {...formInputProps(field, disabled)}
            />
            <p {...fieldMessageProps(field, id)} />
          </div>
        )}
      </form.Field>
      <form.Field name="country">
        {(field) => (
          <div className="space-y-2">
            <Label {...fieldLabelProps(field, id)}>
              {t("profile.form.region")}
            </Label>
            <RegionSelect
              {...fieldItemProps(field, id)}
              {...formSelectProps(field, disabled)}
            />
            <p {...fieldMessageProps(field, id)} />
          </div>
        )}
      </form.Field>
      <form.Field name="organization">
        {(field) => (
          <div className="space-y-2">
            <Label {...fieldLabelProps(field, id)}>
              {t("profile.form.organization")}
            </Label>
            <Input
              {...fieldItemProps(field, id)}
              {...formInputProps(field, disabled)}
            />
            <p {...fieldMessageProps(field, id)} />
          </div>
        )}
      </form.Field>
      <form.Field name="job_role">
        {(field) => (
          <div className="space-y-2">
            <Label {...fieldLabelProps(field, id)}>
              {t("profile.form.job-role")}
            </Label>
            <Select {...formSelectProps(field, disabled)}>
              <SelectTrigger {...fieldItemProps(field, id)}>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {jobRoleValues.map((role) => (
                  <SelectItem key={role} value={role}>
                    {t(`profile.form.job-role-option:${role}`)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <p {...fieldMessageProps(field, id)} />
          </div>
        )}
      </form.Field>
      <form.Field name="industry">
        {(field) => (
          <div className="space-y-2">
            <Label {...fieldLabelProps(field, id)}>
              {t("profile.form.industry")}
            </Label>
            <Select {...formSelectProps(field, disabled)}>
              <SelectTrigger {...fieldItemProps(field, id)}>
                <SelectValue placeholder={t("profile.form.industry-placeholder")} />
              </SelectTrigger>
              <SelectContent>
                {industries.map((industry) => (
                  <SelectItem key={industry} value={industry}>
                    {t(`profile.form.industry-option:${industry}`)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <p {...fieldMessageProps(field, id)} />
          </div>
        )}
      </form.Field>
      <FormServerErrors formApi={form} title={t("profile.failed.title")} />
      <div className="flex items-center gap-4">
        <FormSubmit formApi={form} disabled={disabled}>
          {t("profile.form-submit")}
        </FormSubmit>
        {completed && (
          <NextLink variant="ghost" href="/">
            {t("not-found.back-to-home")}
          </NextLink>
        )}
      </div>
    </form>
  );
}

const jobRoleValues = [
  "Application Developer",
  "Architect",
  "Database Administrator",
  "CTO/CIO",
  "College Student",
  "Others",
] as const;

function isSafeCompleteRedirectTo(url: string) {
  return url.startsWith("/") && !url.startsWith("//");
}

function isIndustry(value: string): value is Industry {
  return industries.some((industry) => industry === value);
}
