import { useState, useEffect } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useLocation } from "wouter";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { registerSchema, loginSchema, type RegisterData, type LoginData } from "@shared/schema";
import { Music } from "lucide-react";
import { ForgotPasswordForm } from "@/components/forgot-password-form";
import { ResetPasswordForm } from "@/components/reset-password-form";
import { Alert, AlertDescription } from "@/components/ui/alert";

// Helper function to process pending invite codes
const processPendingInvite = async (toast: any) => {
  const pendingInviteCode = localStorage.getItem('pendingInviteCode');
  if (pendingInviteCode) {
    try {
      const response = await fetch("/api/bands/join", {
        method: "POST",
        body: JSON.stringify({ inviteCode: pendingInviteCode }),
        headers: { "Content-Type": "application/json" },
      });
      
      if (response.ok) {
        const result = await response.json();
        toast({
          title: "Welcome to the band!",
          description: `You've been added to "${result.bandName}".`,
        });
        localStorage.removeItem('pendingInviteCode');
      }
    } catch (error) {
      // Silent fail for invite processing - user is still logged in
      console.error("Failed to process invite:", error);
      localStorage.removeItem('pendingInviteCode');
    }
  }
};

export default function Auth() {
  const [, setLocation] = useLocation();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [activeTab, setActiveTab] = useState("login");
  const [showForgotPassword, setShowForgotPassword] = useState(false);
  const [resetToken, setResetToken] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [betaEmail, setBetaEmail] = useState("");
  const [isBetaSubmitting, setIsBetaSubmitting] = useState(false);
  const [betaSuccess, setBetaSuccess] = useState(false);
  const [betaError, setBetaError] = useState("");
  const [showInviteForm, setShowInviteForm] = useState(false);

  // Check for reset token and tab in URL
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const token = params.get('token');
    const message = params.get('message');
    const tab = params.get('tab');
    
    if (token) {
      setResetToken(token);
    }
    
    if (message) {
      setSuccessMessage(message);
    }
    
    // Check for pending invite code - if exists, default to register tab
    const pendingInviteCode = localStorage.getItem('pendingInviteCode');
    if (pendingInviteCode) {
      setActiveTab('register');
      setShowInviteForm(true);
    } else if (tab === 'register' || tab === 'beta') {
      // Handle tab parameter (e.g., ?tab=register for old signup links, ?tab=beta for beta signup)
      setActiveTab('beta');
    }
  }, []);

  const loginForm = useForm<LoginData>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: "",
      password: "",
    },
  });

  const registerForm = useForm<RegisterData>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      email: "",
      password: "",
      firstName: "",
      lastName: "",
    },
  });

  // Handle email pre-population from URL
  useEffect(() => {
    const pendingEmail = localStorage.getItem('pendingEmail');
    if (pendingEmail) {
      // Set email in both login and register forms
      loginForm.setValue('email', pendingEmail);
      registerForm.setValue('email', pendingEmail);
      // Clear the pending email after use
      localStorage.removeItem('pendingEmail');
    }
  }, [loginForm, registerForm]);

  const loginMutation = useMutation({
    mutationFn: async (data: LoginData) => {
      const response = await fetch("/api/auth/login", {
        method: "POST",
        body: JSON.stringify(data),
        headers: { "Content-Type": "application/json" },
      });
      if (!response.ok) {
        const errorData = await response.json();
        const error = new Error(errorData.message || "Failed to login");
        // Attach the full error data as cause
        (error as any).cause = errorData;
        throw error;
      }
      return response.json();
    },
    onSuccess: async () => {
      toast({
        title: "Welcome back!",
        description: "You've successfully logged in.",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/auth/user"] });
      
      // Process any pending invite codes
      await processPendingInvite(toast);
      
      setLocation("/");
    },
    onError: async (error: any) => {
      const errorData = error?.cause || {};
      
      if (errorData.requiresVerification) {
        setSuccessMessage("Please verify your email before logging in. Check your inbox for the verification email.");
        toast({
          title: "Email Verification Required",
          description: "Please verify your email before logging in.",
          variant: "destructive",
        });
      } else {
        toast({
          title: "Login failed",
          description: error.message,
          variant: "destructive",
        });
      }
    },
  });

  const registerMutation = useMutation({
    mutationFn: async (data: RegisterData) => {
      const response = await fetch("/api/auth/register", {
        method: "POST",
        body: JSON.stringify(data),
        headers: { "Content-Type": "application/json" },
      });
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || "Failed to register");
      }
      return response.json();
    },
    onSuccess: async (data) => {
      if (data.emailVerified === false) {
        // Show email verification message
        setSuccessMessage("Registration successful! Please check your email to verify your account before logging in.");
        setActiveTab("login");
        toast({
          title: "Verification Email Sent",
          description: "Please check your email to verify your account.",
        });
      } else {
        // Legacy behavior if email verification is not enabled
        toast({
          title: "Account created!",
          description: "Welcome to GigGrid! Let's create your first band to get started.",
        });
        queryClient.invalidateQueries({ queryKey: ["/api/auth/user"] });
        
        // Clear the demo songs welcome flag for new users
        localStorage.removeItem("hasSeenDemoSongsWelcome");
        
        // Set a flag to show they're a new user
        localStorage.setItem("isNewUser", "true");
        
        // Process any pending invite codes
        await processPendingInvite(toast);
        
        setLocation("/");
      }
    },
    onError: (error: Error) => {
      toast({
        title: "Registration failed",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const onLogin = (data: LoginData) => {
    loginMutation.mutate(data);
  };

  const onRegister = (data: RegisterData) => {
    registerMutation.mutate(data);
  };

  const handleBetaSignup = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsBetaSubmitting(true);
    setBetaError("");
    setBetaSuccess(false);

    try {
      const response = await fetch("/api/beta-signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: betaEmail, source: "auth-page" }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || "Failed to sign up");
      }

      setBetaSuccess(true);
      setBetaEmail("");
      toast({
        title: "Success!",
        description: "We'll send you an invite when your spot opens up.",
      });
    } catch (err) {
      setBetaError(err instanceof Error ? err.message : "Something went wrong");
      toast({
        title: "Error",
        description: err instanceof Error ? err.message : "Failed to submit beta request",
        variant: "destructive",
      });
    } finally {
      setIsBetaSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#fafaf7] dark:bg-[#11120d] flex items-center justify-center p-4 pt-safe-ios">
      <div className="w-full max-w-md">
        {/* Header */}
        <div className="text-center mb-8">
          <div className="flex items-center justify-center space-x-2 mb-4">
            <Music className="h-8 w-8 text-[#315f3f]" />
            <h1 className="text-2xl font-bold text-[#171812] dark:text-[#f4f2e8]">
              GigGrid
            </h1>
          </div>
          <p className="text-gray-600 dark:text-gray-400">Collaborate with bands using the Nashville Number System</p>
        </div>

        <Card>
          <CardHeader>
            <CardTitle className="text-center">
              {resetToken ? "Reset Password" : showForgotPassword ? "Forgot Password" : "Welcome"}
            </CardTitle>
            <CardDescription className="text-center">
              {resetToken ? "Enter your new password" : showForgotPassword ? "Enter your email to receive a reset link" : "Sign in to your account or create a new one"}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {successMessage && (
              <Alert className="mb-4">
                <AlertDescription>{successMessage}</AlertDescription>
              </Alert>
            )}
            
            {resetToken ? (
              <ResetPasswordForm token={resetToken} />
            ) : showForgotPassword ? (
              <>
                <ForgotPasswordForm />
                <Button
                  variant="link"
                  className="w-full mt-4"
                  onClick={() => setShowForgotPassword(false)}
                >
                  Back to login
                </Button>
              </>
            ) : (
            <Tabs value={activeTab} onValueChange={setActiveTab}>
              <TabsList className={`grid w-full ${localStorage.getItem('pendingInviteCode') ? 'grid-cols-2' : 'grid-cols-2'}`}>
                <TabsTrigger value="login">Sign In</TabsTrigger>
                {localStorage.getItem('pendingInviteCode') ? (
                  <TabsTrigger value="register">Create Account</TabsTrigger>
                ) : (
                  <TabsTrigger value="beta">Request Beta Access</TabsTrigger>
                )}
              </TabsList>

              <TabsContent value="login" className="space-y-4">
                <Form {...loginForm}>
                  <form onSubmit={loginForm.handleSubmit(onLogin)} className="space-y-4">
                    <FormField
                      control={loginForm.control}
                      name="email"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Email</FormLabel>
                          <FormControl>
                            <Input 
                              type="email"
                              placeholder="Enter your email" 
                              autoComplete="email"
                              {...field} 
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={loginForm.control}
                      name="password"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Password</FormLabel>
                          <FormControl>
                            <Input 
                              type="password"
                              placeholder="Enter your password" 
                              autoComplete="current-password"
                              {...field} 
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <Button type="submit" className="w-full" disabled={loginMutation.isPending}>
                      {loginMutation.isPending ? "Signing in..." : "Sign In"}
                    </Button>
                    <Button
                      type="button"
                      variant="link"
                      className="w-full"
                      onClick={() => setShowForgotPassword(true)}
                    >
                      Forgot your password?
                    </Button>
                  </form>
                </Form>
              </TabsContent>

              <TabsContent value="register" className="space-y-4">
                {localStorage.getItem('pendingInviteCode') && (
                  <Alert className="mb-4">
                    <AlertDescription>
                      🎉 You've been invited to join a band! Create your account below and you'll be automatically added.
                    </AlertDescription>
                  </Alert>
                )}
                <Form {...registerForm}>
                  <form onSubmit={registerForm.handleSubmit(onRegister)} className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={registerForm.control}
                        name="firstName"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>First Name</FormLabel>
                            <FormControl>
                              <Input placeholder="First name" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={registerForm.control}
                        name="lastName"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Last Name</FormLabel>
                            <FormControl>
                              <Input placeholder="Last name" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                    <FormField
                      control={registerForm.control}
                      name="email"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Email</FormLabel>
                          <FormControl>
                            <Input 
                              type="email" 
                              placeholder="Enter your email" 
                              autoComplete="email"
                              {...field} 
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={registerForm.control}
                      name="password"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Password</FormLabel>
                          <FormControl>
                            <Input 
                              type="password" 
                              placeholder="Create a password" 
                              autoComplete="new-password"
                              {...field} 
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <Button type="submit" className="w-full" disabled={registerMutation.isPending}>
                      {registerMutation.isPending ? "Creating account..." : "Create Account"}
                    </Button>
                  </form>
                </Form>
              </TabsContent>

              {!localStorage.getItem('pendingInviteCode') && (
                <TabsContent value="beta" className="space-y-4">
                  <div className="space-y-4">
                    <p className="text-sm text-muted-foreground">
                      GigGrid is currently in private beta. Request access and we'll send you an invite when space opens up.
                    </p>
                    <form onSubmit={handleBetaSignup} className="space-y-4">
                      <div className="space-y-2">
                        <label htmlFor="beta-email" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
                          Email
                        </label>
                        <Input 
                          id="beta-email"
                          type="email"
                          placeholder="Enter your email" 
                          value={betaEmail}
                          onChange={(e) => setBetaEmail(e.target.value)}
                          required
                          autoComplete="email"
                        />
                      </div>
                      <Button type="submit" className="w-full" disabled={isBetaSubmitting}>
                        {isBetaSubmitting ? "Requesting access..." : "Request Beta Access"}
                      </Button>
                    </form>
                    {betaSuccess && (
                      <Alert>
                        <AlertDescription>
                          Thanks for your interest! We'll send you an invite when your spot opens.
                        </AlertDescription>
                      </Alert>
                    )}
                    {betaError && (
                      <Alert variant="destructive">
                        <AlertDescription>{betaError}</AlertDescription>
                      </Alert>
                    )}
                    <div className="text-center pt-4">
                      <p className="text-sm text-muted-foreground">
                        Have an invite code? 
                        <Button
                          variant="link"
                          className="ml-1 p-0 h-auto"
                          onClick={() => setShowInviteForm(true)}
                        >
                          Enter it here
                        </Button>
                      </p>
                    </div>
                  </div>
                </TabsContent>
              )}
            </Tabs>
            )}
          </CardContent>
        </Card>

        {/* Invite Code Dialog - Only show if no pending invite code and showInviteForm is true */}
        {showInviteForm && !localStorage.getItem('pendingInviteCode') && (
          <Card className="mt-4">
            <CardHeader>
              <CardTitle>Enter Invite Code</CardTitle>
              <CardDescription>
                If you have received an invite code, you can use it to create your account.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Form {...registerForm}>
                <form onSubmit={registerForm.handleSubmit(onRegister)} className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <FormField
                      control={registerForm.control}
                      name="firstName"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>First Name</FormLabel>
                          <FormControl>
                            <Input 
                              placeholder="First name" 
                              autoComplete="given-name"
                              {...field} 
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={registerForm.control}
                      name="lastName"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Last Name</FormLabel>
                          <FormControl>
                            <Input 
                              placeholder="Last name" 
                              autoComplete="family-name"
                              {...field} 
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                  <FormField
                    control={registerForm.control}
                    name="email"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Email</FormLabel>
                        <FormControl>
                          <Input 
                            type="email"
                            placeholder="Enter your email" 
                            autoComplete="email"
                            {...field} 
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={registerForm.control}
                    name="password"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Password</FormLabel>
                        <FormControl>
                          <Input 
                            type="password"
                            placeholder="Create a password" 
                            autoComplete="new-password"
                            {...field} 
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <Button type="submit" className="w-full" disabled={registerMutation.isPending}>
                    {registerMutation.isPending ? "Creating account..." : "Create Account"}
                  </Button>
                  <Button
                    type="button"
                    variant="ghost"
                    className="w-full"
                    onClick={() => setShowInviteForm(false)}
                  >
                    Back to Beta Request
                  </Button>
                </form>
              </Form>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}