"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter, Link } from "@/i18n/routing";
import { apiPost, ApiClientError } from "@/lib/api/client";
import type { AuthTokenResponse } from "@/lib/api/types";
import { useAuthStore } from "@/lib/stores/auth.store";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LabeledField } from "@/components/ui/labeled-field";
import { OtpInput } from "@/components/ui/otp-input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

export default function LoginPage() {
  const t = useTranslations("auth");
  const router = useRouter();
  const setAuth = useAuthStore((s) => s.setAuth);

  const [phone, setPhone] = useState("09121234567");
  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 ApiClientError) {
      switch (err.code) {
        case "RATE_LIMITED":
          return t("rateLimited");
        case "SMS_FAILED":
          return t("smsFailed");
        case "INVALID_OTP":
          return t("invalidOtp");
        default:
          return err.message;
      }
    }
    return err instanceof Error ? err.message : t("title");
  };

  const sendOtp = async () => {
    setLoading(true);
    setError(null);
    try {
      await apiPost("/api/auth/send-otp", { phone });
      setStep("otp");
    } catch (e) {
      if (e instanceof ApiClientError && e.code === "NOT_FOUND") {
        // No account → take them to register with phone pre-filled
        router.push(`/register?phone=${encodeURIComponent(phone)}`);
        return;
      }
      setError(authErrorMessage(e));
    } finally {
      setLoading(false);
    }
  };

  const verifyOtp = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await apiPost<AuthTokenResponse>("/api/auth/verify-otp", {
        phone,
        code,
      });
      setAuth(data);
      router.push("/pos");
    } catch (e) {
      setError(authErrorMessage(e));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-muted/30 p-4">
      <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>
        </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="login-phone">
                <Input
                  id="login-phone"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder={t("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 verifyOtp();
              }}
            >
              <LabeledField label={t("otp")} htmlFor="login-otp">
                <OtpInput
                  value={code}
                  onChange={setCode}
                  autoFocus
                  disabled={loading}
                />
              </LabeledField>
              <Button type="submit" className="w-full" disabled={loading || code.length < 6}>
                {loading ? "..." : t("verify")}
              </Button>
              <Button
                type="button"
                variant="ghost"
                className="w-full"
                onClick={() => setStep("phone")}
              >
                {t("resend")}
              </Button>
            </form>
          )}
          {error && (
            <p className="text-center text-sm text-destructive">{error}</p>
          )}

          <p className="text-center text-sm text-muted-foreground">
            {t("noAccount")}{" "}
            <Link href="/register" className="font-medium text-primary hover:underline">
              {t("registerLink")}
            </Link>
          </p>
        </CardContent>
      </Card>
    </div>
  );
}
