import React, { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { 
  Shield, 
  Users, 
  Award, 
  LogIn, 
  ArrowRight,
  CheckCircle,
  Star,
  KeyRound,
  Mail,
  ArrowLeft
} from "lucide-react";

const userTypes = [
  {
    type: "Administrator",
    icon: Shield,
    color: "bg-red-600",
    description: "Full system access and management capabilities",
    features: [
      "Manage all teams and players",
      "User account administration", 
      "System settings and configuration",
      "Analytics and reporting access"
    ]
  },
  {
    type: "Coach",
    icon: Award,
    color: "bg-blue-600", 
    description: "Team and player management for assigned teams",
    features: [
      "Manage assigned teams",
      "Player roster management",
      "Performance tracking",
      "Biometric data access"
    ]
  },
  {
    type: "User/Viewer",
    icon: Users,
    color: "bg-green-600",
    description: "View-only access to team and player information", 
    features: [
      "View team information",
      "Access player profiles",
      "View statistics and reports",
      "Limited dashboard access"
    ]
  }
];

export default function Login() {
  const [showPasswordReset, setShowPasswordReset] = useState(false);
  const [resetEmail, setResetEmail] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [resetSent, setResetSent] = useState(false);
  const { toast } = useToast();

  const handleLogin = () => {
    window.location.href = "/api/login";
  };

  const handlePasswordReset = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!resetEmail) {
      toast({
        title: "Email Required",
        description: "Please enter your email address",
        variant: "destructive",
      });
      return;
    }

    setIsLoading(true);
    try {
      const response = await fetch("/api/auth/request-password-reset", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ email: resetEmail }),
      });

      const data = await response.json();
      
      if (response.ok) {
        setResetSent(true);
        toast({
          title: "Reset Link Sent",
          description: data.message,
        });
        
        // For demo purposes, show the reset token
        if (data.resetToken) {
          console.log("Demo reset token:", data.resetToken);
          toast({
            title: "Demo Mode",
            description: `Reset token: ${data.resetToken.substring(0, 8)}... (check console for full token)`,
          });
        }
      } else {
        toast({
          title: "Error",
          description: data.message || "Failed to send reset link",
          variant: "destructive",
        });
      }
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to send reset link. Please try again.",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  const resetPasswordResetForm = () => {
    setShowPasswordReset(false);
    setResetEmail("");
    setResetSent(false);
    setIsLoading(false);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-blue-50 flex items-center justify-center p-4">
      <div className="w-full max-w-6xl">
        {/* Header */}
        <div className="text-center mb-12">
          <div className="flex items-center justify-center mb-6">
            <div className="w-16 h-16 bg-primary rounded-xl flex items-center justify-center shadow-lg">
              <Star className="h-8 w-8 text-white" />
            </div>
          </div>
          <h1 className="text-4xl font-bold text-gray-900 mb-4">
            Welcome to <span className="text-primary">SportsPro</span>
          </h1>
          <p className="text-xl text-gray-600 max-w-2xl mx-auto">
            Your comprehensive sports management platform. Sign in to access team management, 
            player profiles, and performance analytics.
          </p>
        </div>

        {/* User Type Cards */}
        <div className="grid md:grid-cols-3 gap-8 mb-12">
          {userTypes.map((userType) => (
            <Card key={userType.type} className="relative overflow-hidden border-2 hover:border-primary/20 transition-all duration-300 hover:shadow-lg">
              <CardHeader className="text-center pb-4">
                <div className={`w-14 h-14 ${userType.color} rounded-lg flex items-center justify-center mx-auto mb-4 shadow-md`}>
                  <userType.icon className="h-7 w-7 text-white" />
                </div>
                <CardTitle className="text-xl font-bold text-gray-900">
                  {userType.type}
                </CardTitle>
                <CardDescription className="text-gray-600">
                  {userType.description}
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-3">
                {userType.features.map((feature, index) => (
                  <div key={index} className="flex items-center space-x-3">
                    <CheckCircle className="h-4 w-4 text-green-600 flex-shrink-0" />
                    <span className="text-sm text-gray-700">{feature}</span>
                  </div>
                ))}
              </CardContent>
            </Card>
          ))}
        </div>

        {/* Login Section */}
        <Card className="max-w-md mx-auto border-2 border-primary/20 shadow-xl">
          <CardHeader className="text-center space-y-4">
            <Badge variant="secondary" className="bg-primary/10 text-primary mx-auto">
              {showPasswordReset ? "Password Reset" : "Secure Authentication"}
            </Badge>
            <CardTitle className="text-2xl font-bold text-gray-900">
              {showPasswordReset ? "Reset Your Password" : "Sign In to Continue"}
            </CardTitle>
            <CardDescription className="text-gray-600">
              {showPasswordReset 
                ? "Enter your email address to receive a password reset link" 
                : "Access your SportsPro account to manage teams, players, and performance data"
              }
            </CardDescription>
          </CardHeader>
          
          <CardContent className="space-y-6">
            {!showPasswordReset ? (
              <>
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <div className="flex items-center space-x-2 text-blue-700">
                    <Shield className="h-4 w-4" />
                    <span className="text-sm font-medium">Secure Login via Replit</span>
                  </div>
                  <p className="text-xs text-blue-600 mt-1">
                    Your credentials are protected with enterprise-grade security
                  </p>
                </div>

                <Button 
                  onClick={handleLogin}
                  className="w-full bg-primary hover:bg-primary/90 text-white font-semibold py-3 text-lg flex items-center justify-center space-x-2 shadow-lg"
                  size="lg"
                >
                  <LogIn className="h-5 w-5" />
                  <span>Sign In</span>
                  <ArrowRight className="h-4 w-4" />
                </Button>

                <div className="flex flex-col items-center space-y-3 text-sm text-gray-500">
                  <p>New to SportsPro? Contact your administrator for access.</p>
                  <Button
                    variant="link"
                    onClick={() => setShowPasswordReset(true)}
                    className="text-primary hover:text-primary/80 p-0 h-auto font-normal"
                  >
                    <KeyRound className="h-4 w-4 mr-1" />
                    Forgot your password?
                  </Button>
                </div>
              </>
            ) : (
              <>
                {!resetSent ? (
                  <form onSubmit={handlePasswordReset} className="space-y-4">
                    <div className="space-y-2">
                      <Label htmlFor="reset-email">Email Address</Label>
                      <div className="relative">
                        <Mail className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                        <Input
                          id="reset-email"
                          type="email"
                          placeholder="Enter your email address"
                          value={resetEmail}
                          onChange={(e) => setResetEmail(e.target.value)}
                          className="pl-10"
                          required
                        />
                      </div>
                    </div>

                    <Button
                      type="submit"
                      disabled={isLoading}
                      className="w-full bg-primary hover:bg-primary/90 text-white font-semibold py-3"
                    >
                      {isLoading ? (
                        <>
                          <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2" />
                          Sending Reset Link...
                        </>
                      ) : (
                        <>
                          <Mail className="h-4 w-4 mr-2" />
                          Send Reset Link
                        </>
                      )}
                    </Button>
                  </form>
                ) : (
                  <div className="text-center space-y-4">
                    <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                      <CheckCircle className="h-8 w-8 text-green-600 mx-auto mb-2" />
                      <p className="text-sm text-green-700 font-medium">Reset link sent!</p>
                      <p className="text-xs text-green-600 mt-1">
                        Check your email for the password reset link
                      </p>
                    </div>
                    
                    <Button
                      onClick={resetPasswordResetForm}
                      variant="outline"
                      className="w-full"
                    >
                      Try Different Email
                    </Button>
                  </div>
                )}

                <Button
                  onClick={resetPasswordResetForm}
                  variant="ghost"
                  className="w-full text-gray-500 hover:text-gray-700"
                >
                  <ArrowLeft className="h-4 w-4 mr-2" />
                  Back to Sign In
                </Button>
              </>
            )}
          </CardContent>
        </Card>

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