import React, { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useLocation } from "wouter";
import { useAdminAuth } from "@/hooks/useAdminAuth";
import { Card, CardContent, CardDescription, 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 { Badge } from "@/components/ui/badge";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { useToast } from "@/hooks/use-toast";
import { 
  Shield, 
  LogIn, 
  Eye, 
  EyeOff,
  Lock,
  User,
  AlertTriangle,
  KeyRound,
  Crown
} from "lucide-react";

const adminLoginSchema = z.object({
  username: z.string().min(1, "Username is required"),
  password: z.string().min(6, "Password must be at least 6 characters"),
});

type AdminLoginFormData = z.infer<typeof adminLoginSchema>;

export default function AdminLogin() {
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [location, setLocation] = useLocation();
  const { toast } = useToast();
  const { isAdminAuthenticated, login } = useAdminAuth();

  // Check if already authenticated and redirect
  useEffect(() => {
    if (isAdminAuthenticated) {
      setLocation("/admin");
    }
  }, [isAdminAuthenticated, setLocation]);

  const form = useForm<AdminLoginFormData>({
    resolver: zodResolver(adminLoginSchema),
    defaultValues: {
      username: "",
      password: "",
    },
  });

  const onSubmit = async (data: AdminLoginFormData) => {
    setIsLoading(true);
    try {
      // Simulate admin authentication
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // For demo purposes - in real app, this would call your admin auth API
      if (data.username === "admin" && data.password === "sportspro123") {
        const userData = {
          id: "admin_001",
          username: "admin",
          firstName: "System",
          lastName: "Administrator",
          email: "admin@sportspro.com",
          role: "super_admin",
          loginTime: new Date().toISOString()
        };
        
        login(userData);
        
        toast({
          title: "Login Successful",
          description: "Welcome to SportsPro Admin Dashboard",
        });
        
        // Immediate redirect to admin dashboard
        setLocation("/admin");
      } else {
        throw new Error("Invalid credentials");
      }
    } catch (error) {
      toast({
        title: "Login Failed",
        description: "Invalid username or password",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Header */}
        <div className="text-center mb-8">
          <div className="flex items-center justify-center mb-6">
            <div className="w-16 h-16 bg-red-600 rounded-xl flex items-center justify-center shadow-lg">
              <Crown className="h-8 w-8 text-white" />
            </div>
          </div>
          <h1 className="text-3xl font-bold text-white mb-2">
            Admin Portal
          </h1>
          <p className="text-slate-300">
            Secure access to SportsPro administration
          </p>
        </div>

        {/* Login Form */}
        <Card className="border-slate-700 bg-slate-800/50 backdrop-blur-sm shadow-2xl">
          <CardHeader className="text-center space-y-4">
            <Badge variant="destructive" className="bg-red-600 mx-auto">
              <Shield className="h-3 w-3 mr-1" />
              Administrator Access Only
            </Badge>
            <CardTitle className="text-xl font-bold text-white">
              Sign In to Continue
            </CardTitle>
            <CardDescription className="text-slate-300">
              Enter your administrator credentials to access the system
            </CardDescription>
          </CardHeader>
          
          <CardContent>
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                <FormField
                  control={form.control}
                  name="username"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-white">Username</FormLabel>
                      <FormControl>
                        <div className="relative">
                          <User className="absolute left-3 top-3 h-4 w-4 text-slate-400" />
                          <Input 
                            placeholder="Enter admin username"
                            className="pl-10 bg-slate-700/50 border-slate-600 text-white placeholder:text-slate-400"
                            {...field}
                          />
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-white">Password</FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Lock className="absolute left-3 top-3 h-4 w-4 text-slate-400" />
                          <Input 
                            type={showPassword ? "text" : "password"}
                            placeholder="Enter admin password"
                            className="pl-10 pr-10 bg-slate-700/50 border-slate-600 text-white placeholder:text-slate-400"
                            {...field}
                          />
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                            onClick={() => setShowPassword(!showPassword)}
                          >
                            {showPassword ? (
                              <EyeOff className="h-4 w-4 text-slate-400" />
                            ) : (
                              <Eye className="h-4 w-4 text-slate-400" />
                            )}
                          </Button>
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Demo Credentials */}
                <div className="bg-blue-900/30 border border-blue-700/50 rounded-lg p-4">
                  <div className="flex items-center space-x-2 text-blue-300 mb-2">
                    <KeyRound className="h-4 w-4" />
                    <span className="text-sm font-medium">Demo Credentials</span>
                  </div>
                  <div className="text-xs text-blue-200 space-y-1">
                    <p>Username: <code className="bg-blue-800/50 px-1 rounded">admin</code></p>
                    <p>Password: <code className="bg-blue-800/50 px-1 rounded">sportspro123</code></p>
                  </div>
                </div>

                <Button 
                  type="submit"
                  className="w-full bg-red-600 hover:bg-red-700 text-white font-semibold py-3"
                  disabled={isLoading}
                >
                  {isLoading ? (
                    <div className="flex items-center space-x-2">
                      <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                      <span>Authenticating...</span>
                    </div>
                  ) : (
                    <div className="flex items-center space-x-2">
                      <LogIn className="h-4 w-4" />
                      <span>Sign In</span>
                    </div>
                  )}
                </Button>
              </form>
            </Form>

            <div className="mt-6 space-y-4">
              <div className="bg-amber-900/30 border border-amber-700/50 rounded-lg p-3">
                <div className="flex items-center space-x-2 text-amber-300">
                  <AlertTriangle className="h-4 w-4" />
                  <span className="text-sm font-medium">Security Notice</span>
                </div>
                <p className="text-xs text-amber-200 mt-1">
                  This is a restricted area. All access attempts are logged and monitored.
                </p>
              </div>

              <div className="text-center">
                <Button variant="link" className="text-slate-400 text-sm">
                  Forgot password? Contact system administrator
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Footer */}
        <div className="text-center mt-8 text-slate-400">
          <p className="text-sm">
            © 2024 SportsPro Admin Portal. Secure access required.
          </p>
        </div>
      </div>
    </div>
  );
}