import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { MessageSquare, Sparkles, Phone, ShieldCheck, Mail, Lock, User } from "lucide-react";
import { useAuth } from "@/contexts/AuthContext";
import { useNavigate } from "react-router-dom";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/integrations/supabase/client";
import { isAdminUser } from "@/utils/adminCheck";
import { z } from "zod";

/** Block admin accounts from signing into the C-side. Returns true if blocked. */
async function rejectIfAdmin(
  userId: string | undefined,
  setError: (s: string) => void,
): Promise<boolean> {
  if (!userId) return false;
  if (await isAdminUser(userId)) {
    await supabase.auth.signOut();
    setError("该账号为管理员账号，请前往管理后台登录（/admin/login）");
    return true;
  }
  return false;
}

const emailSchema = z.string().trim().email({ message: "请输入有效的邮箱地址" }).max(255);
const phoneSchema = z.string().trim().regex(/^1\d{10}$/, { message: "请输入有效的11位手机号" });
const passwordSchema = z
  .string()
  .min(6, { message: "密码至少需要 6 位" })
  .max(72, { message: "密码不能超过 72 位" });
const displayNameSchema = z
  .string()
  .trim()
  .min(1, { message: "请填写昵称" })
  .max(50, { message: "昵称不能超过 50 个字符" });

/** Resolve user input (phone or email) to the internal Supabase email. */
function resolveAccountEmail(account: string): { email: string; isPhone: boolean } | { error: string } {
  const trimmed = account.trim();
  // Phone (11-digit Chinese mobile) -> internal sms.local mapping (matches verify-sms-code)
  if (/^\d+$/.test(trimmed)) {
    const phoneParsed = phoneSchema.safeParse(trimmed);
    if (!phoneParsed.success) return { error: phoneParsed.error.issues[0].message };
    return { email: `${phoneParsed.data}@sms.local`, isPhone: true };
  }
  const emailParsed = emailSchema.safeParse(trimmed);
  if (!emailParsed.success) return { error: "请输入有效的手机号或邮箱" };
  return { email: emailParsed.data, isPhone: false };
}

