"use client";

import { useState } from "react";
import Link from "next/link";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { ArrowLeft } from "lucide-react";
import { AuthCard } from "@/features/auth/auth-card";
import { Button } from "@/components/ui/button";
import { FormField } from "@/components/ui/form-field";
import { Input } from "@/components/ui/input";
import { Alert } from "@/components/ui/alert";
import { useT } from "@/i18n";
import { resetPassword, resendCode } from "@/services/auth-api";
import { OTP_LENGTH } from "@/config/site";
import { applyFieldErrors, friendlyErrorMessage } from "@/lib/errors";

const formSchema = z
  .object({
    email: z.string().email("errors.email"),
    code: z.string().regex(new RegExp(`^\\d{${OTP_LENGTH}}$`), "errors.code"),
    password: z.string().min(8, "errors.generic"),
    password_confirmation: z.string(),
  })
  .refine((values) => values.password === values.password_confirmation, {
    path: ["password_confirmation"],
    message: "errors.passwordMismatch",
  });

export default function ResetPasswordPage() {
  const t = useT();
  const [serverError, setServerError] = useState<string | null>(null);
  const [done, setDone] = useState(false);

  const form = useForm({
    resolver: zodResolver(formSchema),
    mode: "onTouched",
    defaultValues: { email: "", code: "", password: "", password_confirmation: "" },
  });

  async function onSubmit(values: z.infer<typeof formSchema>) {
    setServerError(null);
    try {
      await resetPassword(values);
      toast.success(t("auth.resetTitle"));
      setDone(true);
    } catch (error) {
      // The wrong-code refusal names `code`, so it lands under the code box rather than in a
      // banner that leaves the operator guessing which of the four fields was wrong.
      // Whatever the server refused per field goes under that field; the banner is for the rest.
      const shown = applyFieldErrors(
        error,
        (field, message) => form.setError(field as never, { message }),
        { only: ["email", "code", "password", "password_confirmation"] },
      );
      if (shown === 0) setServerError(friendlyErrorMessage(error, t));
    }
  }

  async function handleResend() {
    const email = form.getValues("email");
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      form.setError("email", { type: "manual", message: "errors.email" });
      return;
    }
    try {
      const response = await resendCode({ email });
      toast.success(response.Message || t("auth.forgotSent"));
    } catch (error) {
      toast.error(friendlyErrorMessage(error, t));
    }
  }

  if (done) {
    return (
      <AuthCard
        title={t("auth.resetTitle")}
        footer={
          <Link
            href="/"
            className="inline-flex items-center gap-1.5 text-xs font-medium text-primary"
          >
            <ArrowLeft className="h-3.5 w-3.5 rtl:rotate-180" aria-hidden />
            {t("auth.backToLogin")}
          </Link>
        }
      >
        <Alert variant="success" title={t("auth.resetSubtitle")} />
      </AuthCard>
    );
  }

  return (
    <AuthCard
      title={t("auth.resetTitle")}
      subtitle={t("auth.resetSubtitle")}
      footer={
        <Link
          href="/"
          className="inline-flex items-center gap-1.5 text-xs font-medium text-primary"
        >
          <ArrowLeft className="h-3.5 w-3.5 rtl:rotate-180" aria-hidden />
          {t("auth.backToLogin")}
        </Link>
      }
    >
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" noValidate>
        {serverError ? <Alert variant="destructive" title={serverError} /> : null}
        <FormField
          label={t("auth.email")}
          htmlFor="email"
          error={form.formState.errors.email?.message}
        >
          <Input
            id="email"
            type="email"
            autoComplete="email"
            placeholder="admin@kapitano.app"
            {...form.register("email")}
          />
        </FormField>
        <FormField
          label={t("auth.code")}
          htmlFor="code"
          required
          error={form.formState.errors.code?.message}
        >
          <Input
            id="code"
            inputMode="numeric"
            autoComplete="one-time-code"
            maxLength={OTP_LENGTH}
            placeholder="••••••"
            className="numeric tracking-[0.4em]"
            {...form.register("code")}
          />
        </FormField>
        <FormField
          label={t("auth.newPassword")}
          htmlFor="password"
          required
          error={form.formState.errors.password?.message}
        >
          <Input
            id="password"
            type="password"
            autoComplete="new-password"
            {...form.register("password")}
          />
        </FormField>
        <FormField
          label={t("auth.confirmPassword")}
          htmlFor="password_confirmation"
          required
          error={form.formState.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("auth.resetPassword")}
        </Button>
        <p className="text-center">
          <button
            type="button"
            onClick={handleResend}
            className="text-xs font-medium text-primary underline-offset-4 hover:underline"
          >
            {t("auth.resendCode")}
          </button>
        </p>
      </form>
    </AuthCard>
  );
}