import React, { useState, useEffect } from "react";
import { useQuery, 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 { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/hooks/useAuth";
import { apiRequest } from "@/lib/queryClient";
import AdminProfileEditor from "@/components/admin/admin-profile-editor";
import {
  Shield,
  Users,
  UserPlus,
  Edit,
  Trash2,
  Save,
  UserCheck,
  UserX,
  Menu,
  X,
} from "lucide-react";

interface AdminUser {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  role: string;
  status: string;
  profileImageUrl?: string;
  createdAt: string;
  lastLogin?: string;
  permissions: string[];
}

export default function Admin() {
  const [, setLocation] = useLocation();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const { user, isLoading, isAuthenticated } = useAuth();
  
  const [showUserDialog, setShowUserDialog] = useState(false);
  const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);
  const [showProfileEdit, setShowProfileEdit] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [userFormData, setUserFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    role: 'user',
    password: '',
    confirmPassword: ''
  });
  const [generatedPassword, setGeneratedPassword] = useState('');

  // Check if user has admin permissions
  const isAdminAuthenticated = isAuthenticated && user && ((user as any).role === 'org_admin' || (user as any).role === 'superadmin');

  const { data: users, isLoading: isLoadingUsers } = useQuery({
    queryKey: ["/api/admin/users"],
    enabled: !!isAdminAuthenticated,
  });

  // Generate secure password
  const generatePassword = () => {
    const chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789!@#$%&*';
    let password = '';
    for (let i = 0; i < 12; i++) {
      password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return password;
  };

  const createUserMutation = useMutation({
    mutationFn: async (userData: any) => {
      const response = await apiRequest("POST", "/api/admin/users", userData);
      return response;
    },
    onSuccess: async (data: any) => {
      // Force refetch the users data
      await queryClient.refetchQueries({ queryKey: ["/api/admin/users"] });
      setShowUserDialog(false);
      setUserFormData({
        firstName: '',
        lastName: '',
        email: '',
        role: 'user',
        password: '',
        confirmPassword: ''
      });
      setGeneratedPassword('');
      toast({
        title: "User Created",
        description: `User ${data.user?.firstName || userFormData.firstName} ${data.user?.lastName || userFormData.lastName} has been created successfully`,
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to create user",
        variant: "destructive",
      });
    },
  });

  const deleteUserMutation = useMutation({
    mutationFn: async (userId: string) => {
      await apiRequest("DELETE", `/api/admin/users/${userId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/admin/users"] });
      toast({
        title: "User Deleted",
        description: "User has been successfully deleted",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to delete user",
        variant: "destructive",
      });
    },
  });

  // Check authentication and redirect if not authenticated
  useEffect(() => {
    if (!isLoading && !isAdminAuthenticated) {
      setLocation("/auth");
    }
  }, [isAdminAuthenticated, isLoading, setLocation]);

  const handleAdminLogout = () => {
    window.location.href = "/auth";
  };

  // Helper functions for user management
  const openUserDialog = (user?: AdminUser) => {
    setSelectedUser(user || null);
    if (user) {
      setUserFormData({
        firstName: user.firstName,
        lastName: user.lastName,
        email: user.email,
        role: user.role,
        password: '',
        confirmPassword: ''
      });
    } else {
      setUserFormData({
        firstName: '',
        lastName: '',
        email: '',
        role: 'user',
        password: '',
        confirmPassword: ''
      });
    }
    setGeneratedPassword('');
    setShowUserDialog(true);
  };

  const handleGeneratePassword = () => {
    const newPassword = generatePassword();
    setGeneratedPassword(newPassword);
    setUserFormData(prev => ({
      ...prev,
      password: newPassword,
      confirmPassword: newPassword
    }));
  };

  const handleCreateUser = () => {
    if (!userFormData.firstName || !userFormData.lastName || !userFormData.email || !userFormData.password) {
      toast({
        title: "Error",
        description: "Please fill in all required fields",
        variant: "destructive",
      });
      return;
    }

    if (userFormData.password !== userFormData.confirmPassword) {
      toast({
        title: "Error",
        description: "Passwords do not match",
        variant: "destructive",
      });
      return;
    }

    createUserMutation.mutate(userFormData);
  };

  // Use real API data instead of mock data
  const adminUsers: AdminUser[] = Array.isArray(users) ? users : [];

  const currentAdminUser = {
    id: user?.id || "admin_001",
    firstName: "System",
    lastName: "Administrator", 
    email: user?.email || "admin@sportspro.com",
    profileImageUrl: undefined
  };

  // Show loading state while checking authentication - moved after all hooks
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-50">
        <div className="text-center p-6">
          <Shield className="h-12 w-12 animate-spin mx-auto mb-4 text-primary" />
          <p className="text-gray-600">Verifying admin access...</p>
        </div>
      </div>
    );
  }

  // Show loading state for users data
  if (isLoadingUsers) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-50">
        <div className="text-center p-6">
          <Shield className="h-12 w-12 animate-spin mx-auto mb-4 text-primary" />
          <p className="text-gray-600">Loading users...</p>
        </div>
      </div>
    );
  }

  const AdminProfile = () => (
    <Card className="w-full">
      <CardHeader className="text-center pb-4">
        <div className="flex flex-col items-center space-y-4">
          <div className="relative">
            <Avatar className="h-20 w-20 sm:h-24 sm:w-24">
              <AvatarImage src={currentAdminUser.profileImageUrl} />
              <AvatarFallback className="bg-primary/10 text-primary text-lg sm:text-xl font-bold">
                {currentAdminUser.firstName[0]}{currentAdminUser.lastName[0]}
              </AvatarFallback>
            </Avatar>
          </div>
          <div className="text-center">
            <h2 className="text-xl sm:text-2xl font-bold text-gray-900">
              {currentAdminUser.firstName} {currentAdminUser.lastName}
            </h2>
            <p className="text-sm sm:text-base text-gray-600">{currentAdminUser.email}</p>
            <Badge className="bg-red-500 mt-2">System Administrator</Badge>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        <Button 
          onClick={() => setShowProfileEdit(true)} 
          className="w-full"
        >
          <Edit className="h-4 w-4 mr-2" />
          Edit Profile
        </Button>
      </CardContent>
    </Card>
  );

  const UserManagementTable = () => (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
        <div>
          <CardTitle className="text-lg sm:text-xl">User Management</CardTitle>
          <CardDescription className="text-sm">
            Manage administrator accounts and permissions
          </CardDescription>
        </div>
        <Button
          onClick={() => openUserDialog()}
          size="sm"
        >
          <UserPlus className="h-4 w-4 mr-2" />
          Add User
        </Button>
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          {adminUsers.map((adminUser: AdminUser) => (
            <div
              key={adminUser.id}
              className="flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 border rounded-lg bg-white space-y-3 sm:space-y-0"
            >
              <div className="flex items-center space-x-3 flex-1">
                <Avatar className="h-10 w-10">
                  <AvatarImage src={adminUser.profileImageUrl} />
                  <AvatarFallback className="bg-primary/10 text-primary font-medium">
                    {adminUser.firstName[0]}{adminUser.lastName[0]}
                  </AvatarFallback>
                </Avatar>
                <div className="flex-1">
                  <div className="flex flex-col sm:flex-row sm:items-center gap-2">
                    <h3 className="font-medium text-gray-900">
                      {adminUser.firstName} {adminUser.lastName}
                    </h3>
                    <div className="flex items-center gap-2">
                      <Badge
                        variant={adminUser.role === "super_admin" ? "default" : "secondary"}
                        className="text-xs"
                      >
                        {adminUser.role === "super_admin" ? "Super Admin" : "Admin"}
                      </Badge>
                      <Badge
                        variant={adminUser.status === "active" ? "default" : "secondary"}
                        className="text-xs"
                      >
                        {adminUser.status === "active" ? (
                          <UserCheck className="h-3 w-3 mr-1" />
                        ) : (
                          <UserX className="h-3 w-3 mr-1" />
                        )}
                        {adminUser.status}
                      </Badge>
                    </div>
                  </div>
                  <p className="text-sm text-gray-600">{adminUser.email}</p>
                </div>
              </div>

              <div className="flex items-center gap-2 self-end sm:self-center">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setSelectedUser(adminUser);
                    setShowUserDialog(true);
                  }}
                >
                  <Edit className="h-4 w-4" />
                  <span className="sr-only">Edit</span>
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    if (confirm("Are you sure you want to delete this user?")) {
                      deleteUserMutation.mutate(adminUser.id);
                    }
                  }}
                >
                  <Trash2 className="h-4 w-4" />
                  <span className="sr-only">Delete</span>
                </Button>
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );

  if (isLoadingUsers) {
    return (
      <div className="min-h-screen bg-gray-50 p-3 sm:p-4 lg:p-6">
        <div className="max-w-7xl mx-auto">
          <div className="animate-pulse space-y-4">
            <div className="h-8 bg-gray-200 rounded w-1/4"></div>
            <div className="h-32 bg-gray-200 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  // Don't render admin panel if not authenticated
  if (!isAdminAuthenticated) {
    return null;
  }

  return (
    <div className="p-4 sm:p-6">
      {/* Simple Admin Header with Toggle */}
      <div className="flex items-center justify-between mb-6 pb-4 border-b">
        <div className="flex items-center space-x-4">
          {/* Simple menu button */}
          <button
            className="md:hidden p-2 rounded-md border border-gray-300 hover:bg-gray-50"
            onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
          >
            <div className="w-5 h-5 flex flex-col justify-center space-y-1">
              <div className="w-full h-0.5 bg-gray-600"></div>
              <div className="w-full h-0.5 bg-gray-600"></div>
              <div className="w-full h-0.5 bg-gray-600"></div>
            </div>
          </button>
          
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-red-600 rounded-lg flex items-center justify-center">
              <Shield className="h-6 w-6 text-white" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-gray-900">Admin Portal</h1>
              <p className="text-xs text-gray-500">System Administration</p>
            </div>
          </div>
        </div>
        
        <Badge className="bg-red-500">
          <Shield className="h-4 w-4 mr-1" />
          Administrator Access
        </Badge>
      </div>

      {/* Mobile Menu */}
      {mobileMenuOpen && (
        <div className="md:hidden mb-6 p-4 bg-gray-50 rounded-lg border">
          <div className="flex items-center justify-between mb-3">
            <h3 className="font-medium text-gray-900">Navigation</h3>
            <button
              onClick={() => setMobileMenuOpen(false)}
              className="p-1 rounded hover:bg-gray-200"
            >
              <X className="h-4 w-4" />
            </button>
          </div>
          <div className="space-y-2">
            <Button variant="ghost" className="w-full justify-start text-sm">
              <Users className="h-4 w-4 mr-2" />
              User Management
            </Button>
            <Button variant="ghost" className="w-full justify-start text-sm">
              <UserCheck className="h-4 w-4 mr-2" />
              My Profile
            </Button>
          </div>
        </div>
      )}

      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">Admin Dashboard</h1>
            <p className="text-gray-600">Manage users, permissions, and system settings</p>
          </div>
        </div>

        <Tabs defaultValue="users" className="space-y-6">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="users" className="flex items-center gap-2 p-3">
              <Users className="h-4 w-4" />
              <span>User Management</span>
            </TabsTrigger>
            <TabsTrigger value="profile" className="flex items-center gap-2 p-3">
              <UserCheck className="h-4 w-4" />
              <span>My Profile</span>
            </TabsTrigger>
          </TabsList>

          <TabsContent value="users">
            <UserManagementTable />
          </TabsContent>

          <TabsContent value="profile">
            <AdminProfile />
          </TabsContent>
        </Tabs>

        {/* User Creation/Edit Dialog */}
        <Dialog open={showUserDialog} onOpenChange={setShowUserDialog}>
          <DialogContent className="max-w-md mx-4 sm:mx-auto">
            <DialogHeader>
              <DialogTitle className="text-lg">
                {selectedUser ? "Edit Admin User" : "Create Admin User"}
              </DialogTitle>
              <DialogDescription className="text-sm">
                {selectedUser ? "Update user information and permissions" : "Add a new administrator to the system"}
              </DialogDescription>
            </DialogHeader>
            <form onSubmit={(e) => {
              e.preventDefault();
              handleCreateUser();
            }} className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="firstName" className="text-sm">First Name *</Label>
                  <Input 
                    id="firstName" 
                    placeholder="John"
                    value={userFormData.firstName}
                    onChange={(e) => setUserFormData(prev => ({ ...prev, firstName: e.target.value }))}
                    autoComplete="given-name"
                  />
                </div>
                <div>
                  <Label htmlFor="lastName" className="text-sm">Last Name *</Label>
                  <Input 
                    id="lastName" 
                    placeholder="Doe"
                    value={userFormData.lastName}
                    onChange={(e) => setUserFormData(prev => ({ ...prev, lastName: e.target.value }))}
                    autoComplete="family-name"
                  />
                </div>
              </div>
              
              <div>
                <Label htmlFor="email" className="text-sm">Email *</Label>
                <Input 
                  id="email" 
                  type="email" 
                  placeholder="user@example.com"
                  value={userFormData.email}
                  onChange={(e) => setUserFormData(prev => ({ ...prev, email: e.target.value }))}
                  autoComplete="email"
                />
              </div>
              
              <div>
                <Label htmlFor="role" className="text-sm">Role *</Label>
                <Select 
                  value={userFormData.role} 
                  onValueChange={(value) => setUserFormData(prev => ({ ...prev, role: value }))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select role" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="user">User</SelectItem>
                    <SelectItem value="coach">Coach</SelectItem>
                    <SelectItem value="admin">Admin</SelectItem>
                    <SelectItem value="org_admin">Organization Admin</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Password Section */}
              <div className="space-y-3 p-4 bg-gray-50 rounded-lg border">
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-medium">Password Setup</Label>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={handleGeneratePassword}
                    className="text-xs"
                  >
                    Generate Secure Password
                  </Button>
                </div>
                
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <div>
                    <Label htmlFor="password" className="text-sm">Password *</Label>
                    <Input 
                      id="password" 
                      type="password" 
                      placeholder="Enter password"
                      value={userFormData.password}
                      onChange={(e) => setUserFormData(prev => ({ ...prev, password: e.target.value }))}
                      autoComplete="new-password"
                    />
                  </div>
                  <div>
                    <Label htmlFor="confirmPassword" className="text-sm">Confirm Password *</Label>
                    <Input 
                      id="confirmPassword" 
                      type="password" 
                      placeholder="Confirm password"
                      value={userFormData.confirmPassword}
                      onChange={(e) => setUserFormData(prev => ({ ...prev, confirmPassword: e.target.value }))}
                      autoComplete="new-password"
                    />
                  </div>
                </div>

                {generatedPassword && (
                  <div className="p-3 bg-green-50 border border-green-200 rounded-md">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="text-sm font-medium text-green-800">Generated Password:</p>
                        <p className="text-sm font-mono text-green-700 mt-1">{generatedPassword}</p>
                      </div>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => navigator.clipboard.writeText(generatedPassword)}
                        className="text-green-700 hover:bg-green-100"
                      >
                        Copy
                      </Button>
                    </div>
                    <p className="text-xs text-green-600 mt-2">
                      Save this password securely. The user can change it after first login.
                    </p>
                  </div>
                )}
              </div>

              <div className="flex flex-col sm:flex-row gap-2 pt-2">
                <Button 
                  type="button"
                  onClick={() => setShowUserDialog(false)}
                  variant="outline" 
                  className="flex-1"
                  size="sm"
                >
                  Cancel
                </Button>
                <Button 
                  type="submit"
                  className="flex-1" 
                  size="sm"
                  disabled={createUserMutation.isPending}
                >
                  {createUserMutation.isPending ? (
                    <>
                      <div className="animate-spin w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full" />
                      Creating...
                    </>
                  ) : (
                    <>
                      <Save className="h-4 w-4 mr-2" />
                      {selectedUser ? "Update User" : "Create User"}
                    </>
                  )}
                </Button>
              </div>
            </form>
          </DialogContent>
        </Dialog>

        {/* Profile Editor Modal */}
        <AdminProfileEditor
          isOpen={showProfileEdit}
          onClose={() => setShowProfileEdit(false)}
          currentUser={currentAdminUser}
        />
      </div>
    </div>
  );
}