"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { zodResolver } from "@hookform/resolvers/zod";
import { CheckCircle2 } from "lucide-react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { FormField } from "@/components/ui/form-field";
import { Input } from "@/components/ui/input";
import { AuthCard } from "@/features/auth/auth-card";
import { useT } from "@/i18n";
import { applyFieldErrors, friendlyErrorMessage } from "@/lib/errors";
import { registerStore } from "@/services/portal";
import { LETTERS_ONLY_RE } from "@/lib/field-rules";

/*
 * Mirrors RegisterStoreRequest. The server is the authority — these only save a round trip for the
 * mistakes a person can see at a glance — so each rule is no stricter than the server's.
 */
const formSchema = z
  .object({
    store_name: z.string().trim().min(1, "errors.required").max(255),
    name: z.string().trim().min(1, "errors.required").regex(LETTERS_ONLY_RE, "errors.lettersOnly").max(255),
    email: z.string().email("errors.email").max(255),
    phone: z
      .string()
      .trim()
      .min(1, "errors.required")
      .max(20)
      .regex(/^\+\d{8,18}$/, "errors.portalPhone"),
    password: z
      .string()
      .min(10, "errors.portalPassword")
      .regex(/[A-Za-z]/, "errors.portalPassword")
      .regex(/\d/, "errors.portalPassword"),
    password_confirmation: z.string().min(1, "errors.required"),
  })
  .refine((values) => values.password === values.password_confirmation, {
    path: ["password_confirmation"],
    message: "errors.passwordMismatch",
  });

type FormValues = z.infer<typeof formSchema>;

const FIELDS: (keyof FormValues)[] = [
  "store_name",
  "name",
  "email",
  "phone",
  "password",
  "password_confirmation",
];

export default function PortalRegisterPage() {
  const t = useT();
  const router = useRouter();
  const [serverError, setServerError] = useState<string | null>(null);
  const [registeredStore, setRegisteredStore] = useState<string | null>(null);

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    // Not `onTouched`: a store applicant moving through the form field by field saw an error
    // under the very first box the moment they left it empty to read the next one. Validating
    // only on submit means nothing is flagged red before anybody has asked the form to check —
    // and once a field has been flagged, the default `reValidateMode` of `onChange` still clears
    // it live as they fix it, rather than waiting for a second submit.
    mode: "onSubmit",
    defaultValues: {
      store_name: "",
      name: "",
      email: "",
      phone: "",
      password: "",
      password_confirmation: "",
    },
  });

  const errors = form.formState.errors;

  async function onSubmit(values: FormValues) {
    setServerError(null);
    try {
      await registerStore(values);
      setRegisteredStore(values.store_name);
    } catch (error) {
      const shown = applyFieldErrors(
        error,
        (field, message) => form.setError(field as keyof FormValues, { message }),
        { only: FIELDS },
      );
      // 422 on a field is shown in place; anything else (throttled, offline) goes in the banner.
      if (shown === 0) setServerError(friendlyErrorMessage(error, t));
    }
  }

  if (registeredStore) {
    return (
      <AuthCard title={t("portal.register.doneTitle")}>
        <div className="space-y-5">
          <div className="flex items-start gap-3">
            <CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0 text-success" aria-hidden />
            <p className="text-sm text-muted-foreground">
              {t("portal.register.doneBody", { store: registeredStore })}
            </p>
          </div>
          <Button className="w-full" size="lg" onClick={() => router.push("/portal/login")}>
            {t("portal.register.goToLogin")}
          </Button>
        </div>
      </AuthCard>
    );
  }

  return (
    <AuthCard
      title={t("portal.register.title")}
      subtitle={t("portal.register.subtitle")}
      footer={
        <p className="text-xs text-muted-foreground">
          {t("portal.register.haveAccount")}{" "}
          <Link href="/portal/login" className="font-medium text-primary underline-offset-4 hover:underline">
            {t("auth.signIn")}
          </Link>
        </p>
      }
    >
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" noValidate>
        {serverError ? <Alert variant="destructive" title={serverError} /> : null}

        <p className="text-xs font-semibold text-muted-foreground">
          {t("portal.register.storeSection")}
        </p>
        <FormField label={t("portal.register.storeName")} htmlFor="store_name" required error={errors.store_name?.message}>
          <Input id="store_name" autoComplete="organization" {...form.register("store_name")} />
        </FormField>

        <p className="pt-2 text-xs font-semibold text-muted-foreground">
          {t("portal.register.ownerSection")}
        </p>
        <FormField label={t("portal.register.ownerName")} htmlFor="name" required error={errors.name?.message}>
          <Input id="name" autoComplete="name" kind="letters" {...form.register("name")} />
        </FormField>
        <FormField label={t("auth.email")} htmlFor="email" required error={errors.email?.message}>
          <Input id="email" type="email" autoComplete="email" dir="ltr" {...form.register("email")} />
        </FormField>
        <FormField
          label={t("portal.register.phone")}
          htmlFor="phone"
          required
          hint={t("portal.register.phoneHint")}
          error={errors.phone?.message}
        >
          <Input id="phone" type="tel" autoComplete="tel" dir="ltr" placeholder="+963" {...form.register("phone")} />
        </FormField>
        <FormField
          label={t("auth.password")}
          htmlFor="password"
          required
          hint={t("portal.register.passwordHint")}
          error={errors.password?.message}
        >
          <Input id="password" type="password" autoComplete="new-password" {...form.register("password")} />
        </FormField>
        <FormField
          label={t("portal.register.confirmPassword")}
          htmlFor="password_confirmation"
          required
          error={errors.password_confirmation?.message}
        >
          <Input
            id="password_confirmation"
            type="password"
            autoComplete="new-password"
            {...form.register("password_confirmation")}
          />
        </FormField>

        <Button type="submit" className="w-full" size="lg" loading={form.formState.isSubmitting}>
          {t("portal.register.submit")}
        </Button>
      </form>
    </AuthCard>
  );
}
