"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";

type LoginTab = "otp" | "password";

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

  const [tab, setTab] = useState<LoginTab>("otp");

  // OTP state
  const [phone, setPhone] = useState("09121234567");
  const [code, setCode] = useState("");
  const [otpStep, setOtpStep] = useState<"phone" | "otp">("phone");

  // Password state
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  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");
        case "INVALID_TOKEN":
        case "NOT_FOUND":
          return tab === "password" ? t("invalidCredentials") : t("notFound");
        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 });
      setOtpStep("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);
    }
  };

  const loginWithPassword = async () => {
    if (!username.trim() || !password) {
      setError(t("invalidCredentials"));
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const data = await apiPost<AuthTokenResponse>("/api/auth/login", {
        username: username.trim(),
        password,
      });
      setAuth(data);
      router.push("/pos");
    } catch (e) {
      setError(authErrorMessage(e));
    } finally {
      setLoading(false);
    }
  };

  const switchTab = (next: LoginTab) => {
    setTab(next);
    setError(null);
    setOtpStep("phone");
    setCode("");
  };

  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>

        {/* Tab switcher */}
        <div className="flex border-b px-6">
          <button
            type="button"
            className={`flex-1 py-2 text-sm font-medium transition-colors cursor-pointer ${
              tab === "otp"
                ? "border-b-2 border-primary text-primary"
                : "text-muted-foreground hover:text-foreground"
            }`}
            onClick={() => switchTab("otp")}
          >
            {t("tabOtp")}
          </button>
          <button
            type="button"
            className={`flex-1 py-2 text-sm font-medium transition-colors cursor-pointer ${
              tab === "password"
                ? "border-b-2 border-primary text-primary"
                : "text-muted-foreground hover:text-foreground"
            }`}
            onClick={() => switchTab("password")}
          >
            {t("tabPassword")}
          </button>
        </div>

        <CardContent className="space-y-4 pt-4">
          {/* ───── OTP tab ───── */}
          {tab === "otp" && otpStep === "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>
          )}

          {tab === "otp" && otpStep === "otp" && (
            <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={() => {
                  setOtpStep("phone");
                  setCode("");
                  setError(null);
                }}
              >
                {t("resend")}
              </Button>
            </form>
          )}

          {/* ───── Password tab ───── */}
          {tab === "password" && (
            <form
              className="space-y-4"
              onSubmit={(e) => {
                e.preventDefault();
                if (!loading) void loginWithPassword();
              }}
            >
              <LabeledField label={t("username")} htmlFor="login-username">
                <Input
                  id="login-username"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  placeholder={t("usernamePlaceholder")}
                  dir="ltr"
                  className="text-start"
                  autoComplete="username"
                  autoFocus
                />
              </LabeledField>
              <LabeledField label={t("password")} htmlFor="login-password">
                <Input
                  id="login-password"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder={t("passwordPlaceholder")}
                  dir="ltr"
                  className="text-start"
                  autoComplete="current-password"
                />
              </LabeledField>
              <Button
                type="submit"
                className="w-full"
                disabled={loading || !username.trim() || !password}
              >
                {loading ? "..." : t("verify")}
              </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>
  );
}
