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

const phoneToEmail = (phone: string) => `${phone}@sms.local`;
const isPhone = (v: string) => /^1\d{10}$/.test(v);
const isEmail = (v: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);

export default function AdminAuthPage() {
  const { user, loading } = useAuth();
  const { toast } = useToast();

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

  // Password state
  const [account, setAccount] = useState("");
  const [password, setPassword] = useState("");

  const [error, setError] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  // Admin role check via user_roles SSOT (not profile.role)
  const [adminState, setAdminState] = useState<"checking" | "admin" | "denied" | "anon">("anon");

  useEffect(() => {
    if (!user) { setAdminState("anon"); return; }
    setAdminState("checking");
    let cancelled = false;
    isAdminUser(user.id).then((ok) => {
      if (cancelled) return;
      setAdminState(ok ? "admin" : "denied");
    });
    return () => { cancelled = true; };
  }, [user]);

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

  if (loading || (user && adminState === "checking")) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (user && adminState === "admin") {
    return <Navigate to="/admin" replace />;
  }

  if (user && adminState === "denied") {
    return (
      <div className="min-h-screen flex items-center justify-center bg-muted/30 p-4">
        <Card className="w-full max-w-md">
          <CardHeader className="text-center">
            <Shield className="h-12 w-12 text-destructive mx-auto mb-2" />
            <CardTitle className="text-xl">权限不足</CardTitle>
            <CardDescription>当前账号没有管理后台访问权限</CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col gap-3">
            <Button variant="outline" onClick={() => window.location.href = "/"}>
              返回前台
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  const handleSendCode = async () => {
    if (!isPhone(phone)) {
      setError("请输入有效的11位手机号");
      return;
    }
    setIsLoading(true);
    setError("");
    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);
  };

  const handleVerifyCode = async () => {
    if (!code || code.length < 4) {
      setError("请输入完整的验证码");
      return;
    }
    setIsLoading(true);
    setError("");
    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,
        });
        toast({ title: "登录成功", description: "欢迎回来！" });
      }
    } catch {
      setError("网络错误，请稍后重试");
    }
    setIsLoading(false);
  };

  const handlePasswordLogin = async () => {
    const acc = account.trim();
    if (!acc || !password) {
      setError("请输入账号和密码");
      return;
    }
    let email = "";
    if (isPhone(acc)) email = phoneToEmail(acc);
    else if (isEmail(acc)) email = acc;
    else {
      setError("请输入有效的手机号或邮箱");
      return;
    }
    setIsLoading(true);
    setError("");
    try {
      const { error: signInError } = await supabase.auth.signInWithPassword({ email, password });
      if (signInError) {
        setError("账号或密码错误");
      } else {
        toast({ title: "登录成功", description: "欢迎回来！" });
      }
    } catch {
      setError("网络错误，请稍后重试");
    }
    setIsLoading(false);
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-muted/30 p-4">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center space-y-2">
          <div className="mx-auto w-14 h-14 rounded-2xl bg-primary/10 flex items-center justify-center">
            <Shield className="h-7 w-7 text-primary" />
          </div>
          <CardTitle className="text-2xl font-bold">管理后台</CardTitle>
          <CardDescription>请使用管理员账号登录</CardDescription>
        </CardHeader>
        <CardContent>
          {error && (
            <Alert variant="destructive" className="mb-4">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

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

            <TabsContent value="sms">
              {step === "phone" ? (
                <div className="space-y-4">
                  <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>
              ) : (
                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="code">验证码已发送至 {phone}</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="请输入验证码"
                        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(""); }}
                    >
                      更换手机号
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={handleSendCode}
                      disabled={countdown > 0 || isLoading}
                    >
                      {countdown > 0 ? `${countdown}s 后重新发送` : "重新发送"}
                    </Button>
                  </div>
                </div>
              )}
            </TabsContent>

            <TabsContent value="password">
              <div className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="account">账号（手机号或邮箱）</Label>
                  <div className="relative">
                    <User className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="account"
                      type="text"
                      placeholder="手机号或邮箱"
                      value={account}
                      onChange={(e) => setAccount(e.target.value)}
                      className="pl-10"
                      maxLength={100}
                    />
                  </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"
                      placeholder="请输入密码"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      onKeyDown={(e) => { if (e.key === "Enter") handlePasswordLogin(); }}
                      className="pl-10"
                      maxLength={72}
                    />
                  </div>
                </div>
                <Button
                  className="w-full"
                  onClick={handlePasswordLogin}
                  disabled={isLoading || !account || !password}
                >
                  {isLoading ? "登录中..." : "登录"}
                </Button>
                <p className="text-xs text-muted-foreground text-center">
                  手机号账号需先在 C 端通过"账号密码注册"设置密码
                </p>
              </div>
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    </div>
  );
}
