
"use client";

import { useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from '@/hooks/use-toast';
import { LogIn, UserPlus } from 'lucide-react';
import { RuningaLogo } from '@/components/icons/runinga-logo';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

// Placeholder icons - consider using actual SVGs for brand logos in a real app
const GoogleIcon = () => <svg className="mr-2 h-4 w-4" viewBox="0 0 24 24"><path fill="currentColor" d="M21.35 11.1h-9.2v2.7h5.1c-.6 2.1-2.5 3.6-4.9 3.6-3 0-5.5-2.4-5.5-5.4s2.5-5.4 5.5-5.4c1.2 0 2.3.4 3.2 1.2l2.1-2.1c-1.7-1.5-4-2.4-6.4-2.4-5.1 0-9.3 4.1-9.3 9.2s4.2 9.2 9.3 9.2c5.3 0 9.1-3.7 9.1-9.4 0-.7-.1-1.2-.2-1.8z"/></svg>;
const FacebookIcon = () => <svg className="mr-2 h-4 w-4" viewBox="0 0 24 24"><path fill="currentColor" d="M22 12c0-5.52-4.48-10-10-10S2 6.48 2 12c0 4.84 3.44 8.87 8 9.8V15H8v-3h2V9.5C10 7.57 11.57 6 13.5 6H16v3h-1.8c-.96 0-1.2.46-1.2 1.18V12h3.1l-.4 3H15v6.8c4.56-.93 8-4.96 8-9.8z"/></svg>;

export default function LoginPage() {
  const [loginEmail, setLoginEmail] = useState('');
  const [loginPassword, setLoginPassword] = useState('');
  const [signupUsername, setSignupUsername] = useState('');
  const [signupEmail, setSignupEmail] = useState('');
  const [signupPassword, setSignupPassword] = useState('');
  const [signupConfirmPassword, setSignupConfirmPassword] = useState('');

  const { login, signInWithGoogle, signInWithFacebook, signUpCreator } = useAuth();
  const { toast } = useToast();

  const handleLoginSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const { success, message } = await login(loginEmail, loginPassword);
    if (!success) {
      toast({
        title: "Login Failed",
        description: message || "Invalid email or password.",
        variant: "destructive",
        duration: 7000,
      });
    }
  };

  const handleSignUpSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (signupPassword !== signupConfirmPassword) {
      toast({ title: "Signup Failed", description: "Passwords do not match.", variant: "destructive" });
      return;
    }
    if (!signupUsername.trim() || !signupEmail.trim() || !signupPassword.trim()) {
      toast({ title: "Signup Failed", description: "Username, email, and password cannot be empty.", variant: "destructive" });
      return;
    }

    const { success, message } = await signUpCreator(signupEmail, signupPassword, signupUsername);
    if (success) {
      toast({
        title: "Account Creation Successful",
        description: message || "You are now logged in. Redirecting...",
      });
    } else {
      toast({
        title: "Account Creation Failed",
        description: message || "Could not create account. The email might be taken or an error occurred.",
        variant: "destructive",
      });
    }
  };

  const handleGoogleSignIn = () => {
    signInWithGoogle(); // Will show an alert for now
  };

  const handleFacebookSignIn = () => {
    signInWithFacebook(); // Will show an alert for now
  };

  return (
    <main className="min-h-screen flex flex-col items-center justify-center p-4">
      <Card className="w-full max-w-md shadow-2xl rounded-xl">
        <CardHeader className="items-center">
            <RuningaLogo className="h-16 w-auto text-primary-foreground mb-2" />
          <CardTitle className="text-2xl font-bold text-center text-foreground">Welcome to RUNINGA</CardTitle>
          <CardDescription className="text-center text-muted-foreground space-y-1">
            <span>Login or create an account to like, comment, or manage streams.</span>
            <br />
            <span className="text-sm block">
              Viewers do not need an account to watch streams.
            </span>
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <Tabs defaultValue="login" className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="login">Login</TabsTrigger>
              <TabsTrigger value="signup">Create Account</TabsTrigger>
            </TabsList>
            <TabsContent value="login">
              <form onSubmit={handleLoginSubmit} className="space-y-6 mt-4">
                <div className="space-y-2">
                  <Label htmlFor="login-email">Email</Label>
                  <Input
                    id="login-email"
                    type="email"
                    value={loginEmail}
                    onChange={(e) => setLoginEmail(e.target.value)}
                    placeholder="you@example.com"
                    className="bg-input border-border placeholder:text-muted-foreground"
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="login-password">Password</Label>
                  <Input
                    id="login-password"
                    type="password"
                    value={loginPassword}
                    onChange={(e) => setLoginPassword(e.target.value)}
                    placeholder="Enter your password"
                    className="bg-input border-border placeholder:text-muted-foreground"
                    required
                  />
                </div>
                <Button type="submit" className="w-full bg-accent text-accent-foreground hover:bg-accent/90">
                  <LogIn className="mr-2 h-4 w-4" /> Login
                </Button>
              </form>

              <div className="relative my-6">
                <div className="absolute inset-0 flex items-center">
                  <span className="w-full border-t border-border" />
                </div>
                <div className="relative flex justify-center text-xs uppercase">
                  <span className="bg-card px-2 text-muted-foreground">
                    Or continue with
                  </span>
                </div>
              </div>

              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <Button variant="outline" className="w-full" onClick={handleGoogleSignIn}>
                  <GoogleIcon /> Sign in with Google
                </Button>
                <Button variant="outline" className="w-full" onClick={handleFacebookSignIn}>
                  <FacebookIcon /> Sign in with Facebook
                </Button>
              </div>
            </TabsContent>

            <TabsContent value="signup">
              <form onSubmit={handleSignUpSubmit} className="space-y-6 mt-4">
                 <div className="space-y-2">
                  <Label htmlFor="signup-username">Username</Label>
                  <Input
                    id="signup-username"
                    type="text"
                    value={signupUsername}
                    onChange={(e) => setSignupUsername(e.target.value)}
                    placeholder="Choose a username"
                    className="bg-input border-border placeholder:text-muted-foreground"
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="signup-email">Email</Label>
                  <Input
                    id="signup-email"
                    type="email"
                    value={signupEmail}
                    onChange={(e) => setSignupEmail(e.target.value)}
                    placeholder="you@example.com"
                    className="bg-input border-border placeholder:text-muted-foreground"
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="signup-password">Password</Label>
                  <Input
                    id="signup-password"
                    type="password"
                    value={signupPassword}
                    onChange={(e) => setSignupPassword(e.target.value)}
                    placeholder="Choose a password (min. 6 characters)"
                    className="bg-input border-border placeholder:text-muted-foreground"
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="signup-confirm-password">Confirm Password</Label>
                  <Input
                    id="signup-confirm-password"
                    type="password"
                    value={signupConfirmPassword}
                    onChange={(e) => setSignupConfirmPassword(e.target.value)}
                    placeholder="Confirm your password"
                    className="bg-input border-border placeholder:text-muted-foreground"
                    required
                  />
                </div>
                <Button type="submit" className="w-full bg-green-600 text-white hover:bg-green-700">
                  <UserPlus className="mr-2 h-4 w-4" /> Create Account
                </Button>
              </form>
               <div className="relative my-6">
                <div className="absolute inset-0 flex items-center">
                  <span className="w-full border-t border-border" />
                </div>
                <div className="relative flex justify-center text-xs uppercase">
                  <span className="bg-card px-2 text-muted-foreground">
                    Or sign up with
                  </span>
                </div>
              </div>
               <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <Button variant="outline" className="w-full" onClick={handleGoogleSignIn}>
                  <GoogleIcon /> Sign up with Google
                </Button>
                <Button variant="outline" className="w-full" onClick={handleFacebookSignIn}>
                  <FacebookIcon /> Sign up with Facebook
                </Button>
              </div>
            </TabsContent>
          </Tabs>
        </CardContent>
        <CardFooter className="text-center text-xs text-muted-foreground pt-4">
            <p>This application now uses Firebase Authentication for secure login and registration.</p>
        </CardFooter>
      </Card>
    </main>
  );
}
