"use client";

import { useCallback, useState } from "react";
import { useRouter } from "next/navigation";
import { supabaseBrowser } from "@/lib/supabase/client";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("test@163.com");
  const [password, setPassword] = useState("123456");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<string>("");
  const [sessionInfo, setSessionInfo] = useState<string>("");

  const handleLogin = useCallback(async () => {
    setLoading(true);
    setMessage("");
    const { data, error } = await supabaseBrowser.auth.signInWithPassword({
      email,
      password,
    });
    setLoading(false);
    if (error) {
      setMessage(`登录失败：${error.message}`);
      return;
    }
    setMessage("登录成功，准备跳转...");
    setSessionInfo(JSON.stringify(data.session, null, 2));
    router.replace("/");
  }, [email, password, router]);

  const handleGetSession = useCallback(async () => {
    setLoading(true);
    const {
      data: { session },
      error,
    } = await supabaseBrowser.auth.getSession();
    setLoading(false);
    if (error) {
      setMessage(`获取会话失败：${error.message}`);
      return;
    }
    if (!session) {
      setMessage("当前未登录");
      setSessionInfo("");
      return;
    }
    setMessage("发现有效 Session");
    setSessionInfo(JSON.stringify(session, null, 2));
  }, []);

  return (
    <div className="flex min-h-screen items-center justify-center bg-zinc-50 p-4">
      <Card className="w-[400px] space-y-4 bg-white/90 shadow-md backdrop-blur">
        <CardHeader>
          <CardTitle className="text-xl">Supabase 登录</CardTitle>
          <p className="text-sm text-zinc-500">测试账号：test@163.com / 123456</p>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="space-y-1">
            <label className="text-sm text-zinc-700">邮箱</label>
            <Input value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>
          <div className="space-y-1">
            <label className="text-sm text-zinc-700">密码</label>
            <Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
          </div>
          <div className="flex gap-2">
            <Button className="flex-1" onClick={handleLogin} disabled={loading}>
              {loading ? "处理中..." : "登录"}
            </Button>
            <Button variant="outline" onClick={handleGetSession} disabled={loading}>
              会话检测
            </Button>
          </div>
          {message && <p className="whitespace-pre-wrap text-sm text-blue-600">{message}</p>}
          <Separator />
          {sessionInfo && (
            <pre className="max-h-64 overflow-auto rounded-md bg-zinc-900 p-3 text-xs text-zinc-100">
              {sessionInfo}
            </pre>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
