"use client";

import { useRouter } from "next/navigation";
import { useId, useMemo, useTransition } from "react";
import { useForm } from "@tanstack/react-form";
import { z } from "zod";
import Link from "next/link";
import {
  UserIcon,
  AlertTriangleIcon,
  ArrowRightIcon,
  ArrowLeftIcon,
} from "lucide-react";

import {
  fieldItemProps,
  fieldLabelProps,
  fieldMessageProps,
  formInputProps,
} from "@/components/tanstack-form-utils";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { FormSubmit } from "@/components/form-common/form-submit";

import { type User } from "@/lib/api/labs";
import { handleFormElementSubmitEvent, handleSubmitErrors } from "@/lib/form";
import { useLocaleFunction } from "@/hooks/use-localed";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { updateUserSettings } from "@/lib/api/labs";
import { renderRemarkInline } from "@/lib/remark-inline";

export default function ExamConfirmInfoForm({
  examId,
  user,
}: {
  examId: number;
  user: User;
}) {
  const router = useRouter();
  const [transitioning, startTransition] = useTransition();
  const t = useLocaleFunction();

  const id = useId();
  const disabled = transitioning;

  const schema = useMemo(
    () =>
      z.object({
        first_name: z.string().refine((s) => s.trim().length > 0, {
          message: t("exam.confirm-info.validation.first_name_required"),
        }),
        last_name: z.string().refine((s) => s.trim().length > 0, {
          message: t("exam.confirm-info.validation.last_name_required"),
        }),
      }),
    [t]
  );

  const form = useForm({
    validators: {
      onChange: schema,
      onSubmit: schema,
      onBlur: schema,
    },
    defaultValues: {
      first_name: user?.first_name ?? "",
      last_name: user?.last_name ?? "",
    },
    async onSubmit({ value, formApi }) {
      await handleSubmitErrors(formApi, async () => {
        await updateUserSettings({
          first_name: value.first_name.trim(),
          last_name: value.last_name.trim(),
        });
      });

      startTransition(() => {
        router.push(`/exam/${examId}/waiting`);
      });
    },
  });

  return (
    <form id="exam-confirm" onSubmit={handleFormElementSubmitEvent(form)}>
      <Card className="py-2">
        <CardHeader>
          <CardTitle className="text-xl">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 rounded-full bg-muted flex items-center justify-center">
                <UserIcon className="w-6 h-6 text-muted-foreground" />
              </div>
              <div>
                <h1 className="text-xl font-semibold text-foreground">
                  {t("exam.confirm-info.title")}
                </h1>
                <p className="text-sm text-muted-foreground">
                  {t("exam.confirm-info.description")}
                </p>
              </div>
            </div>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Alert
            variant="warn"
            className="bg-amber-600/10 border border-amber-600/20"
          >
            <AlertTriangleIcon size={20} className="-mt-1" />
            <AlertTitle className="text-foreground">
              {t("exam.confirm-info.alert.title")}
            </AlertTitle>
            <AlertDescription className="text-muted-foreground">
              {renderRemarkInline(t("exam.confirm-info.alert.description"), true)}
            </AlertDescription>
          </Alert>

          <div className="mt-6 flex flex-col gap-6">
            <form.Field name="first_name">
              {(field) => (
                <div className="flex flex-col gap-2">
                  <Label {...fieldLabelProps(field, id)}>
                    {t("exam.first_name")}
                  </Label>
                  <Input
                    {...fieldItemProps(field, id, "h-10")}
                    {...formInputProps(field, disabled)}
                  />
                  <p {...fieldMessageProps(field, id)} />
                </div>
              )}
            </form.Field>
            <form.Field name="last_name">
              {(field) => (
                <div className="flex flex-col gap-2">
                  <Label {...fieldLabelProps(field, id)}>
                    {t("exam.last_name")}
                  </Label>
                  <Input
                    {...fieldItemProps(field, id, "h-10")}
                    {...formInputProps(field, disabled)}
                  />
                  <p {...fieldMessageProps(field, id)} />
                </div>
              )}
            </form.Field>
          </div>
        </CardContent>
      </Card>

      <div className="flex justify-between gap-4 pt-8">
        <Button variant="outline" size="lg" asChild className="px-4">
          <Link href={`/exam/${examId}`}>
            <ArrowLeftIcon className="w-4 h-4 mr-2" />
            {t("exam.back")}
          </Link>
        </Button>
        <FormSubmit
          formApi={form}
          disabled={disabled}
          className="cursor-pointer"
        >
          {t("exam.next")}
          <ArrowRightIcon className="w-4 h-4 ml-2" />
        </FormSubmit>
      </div>
    </form>
  );
}
