"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "@/i18n/routing";
import { AdminApiClientError } from "@/lib/api/admin-client";
import { adminPost } from "@/lib/api/admin-client";
import type { AuthTokenResponse } from "@/lib/api/types";
import { useAdminAuthStore } from "@/lib/stores/admin-auth.store";
import { normalizeOtpInput } from "@/lib/utils/otp";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LabeledField } from "@/components/ui/labeled-field";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

export default function AdminLoginPage() {
  const t = useTranslations("admin.auth");
  const tAuth = useTranslations("auth");
  const router = useRouter();
  const setAuth = useAdminAuthStore((s) => s.setAuth);
  const [phone, setPhone] = useState("09120000001");
  const [code, setCode] = useState("");
  const [step, setStep] = useState<"phone" | "otp">("phone");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const authErrorMessage = (err: unknown) => {
    if (err instanceof AdminApiClientError) {
      switch (err.code) {
        case "RATE_LIMITED":
          return tAuth("rateLimited");
        case "NOT_FOUND":
          return tAuth("notFound");
        case "INVALID_OTP":
        case "VALIDATION_ERROR":
          return tAuth("invalidOtp");
        default:
          return err.message;
      }
    }
    return err instanceof Error ? err.message : t("error");
  };

  const sendOtp = async () => {
    setLoading(true);
    setError(null);
    try {
      await adminPost("/api/admin/auth/send-otp", { phone });
      setStep("otp");
      setCode("");
    } catch (e) {
      setError(authErrorMessage(e));
    } finally {
      setLoading(false);
    }
  };

  const verify = async () => {
    const normalized = normalizeOtpInput(code);
    if (normalized.length !== 6) {
      setError(tAuth("invalidOtp"));
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const data = await adminPost<AuthTokenResponse>("/api/admin/auth/verify-otp", {
        phone,
        code: normalized,
      });
      setAuth(data);
      router.push("/admin");
    } catch (e) {
      setError(authErrorMessage(e));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-muted/30 p-4" dir="rtl">
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle className="text-center text-primary">{t("title")}</CardTitle>
          <p className="text-center text-sm text-muted-foreground">{t("subtitle")}</p>
          {process.env.NODE_ENV === "development" ? (
            <p className="text-center text-xs text-muted-foreground">{t("devHint")}</p>
          ) : null}
        </CardHeader>
        <CardContent className="space-y-4">
          {step === "phone" ? (
            <form
              className="space-y-4"
              onSubmit={(e) => {
                e.preventDefault();
                if (!loading) void sendOtp();
              }}
            >
              <LabeledField label={t("phone")} htmlFor="admin-login-phone">
                <Input
                  id="admin-login-phone"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder={tAuth("phonePlaceholder")}
                  dir="ltr"
                  className="text-end"
                  autoComplete="tel"
                />
              </LabeledField>
              <Button type="submit" className="w-full" disabled={loading}>
                {loading ? "..." : t("sendOtp")}
              </Button>
            </form>
          ) : (
            <form
              className="space-y-4"
              onSubmit={(e) => {
                e.preventDefault();
                if (!loading) void verify();
              }}
            >
              <LabeledField label={t("otp")} htmlFor="admin-login-otp">
                <Input
                  id="admin-login-otp"
                  value={code}
                  onChange={(e) => setCode(normalizeOtpInput(e.target.value))}
                  placeholder={tAuth("otpPlaceholder")}
                  maxLength={6}
                  inputMode="numeric"
                  dir="ltr"
                  className="text-center tracking-widest"
                  autoComplete="one-time-code"
                  autoFocus
                />
              </LabeledField>
              <Button type="submit" className="w-full" disabled={loading || code.length < 6}>
                {loading ? "..." : t("login")}
              </Button>
              <Button
                type="button"
                variant="ghost"
                className="w-full"
                disabled={loading}
                onClick={() => {
                  setStep("phone");
                  setCode("");
                  setError(null);
                }}
              >
                {tAuth("resend")}
              </Button>
            </form>
          )}
          {error ? <p className="text-center text-sm text-destructive">{error}</p> : null}
        </CardContent>
      </Card>
    </div>
  );
}
