"use client";

import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
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 { login } from "@/services/auth-api";
import { storeAdminSession, clearAdminSession } from "@/services/auth";
import { applyFieldErrors, friendlyErrorMessage } from "@/lib/errors";
import { isApiError } from "@/services/http";

const formSchema = z.object({
  email: z.string().email("errors.email"),
  password: z.string().min(1, "errors.required"),
  device_name: z.string().optional(),
});

type FormValues = z.infer<typeof formSchema>;

export default function LoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginForm />
    </Suspense>
  );
}

function LoginForm() {
  const t = useT();
  const router = useRouter();
  const searchParams = useSearchParams();
  const [serverError, setServerError] = useState<string | null>(null);

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

  useEffect(() => {
    // a token on the login screen usually means a stale tenant; drop it
    clearAdminSession();
  }, []);

  async function onSubmit(values: FormValues) {
    setServerError(null);
    try {
      const response = await login(values);
      if (!response.Model) {
        setServerError(t("errors.generic"));
        return;
      }
      storeAdminSession(response.Model.admin, response.Model.token);
      toast.success(response.Message || t("common.appName"));
      const next = searchParams.get("next");
      // Land on the overview after signing in unless a deep link was supplied.
      // "/" is the login screen itself, so it must never be a sign-in destination.
      router.replace(next && next.startsWith("/") && next !== "/" ? next : "/overview");
    } catch (error) {
      if (isApiError(error) && error.status === 401) {
        setServerError(t("errors.unauthorized"));
        return;
      }
      // 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", "password", "device_name"] },
      );
      if (shown === 0) setServerError(friendlyErrorMessage(error, t));
    }
  }

  return (
    <AuthCard
      title={t("auth.loginTitle")}
      subtitle={t("auth.loginSubtitle")}
      footer={
        <a
          href="/forgot-password"
          className="text-xs font-medium text-primary underline-offset-4 transition-colors hover:underline"
        >
          {t("auth.forgotPassword")}
        </a>
      }
    >
      <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.password")}
          htmlFor="password"
          error={form.formState.errors.password?.message}
        >
          <Input
            id="password"
            type="password"
            autoComplete="current-password"
            {...form.register("password")}
          />
        </FormField>
        <FormField
          label={t("auth.deviceName")}
          htmlFor="device_name"
          hint={t("auth.deviceNamePlaceholder")}
          error={form.formState.errors.device_name?.message}
        >
          <Input
            id="device_name"
            placeholder={t("auth.deviceNamePlaceholder")}
            {...form.register("device_name")}
          />
        </FormField>
        <Button type="submit" className="w-full" size="lg" loading={form.formState.isSubmitting}>
          {t("auth.signIn")}
        </Button>
      </form>
    </AuthCard>
  );
}