"use client";

import { useState } from "react";
import Link from "next/link";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
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 { forgotPassword } from "@/services/auth-api";
import { applyFieldErrors, friendlyErrorMessage } from "@/lib/errors";

const formSchema = z.object({
  email: z.string().email("errors.email"),
});

export default function ForgotPasswordPage() {
  const t = useT();
  const [serverError, setServerError] = useState<string | null>(null);
  const [sent, setSent] = useState(false);

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

  async function onSubmit(values: z.infer<typeof formSchema>) {
    setServerError(null);
    try {
      const response = await forgotPassword(values);
      const message = response.Message || t("auth.forgotSent");
      setSent(true);
      // keep serverError cleared; the flow moves to the reset page
      setServerError(null);
      return message;
    } catch (error) {
      // 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"] },
      );
      if (shown === 0) setServerError(friendlyErrorMessage(error, t));
    }
  }

  if (sent) {
    return (
      <AuthCard
        title={t("auth.forgotTitle")}
        footer={
          <Link
            href="/forgot-password"
            className="inline-flex items-center gap-1.5 text-xs font-medium text-primary"
            onClick={() => setSent(false)}
          >
            <ArrowLeft className="h-3.5 w-3.5 rtl:rotate-180" aria-hidden />
            {t("auth.sendCode")}
          </Link>
        }
      >
        <Alert variant="success" title={t("auth.forgotSent")} />
        <div className="mt-6">
          <Link href="/reset-password" className="w-full">
            <Button variant="outline" className="w-full">
              {t("auth.resetTitle")}
            </Button>
          </Link>
        </div>
      </AuthCard>
    );
  }

  return (
    <AuthCard
      title={t("auth.forgotTitle")}
      subtitle={t("auth.forgotSubtitle")}
      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>
        <Button type="submit" className="w-full" size="lg" loading={form.formState.isSubmitting}>
          {t("auth.sendCode")}
        </Button>
      </form>
    </AuthCard>
  );
}