"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter, Link } from "@/i18n/routing";
import { useSearchParams } from "next/navigation";
import { Suspense } from "react";
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";

function RegisterForm() {
  const t = useTranslations("auth");
  const router = useRouter();
  const setAuth = useAuthStore((s) => s.setAuth);
  const searchParams = useSearchParams();

  const [phone, setPhone] = useState(searchParams.get("phone") ?? "");
  const [cafeName, setCafeName] = useState("");
  const [code, setCode] = useState("");
  const [step, setStep] = useState<"info" | "otp">("info");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const errorMessage = (err: unknown) => {
    if (err instanceof ApiClientError) {
      switch (err.code) {
        case "RATE_LIMITED":      return t("rateLimited");
        case "ALREADY_REGISTERED": return t("alreadyRegistered");
        case "SMS_FAILED":        return t("smsFailed");
        case "INVALID_OTP":       return t("invalidOtp");
        case "REGISTRATION_EXPIRED": return t("registrationExpired");
        default:                  return err.message;
      }
    }
    return err instanceof Error ? err.message : String(err);
  };

  const sendOtp = async () => {
    setLoading(true);
    setError(null);
    try {
      await apiPost("/api/auth/register", { phone, cafeName });
      setStep("otp");
    } catch (e) {
      setError(errorMessage(e));
    } finally {
      setLoading(false);
    }
  };

  const verifyOtp = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await apiPost<AuthTokenResponse>("/api/auth/verify-register", { phone, code });
      setAuth(data);
      router.push("/");
    } catch (e) {
      setError(errorMessage(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("register")}</CardTitle>
          <p className="text-center text-sm text-muted-foreground">{t("registerSubtitle")}</p>
        </CardHeader>
        <CardContent className="space-y-4">
          {step === "info" ? (
            <form
              className="space-y-4"
              onSubmit={(e) => {
                e.preventDefault();
                if (!loading) void sendOtp();
              }}
            >
              <LabeledField label={t("cafeName")} htmlFor="reg-cafe-name">
                <Input
                  id="reg-cafe-name"
                  value={cafeName}
                  onChange={(e) => setCafeName(e.target.value)}
                  placeholder={t("cafeNamePlaceholder")}
                  autoComplete="organization"
                  required
                />
              </LabeledField>
              <LabeledField label={t("phone")} htmlFor="reg-phone">
                <Input
                  id="reg-phone"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder={t("phonePlaceholder")}
                  dir="ltr"
                  className="text-end"
                  autoComplete="tel"
                  required
                />
              </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="reg-otp">
                <OtpInput
                  value={code}
                  onChange={setCode}
                  autoFocus
                  disabled={loading}
                />
              </LabeledField>
              <Button type="submit" className="w-full" disabled={loading || code.length < 6}>
                {loading ? "..." : t("createAccount")}
              </Button>
              <Button
                type="button"
                variant="ghost"
                className="w-full"
                onClick={() => { setStep("info"); setCode(""); }}
              >
                {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("alreadyHaveAccount")}{" "}
            <Link href="/login" className="font-medium text-primary hover:underline">
              {t("loginLink")}
            </Link>
          </p>
        </CardContent>
      </Card>
    </div>
  );
}

export default function RegisterPage() {
  return (
    <Suspense>
      <RegisterForm />
    </Suspense>
  );
}
