import { useState } from "react";
import { useLocation } from "wouter";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { useMutation } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { 
  Lock, 
  Mail, 
  Eye, 
  EyeOff, 
  Trophy,
  Loader2,
  Users,
  BarChart3,
  Target
} from "lucide-react";

interface LoginData {
  email: string;
  password: string;
}

export default function AuthPage() {
  const [, setLocation] = useLocation();
  const { toast } = useToast();
  const [showPassword, setShowPassword] = useState(false);
  
  // Login form state
  const [loginData, setLoginData] = useState<LoginData>({
    email: "",
    password: ""
  });

  // Login mutation
  const loginMutation = useMutation({
    mutationFn: async (data: LoginData) => {
      const response = await apiRequest("POST", "/api/auth/login", data);
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "Login successful",
        description: "Welcome back to SportsPro",
      });
      // Force a full page reload to ensure proper authentication state
      window.location.href = "/dashboard";
    },
    onError: (error: Error) => {
      toast({
        title: "Login failed",
        description: error.message || "Invalid email or password",
        variant: "destructive",
      });
    },
  });

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    if (!loginData.email || !loginData.password) {
      toast({
        title: "Missing fields",
        description: "Please enter both email and password",
        variant: "destructive",
      });
      return;
    }
    loginMutation.mutate(loginData);
  };

  return (
    <div className="min-h-screen flex">
      {/* Left Side - Sports Image and Branding */}
      <div className="hidden lg:flex lg:w-1/2 bg-gradient-to-br from-primary to-primary/80 relative overflow-hidden">
        {/* Background Pattern */}
        <div 
          className="absolute inset-0 opacity-30"
          style={{
            backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.1'%3E%3Ccircle cx='30' cy='30' r='4'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`
          }}
        ></div>
        
        {/* Sports Illustration */}
        <div className="relative z-10 flex flex-col justify-center items-center p-12 text-white w-full">
          <div className="mb-8">
            <div className="w-24 h-24 bg-white/20 rounded-full flex items-center justify-center mb-6 backdrop-blur-sm">
              <Trophy className="h-12 w-12 text-white" />
            </div>
            <h1 className="text-4xl font-bold mb-4">SportsPro</h1>
            <p className="text-xl text-white/90 mb-8 text-center max-w-md">
              The complete sports management platform for teams and athletes
            </p>
          </div>

          {/* Sports Icons Grid */}
          <div className="grid grid-cols-3 gap-8 mb-8">
            <div className="flex flex-col items-center">
              <div className="w-16 h-16 bg-white/20 rounded-lg flex items-center justify-center mb-2 backdrop-blur-sm">
                <Users className="h-8 w-8 text-white" />
              </div>
              <span className="text-sm text-white/80">Team Management</span>
            </div>
            <div className="flex flex-col items-center">
              <div className="w-16 h-16 bg-white/20 rounded-lg flex items-center justify-center mb-2 backdrop-blur-sm">
                <BarChart3 className="h-8 w-8 text-white" />
              </div>
              <span className="text-sm text-white/80">Analytics</span>
            </div>
            <div className="flex flex-col items-center">
              <div className="w-16 h-16 bg-white/20 rounded-lg flex items-center justify-center mb-2 backdrop-blur-sm">
                <Target className="h-8 w-8 text-white" />
              </div>
              <span className="text-sm text-white/80">Performance</span>
            </div>
          </div>

          {/* Sports Equipment SVG Illustration */}
          <div className="absolute bottom-0 right-0 opacity-20">
            <svg width="300" height="300" viewBox="0 0 300 300" fill="none" xmlns="http://www.w3.org/2000/svg">
              {/* Basketball */}
              <circle cx="80" cy="80" r="35" fill="white" stroke="white" strokeWidth="2"/>
              <path d="M45 80h70M80 45v70M60 60l40 40M60 100l40-40" stroke="currentColor" strokeWidth="2"/>
              
              {/* Soccer Ball */}
              <circle cx="200" cy="120" r="40" fill="white" stroke="white" strokeWidth="2"/>
              <polygon points="200,90 180,110 190,140 210,140 220,110" fill="currentColor"/>
              <polygon points="170,120 180,100 160,110 160,130" fill="currentColor"/>
              <polygon points="230,120 220,100 240,110 240,130" fill="currentColor"/>
              
              {/* Tennis Racket */}
              <ellipse cx="150" cy="220" rx="25" ry="35" fill="none" stroke="white" strokeWidth="3"/>
              <line x1="150" y1="255" x2="150" y2="290" stroke="white" strokeWidth="4"/>
              <path d="M135 210h30M135 220h30M135 230h30" stroke="currentColor" strokeWidth="1"/>
            </svg>
          </div>

          {/* Quote */}
          <div className="text-center mt-8">
            <p className="text-lg italic text-white/90 mb-2">
              "Excellence is not a skill, it's an attitude."
            </p>
            <p className="text-sm text-white/70">- Ralph Marston</p>
          </div>
        </div>
      </div>

      {/* Right Side - Login Form */}
      <div className="flex-1 flex items-center justify-center p-8 bg-gray-50">
        <div className="w-full max-w-md">
          {/* Mobile Logo */}
          <div className="lg:hidden text-center mb-8">
            <div className="flex items-center justify-center mb-4">
              <div className="w-12 h-12 bg-primary rounded-xl flex items-center justify-center">
                <Trophy className="h-7 w-7 text-white" />
              </div>
            </div>
            <h1 className="text-2xl font-bold text-gray-900">SportsPro</h1>
            <p className="text-gray-600 mt-2">Sign in to your account</p>
          </div>

          <Card className="shadow-xl border-0">
            <CardHeader className="space-y-1 pb-6">
              <CardTitle className="text-2xl text-center text-gray-900">Welcome Back</CardTitle>
              <p className="text-center text-gray-600">Enter your credentials to access your account</p>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleLogin} className="space-y-6">
                <div className="space-y-2">
                  <Label htmlFor="email" className="text-sm font-medium text-gray-700">Email Address</Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-3.5 h-4 w-4 text-gray-400" />
                    <Input
                      id="email"
                      type="email"
                      placeholder="Enter your email"
                      className="pl-10 h-12 border-gray-300 focus:border-primary focus:ring-primary"
                      value={loginData.email}
                      onChange={(e) => setLoginData({...loginData, email: e.target.value})}
                      required
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="password" className="text-sm font-medium text-gray-700">Password</Label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-3.5 h-4 w-4 text-gray-400" />
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      placeholder="Enter your password"
                      className="pl-10 pr-12 h-12 border-gray-300 focus:border-primary focus:ring-primary"
                      value={loginData.password}
                      onChange={(e) => setLoginData({...loginData, password: e.target.value})}
                      required
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-0 top-0 h-12 px-3 hover:bg-transparent"
                      onClick={() => setShowPassword(!showPassword)}
                    >
                      {showPassword ? (
                        <EyeOff className="h-4 w-4 text-gray-400" />
                      ) : (
                        <Eye className="h-4 w-4 text-gray-400" />
                      )}
                    </Button>
                  </div>
                </div>

                <div className="flex items-center justify-end">
                  <Button
                    type="button"
                    variant="link"
                    className="px-0 font-normal text-sm text-primary hover:underline"
                    onClick={() => {
                      toast({
                        title: "Forgot Password",
                        description: "Please contact your administrator to reset your password.",
                      });
                    }}
                  >
                    Forgot password?
                  </Button>
                </div>

                <Button 
                  type="submit" 
                  className="w-full h-12 text-base font-medium" 
                  disabled={loginMutation.isPending}
                >
                  {loginMutation.isPending ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Signing in...
                    </>
                  ) : (
                    "Sign In"
                  )}
                </Button>
              </form>

              {/* Demo Credentials Helper */}
              <div className="mt-8 p-4 bg-blue-50 rounded-lg border border-blue-200">
                <p className="text-xs text-blue-800 mb-2 font-medium">Demo Credentials:</p>
                <div className="space-y-1 text-xs text-blue-700">
                  <p><strong>User:</strong> demo@rugby.com / demo123</p>
                  <p><strong>Super Admin:</strong> admin@sportspro.com / superadmin123</p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Footer */}
          <div className="text-center mt-8">
            <p className="text-sm text-gray-500">
              © 2024 SportsPro. Professional sports management platform.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}