export default function AuthPage() {
  // Shared
  const { user, loading, signIn, signUp } = useAuth();
  const navigate = useNavigate();
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // SMS state
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [step, setStep] = useState<"phone" | "code">("phone");
  const [countdown, setCountdown] = useState(0);

  // Password state — `account` accepts phone or email
  const [pwMode, setPwMode] = useState<"signin" | "signup">("signin");
  const [account, setAccount] = useState("");
  const [password, setPassword] = useState("");
  const [displayName, setDisplayName] = useState("");

  useEffect(() => {
    if (!loading && user) {
      navigate("/shop", { replace: true });
    }
  }, [user, loading, navigate]);

  useEffect(() => {
    if (countdown <= 0) return;
    const timer = setTimeout(() => setCountdown((c) => c - 1), 1000);
    return () => clearTimeout(timer);
  }, [countdown]);

  // ============ SMS handlers ============
  const handleSendCode = useCallback(async () => {
    if (!phone || !/^1\d{10}$/.test(phone)) {
      setError("请输入有效的11位手机号");
      return;
    }
    setIsLoading(true);
    setError(null);
    try {
      const { data, error: fnError } = await supabase.functions.invoke("send-sms-code", {
        body: { phone },
      });
      if (fnError) setError("发送失败，请稍后重试");
      else if (data?.error) setError(data.error);
      else {
        setStep("code");
        setCountdown(60);
        toast({ title: "验证码已发送", description: "请查看手机短信" });
      }
    } catch {
      setError("网络错误，请稍后重试");
    }
    setIsLoading(false);
  }, [phone, toast]);

  const handleVerifyCode = useCallback(async () => {
    if (!code || code.length < 4) {
      setError("请输入完整的验证码");
      return;
    }
    setIsLoading(true);
    setError(null);
    try {
      const { data, error: fnError } = await supabase.functions.invoke("verify-sms-code", {
        body: { phone, code },
      });
      if (fnError) setError("验证失败，请稍后重试");
      else if (data?.error) setError(data.error);
      else if (data?.session) {
        await supabase.auth.setSession({
          access_token: data.session.access_token,
          refresh_token: data.session.refresh_token,
        });
        const blocked = await rejectIfAdmin(data.session.user?.id, setError);
        if (!blocked) {
          toast({
            title: data.isNewUser ? "注册成功" : "登录成功",
            description: data.isNewUser ? "欢迎加入！" : "欢迎回来！",
          });
          navigate("/shop");
        }
      }
    } catch {
      setError("网络错误，请稍后重试");
    }
    setIsLoading(false);
  }, [phone, code, navigate, toast]);

  // ============ Password handlers ============
  const handlePasswordSubmit = useCallback(async () => {
    setError(null);

    const resolved = resolveAccountEmail(account);
    if ("error" in resolved) {
      setError(resolved.error);
      return;
    }
    const passwordParsed = passwordSchema.safeParse(password);
    if (!passwordParsed.success) {
      setError(passwordParsed.error.issues[0].message);
      return;
    }
    if (pwMode === "signup") {
      const nameParsed = displayNameSchema.safeParse(displayName);
      if (!nameParsed.success) {
        setError(nameParsed.error.issues[0].message);
        return;
      }
    }

    const { email: loginEmail, isPhone } = resolved;
    setIsLoading(true);
    try {
      if (pwMode === "signin") {
        const { error: e } = await signIn(loginEmail, passwordParsed.data);
        if (e) {
          setError(
            e.message?.includes("Invalid login credentials")
              ? (isPhone ? "手机号或密码错误" : "邮箱或密码错误")
              : e.message || "登录失败"
          );
        } else {
          const { data: sess } = await supabase.auth.getUser();
          const blocked = await rejectIfAdmin(sess.user?.id, setError);
          if (!blocked) {
            toast({ title: "登录成功", description: "欢迎回来！" });
            navigate("/shop");
          }
        }
      } else {
        const { error: e } = await signUp(loginEmail, passwordParsed.data, displayName.trim());
        if (e) {
          setError(
            e.message?.includes("already registered") || e.message?.includes("User already")
              ? (isPhone ? "该手机号已注册，请直接登录" : "该邮箱已注册，请直接登录")
              : e.message || "注册失败"
          );
        } else {
          toast({
            title: "注册成功",
            description: isPhone
              ? "账号已创建，正在登录..."
              : "如已开启邮箱验证，请前往邮箱确认后登录",
          });
          // Try auto sign-in (works when email confirmation is disabled, always true for phone)
          const { error: signInErr } = await signIn(loginEmail, passwordParsed.data);
          if (!signInErr) {
            const { data: sess } = await supabase.auth.getUser();
            const blocked = await rejectIfAdmin(sess.user?.id, setError);
            if (!blocked) navigate("/shop");
          } else {
            setPwMode("signin");
          }
        }
      }
    } catch {
      setError("网络错误，请稍后重试");
    }
    setIsLoading(false);
  }, [account, password, displayName, pwMode, signIn, signUp, navigate, toast]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-background via-background to-muted flex items-center justify-center p-4">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-background via-background to-muted flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Header */}
        <div className="text-center mb-8">
          <div className="flex items-center justify-center space-x-3 mb-4">
            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-gradient-primary">
              <Sparkles className="h-6 w-6 text-white" />
            </div>
            <div className="flex items-center space-x-1">
              <MessageSquare className="h-6 w-6 text-primary" />
              <h1 className="text-2xl font-bold text-foreground">AI购物助手</h1>
            </div>
          </div>
          <p className="text-muted-foreground">智能商品咨询与订单管理平台</p>
        </div>

        <Card className="shadow-lg border-border">
          <CardHeader className="space-y-1 pb-4">
            <CardTitle className="text-2xl text-center text-foreground">欢迎登录</CardTitle>
            <CardDescription className="text-center">
              选择您喜欢的登录方式
            </CardDescription>
          </CardHeader>
          <CardContent>
            {error && (
              <Alert variant="destructive" className="mb-4">
                <AlertDescription>{error}</AlertDescription>
              </Alert>
            )}

            <Tabs
              defaultValue="sms"
              onValueChange={() => setError(null)}
              className="w-full"
            >
              <TabsList className="grid w-full grid-cols-2 mb-4">
                <TabsTrigger value="sms">短信登录</TabsTrigger>
                <TabsTrigger value="password">账号密码</TabsTrigger>
              </TabsList>

              {/* ============ SMS TAB ============ */}
              <TabsContent value="sms" className="space-y-4 mt-0">
                {step === "phone" ? (
                  <>
                    <div className="space-y-2">
                      <Label htmlFor="phone">手机号</Label>
                      <div className="relative">
                        <Phone className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                        <Input
                          id="phone"
                          type="tel"
                          placeholder="请输入11位手机号"
                          value={phone}
                          onChange={(e) =>
                            setPhone(e.target.value.replace(/\D/g, "").slice(0, 11))
                          }
                          className="pl-10"
                          maxLength={11}
                        />
                      </div>
                    </div>
                    <Button
                      className="w-full"
                      onClick={handleSendCode}
                      disabled={isLoading || phone.length !== 11}
                    >
                      {isLoading ? "发送中..." : "获取验证码"}
                    </Button>
                  </>
                ) : (
                  <>
                    <div className="text-sm text-muted-foreground text-center">
                      验证码已发送至 {phone}
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="code">验证码</Label>
                      <div className="relative">
                        <ShieldCheck className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                        <Input
                          id="code"
                          type="text"
                          inputMode="numeric"
                          placeholder="请输入4位验证码"
                          value={code}
                          onChange={(e) =>
                            setCode(e.target.value.replace(/\D/g, "").slice(0, 6))
                          }
                          className="pl-10 text-center text-lg tracking-widest"
                          maxLength={6}
                          autoFocus
                        />
                      </div>
                    </div>
                    <Button
                      className="w-full"
                      onClick={handleVerifyCode}
                      disabled={isLoading || code.length < 4}
                    >
                      {isLoading ? "验证中..." : "登录"}
                    </Button>
                    <div className="flex items-center justify-between text-sm">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          setStep("phone");
                          setCode("");
                          setError(null);
                        }}
                      >
                        更换手机号
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={handleSendCode}
                        disabled={countdown > 0 || isLoading}
                      >
                        {countdown > 0 ? `${countdown}s 后重新发送` : "重新发送"}
                      </Button>
                    </div>
                  </>
                )}
              </TabsContent>

              {/* ============ PASSWORD TAB ============ */}
              <TabsContent value="password" className="space-y-4 mt-0">
                {pwMode === "signup" && (
                  <div className="space-y-2">
                    <Label htmlFor="displayName">昵称</Label>
                    <div className="relative">
                      <User className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                      <Input
                        id="displayName"
                        type="text"
                        placeholder="请输入昵称"
                        value={displayName}
                        onChange={(e) => setDisplayName(e.target.value)}
                        className="pl-10"
                        maxLength={50}
                      />
                    </div>
                  </div>
                )}
                <div className="space-y-2">
                  <Label htmlFor="account">手机号 / 邮箱</Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="account"
                      type="text"
                      autoComplete="username"
                      placeholder="11位手机号 或 邮箱"
                      value={account}
                      onChange={(e) => setAccount(e.target.value)}
                      className="pl-10"
                      maxLength={255}
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="password">密码</Label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="password"
                      type="password"
                      autoComplete={pwMode === "signin" ? "current-password" : "new-password"}
                      placeholder="至少 6 位"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="pl-10"
                      maxLength={72}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") handlePasswordSubmit();
                      }}
                    />
                  </div>
                </div>

                <Button
                  className="w-full"
                  onClick={handlePasswordSubmit}
                  disabled={isLoading}
                >
                  {isLoading
                    ? pwMode === "signin"
                      ? "登录中..."
                      : "注册中..."
                    : pwMode === "signin"
                      ? "登录"
                      : "注册"}
                </Button>

                <div className="text-center text-sm">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      setPwMode(pwMode === "signin" ? "signup" : "signin");
                      setError(null);
                    }}
                  >
                    {pwMode === "signin" ? "还没有账号？立即注册" : "已有账号？前往登录"}
                  </Button>
                </div>
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>

        <div className="text-center mt-6 text-sm text-muted-foreground">
          <p>登录即表示同意我们的服务条款和隐私政策</p>
        </div>
      </div>
    </div>
  );
}
