"use client";

import { useState, useEffect } 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";

/** Client-side Persian-to-Latin slugifier — mirrors SlugHelper.Slugify on the backend */
const PERSIAN_MAP: Record<string, string> = {
  آ: "a", ا: "a", أ: "a", إ: "a",
  ب: "b", پ: "p", ت: "t", ث: "s",
  ج: "j", چ: "ch", ح: "h", خ: "kh",
  د: "d", ذ: "z", ر: "r", ز: "z", ژ: "zh",
  س: "s", ش: "sh", ص: "s", ض: "z",
  ط: "t", ظ: "z", ع: "a", غ: "gh",
  ف: "f", ق: "gh", ک: "k", ك: "k", گ: "g",
  ل: "l", م: "m", ن: "n", و: "v",
  ه: "h", ی: "i", ي: "i",
  ئ: "y", ء: "", ة: "t", ى: "a", ؤ: "o",
  "۰": "0", "۱": "1", "۲": "2", "۳": "3", "۴": "4",
  "۵": "5", "۶": "6", "۷": "7", "۸": "8", "۹": "9",
};

function slugify(input: string): string {
  let s = "";
  for (const ch of input) {
    if (ch in PERSIAN_MAP) {
      s += PERSIAN_MAP[ch];
    } else if (/[a-zA-Z0-9]/.test(ch)) {
      s += ch.toLowerCase();
    } else if (/[\s\-_]/.test(ch)) {
      s += "-";
    }
  }
  return s.replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "");
}

function isValidSlug(slug: string): boolean {
  if (!slug || slug.length < 2 || slug.length > 80) return false;
  return /^[a-z0-9][a-z0-9\-]*[a-z0-9]$/.test(slug);
}

const KOJA_BASE =
  typeof window !== "undefined" && window.location.hostname.includes("meezi.ir")
    ? "koja.meezi.ir"
    : "koja.meezi.ir";

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

  // Already signed in? Don't show the register form — send them into the app.
  // Gate on _hasHydrated so a not-yet-rehydrated (null) session isn't misread.
  const alreadyAuthed = hasHydrated && !!user?.accessToken;
  useEffect(() => {
    if (alreadyAuthed) router.replace("/");
  }, [alreadyAuthed, router]);

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

  // Auto-derive slug from café name unless the user has manually edited it
  useEffect(() => {
    if (!slugEdited) {
      setSlug(slugify(cafeName));
    }
  }, [cafeName, slugEdited]);

  const slugValid = isValidSlug(slug);

  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,
        slug: slugValid ? slug : undefined,
      });
      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);
    }
  };

  if (alreadyAuthed) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-muted/30 p-4">
        <p className="text-sm text-muted-foreground">{t("redirecting")}</p>
      </div>
    );
  }

  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>

              {/* Koja slug / profile URL */}
              <LabeledField
                label={t("kojaSlug")}
                htmlFor="reg-slug"
                hint={t("kojaSlugHint")}
              >
                <Input
                  id="reg-slug"
                  value={slug}
                  onChange={(e) => {
                    setSlugEdited(true);
                    setSlug(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""));
                  }}
                  placeholder={t("kojaSlugPlaceholder")}
                  dir="ltr"
                  className="text-start font-mono text-sm"
                />
                {slug && (
                  <p className={`mt-1 text-xs font-mono ${slugValid ? "text-muted-foreground" : "text-destructive"}`}>
                    {KOJA_BASE}/{slug}
                  </p>
                )}
              </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>
  );
}
