import { useState, type FormEvent } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { motion } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { toast } from "@/hooks/use-toast";
import { apiRequest, getQueryFn } from "@/lib/queryClient";
import type { User } from "@shared/schema";

type SessionUser = Pick<User, "id" | "username">;

type AuthPayload = {
  email: string;
  password: string;
};

export default function AuthSection() {
  const queryClient = useQueryClient();
  const [activeTab, setActiveTab] = useState<"login" | "signup">("signup");
  const [signupForm, setSignupForm] = useState<AuthPayload>({
    email: "",
    password: "",
  });
  const [loginForm, setLoginForm] = useState<AuthPayload>({
    email: "",
    password: "",
  });

  const meQuery = useQuery<SessionUser | null>({
    queryKey: ["/me"],
    queryFn: getQueryFn<SessionUser | null>({ on401: "returnNull" }),
  });

  const handleAuthSuccess = (user: SessionUser, action: "signup" | "login") => {
    queryClient.setQueryData(["/me"], user);
    queryClient.invalidateQueries({ queryKey: ["/broker/status"] });
    toast({
      title: action === "signup" ? "Account created" : "Signed in",
      description: `Welcome ${user.username}`,
    });
  };

  const signupMutation = useMutation<SessionUser, Error, AuthPayload>({
    mutationFn: async (payload) => {
      const res = await apiRequest("POST", "/signup", {
        username: payload.email,
        password: payload.password,
      });
      return res.json();
    },
    onSuccess: (user) => handleAuthSuccess(user, "signup"),
    onError: (err) => {
      toast({
        title: "Signup failed",
        description: err.message,
      });
    },
  });

  const loginMutation = useMutation<SessionUser, Error, AuthPayload>({
    mutationFn: async (payload) => {
      const res = await apiRequest("POST", "/login", payload);
      return res.json();
    },
    onSuccess: (user) => handleAuthSuccess(user, "login"),
    onError: (err) => {
      toast({
        title: "Login failed",
        description: err.message,
      });
    },
  });

  const logoutMutation = useMutation({
    mutationFn: async () => {
      await apiRequest("POST", "/logout");
    },
    onSuccess: () => {
      queryClient.setQueryData(["/me"], null);
      queryClient.removeQueries({ queryKey: ["/broker/status"] });
      toast({ title: "Signed out" });
      window.location.assign("/");
    },
  });

  const handleSignup = (event: FormEvent) => {
    event.preventDefault();
    signupMutation.mutate(signupForm);
  };

  const handleLogin = (event: FormEvent) => {
    event.preventDefault();
    loginMutation.mutate(loginForm);
  };

  const sessionUser = meQuery.data;

  return (
    <section id="account" className="py-24 px-6 bg-gradient-to-b from-background to-background/70">
      <div className="max-w-5xl mx-auto">
        <div className="text-center mb-12 space-y-3">
          <p className="text-sm uppercase tracking-[0.2em] text-muted-foreground">Account</p>
          <h3 className="text-3xl md:text-4xl font-bold">Get started in minutes</h3>
          <p className="text-muted-foreground max-w-2xl mx-auto">
            Create an account with your email, sign in securely, and see your profile instantly.
          </p>
        </div>

        <Card className="bg-card/70 border-border/60 shadow-2xl">
          {sessionUser ? (
            <CardHeader className="space-y-4">
              <div className="flex items-center gap-3">
                <Badge variant="secondary">Signed In</Badge>
                <p className="text-sm text-muted-foreground">
                  You are authenticated. Below is the data we have on file for you.
                </p>
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <div>
                  <p className="text-xs uppercase text-muted-foreground mb-1">Email</p>
                  <p className="font-medium break-all">{sessionUser.username}</p>
                </div>
                <div>
                  <p className="text-xs uppercase text-muted-foreground mb-1">User ID</p>
                  <p className="font-mono text-sm break-all">{sessionUser.id}</p>
                </div>
              </div>
              <div>
                <Button
                  variant="outline"
                  onClick={() => logoutMutation.mutate()}
                  disabled={logoutMutation.isPending}
                >
                  Log out
                </Button>
              </div>
            </CardHeader>
          ) : (
            <CardContent className="pt-6">
              <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as "login" | "signup")}>
                <TabsList className="grid w-full grid-cols-2">
                  <TabsTrigger value="signup">Sign up</TabsTrigger>
                  <TabsTrigger value="login">Log in</TabsTrigger>
                </TabsList>
                <TabsContent value="signup" className="mt-6">
                  <motion.div
                    layout
                    transition={{ type: "spring", stiffness: 400, damping: 30 }}
                  >
                    <form className="space-y-4" onSubmit={handleSignup}>
                      <div className="space-y-2">
                        <Label htmlFor="signup-email">Email</Label>
                        <Input
                          id="signup-email"
                          type="email"
                          required
                          placeholder="you@example.com"
                          value={signupForm.email}
                          onChange={(e) =>
                            setSignupForm((prev) => ({ ...prev, email: e.target.value.trim() }))
                          }
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="signup-password">Password</Label>
                        <Input
                          id="signup-password"
                          type="password"
                          required
                          minLength={6}
                          value={signupForm.password}
                          onChange={(e) =>
                            setSignupForm((prev) => ({ ...prev, password: e.target.value }))
                          }
                        />
                      </div>
                      <Button type="submit" className="w-full" disabled={signupMutation.isPending}>
                        {signupMutation.isPending ? "Creating account..." : "Create account"}
                      </Button>
                    </form>
                  </motion.div>
                </TabsContent>
                <TabsContent value="login" className="mt-6">
                  <motion.div
                    layout
                    transition={{ type: "spring", stiffness: 400, damping: 30 }}
                  >
                    <form className="space-y-4" onSubmit={handleLogin}>
                      <div className="space-y-2">
                        <Label htmlFor="login-email">Email</Label>
                        <Input
                          id="login-email"
                          type="email"
                          required
                          placeholder="you@example.com"
                          value={loginForm.email}
                          onChange={(e) =>
                            setLoginForm((prev) => ({ ...prev, email: e.target.value.trim() }))
                          }
                        />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="login-password">Password</Label>
                        <Input
                          id="login-password"
                          type="password"
                          required
                          value={loginForm.password}
                          onChange={(e) =>
                            setLoginForm((prev) => ({ ...prev, password: e.target.value }))
                          }
                        />
                      </div>
                      <Button type="submit" className="w-full" disabled={loginMutation.isPending}>
                        {loginMutation.isPending ? "Signing in..." : "Log in"}
                      </Button>
                    </form>
                  </motion.div>
                </TabsContent>
              </Tabs>
            </CardContent>
          )}
        </Card>
      </div>
    </section>
  );
}
