import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/hooks/useAuth";
import { apiRequest } from "@/lib/queryClient";
import { useLocation } from "wouter";
import { isUnauthorizedError } from "@/lib/authUtils";
import { UserPlus, Edit, Trash2, ArrowRight, Settings } from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";

const departments = [
  { value: 'engineering', label: 'مهندسی' },
  { value: 'planning', label: 'برنامه‌ریزی' },
  { value: 'commercial', label: 'بازرگانی' },
  { value: 'quality', label: 'تضمین کیفیت' },
  { value: 'financial', label: 'مالی' },
  { value: 'laboratory', label: 'تست آزمایشگاهی' },
  { value: 'warehouse', label: 'انبار' },
  { value: 'admin', label: 'مدیریت' },
];

const userSchema = z.object({
  username: z.string().min(3, "نام کاربری باید حداقل ۳ کاراکتر باشد"),
  fullName: z.string().min(2, "نام و نام خانوادگی الزامی است"),
  department: z.string().min(1, "انتخاب واحد الزامی است"),
  position: z.string().optional(),
  password: z.string().min(6, "رمز عبور باید حداقل ۶ کاراکتر باشد"),
  signatureImage: z.any().optional(),
  signatureImageUrl: z.string().optional(),
});

type UserFormData = z.infer<typeof userSchema>;

interface User {
  id: string;
  username: string;
  fullName: string;
  department: string;
  position?: string;
  isActive: boolean;
  signatureImageUrl?: string;
  departmentAccess?: string[];
  createdAt: string;
}

export default function AdminPanel() {
  const { user, isLoading: authLoading } = useAuth();
  const [, setLocation] = useLocation();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedSignatureFile, setSelectedSignatureFile] = useState<File | null>(null);
  const [signaturePreview, setSignaturePreview] = useState<string | null>(null);
  const [accessManagementUser, setAccessManagementUser] = useState<User | null>(null);
  const [isAccessDialogOpen, setIsAccessDialogOpen] = useState(false);

  // Redirect to login if not authenticated or not admin
  useEffect(() => {
    if (!authLoading && (!user || user.department !== 'admin')) {
      toast({
        title: "دسترسی محدود",
        description: "این بخش فقط برای مدیر سیستم قابل دسترسی است",
        variant: "destructive",
      });
      setLocation("/");
      return;
    }
  }, [user, authLoading, toast, setLocation]);

  // Fetch users
  const { data: users = [], isLoading: usersLoading } = useQuery<User[]>({
    queryKey: ["/api/users"],
    retry: false,
    enabled: user?.department === 'admin',
  });

  // Form for creating/editing users
  const form = useForm<UserFormData>({
    resolver: zodResolver(userSchema),
    defaultValues: {
      username: "",
      fullName: "",
      department: "",
      position: "",
      password: "",
      signatureImage: null,
    },
  });

  // Handle signature file selection
  const handleSignatureFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // Validate file type (only images)
      if (!file.type.startsWith('image/')) {
        toast({
          title: "خطا",
          description: "فقط فایل‌های تصویری مجاز هستند",
          variant: "destructive",
        });
        return;
      }
      
      // Validate file size (max 2MB)
      if (file.size > 2 * 1024 * 1024) {
        toast({
          title: "خطا", 
          description: "حجم فایل نباید بیشتر از ۲ مگابایت باشد",
          variant: "destructive",
        });
        return;
      }
      
      setSelectedSignatureFile(file);
      
      // Create preview
      const reader = new FileReader();
      reader.onload = (e) => {
        setSignaturePreview(e.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  // Upload signature to base64
  const uploadSignatureToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  };

  // Create user mutation
  const createUserMutation = useMutation({
    mutationFn: async (userData: UserFormData) => {
      let signatureImageUrl = null;
      
      // Upload signature if selected
      if (selectedSignatureFile) {
        signatureImageUrl = await uploadSignatureToBase64(selectedSignatureFile);
      }
      
      const finalUserData = {
        ...userData,
        signatureImageUrl,
      };
      
      const response = await apiRequest("POST", "/api/users", finalUserData);
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "موفقیت",
        description: "کاربر جدید با موفقیت ایجاد شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/users"] });
      setIsDialogOpen(false);
      form.reset();
      setSelectedSignatureFile(null);
      setSignaturePreview(null);
    },
    onError: (error) => {
      if (isUnauthorizedError(error)) {
        toast({
          title: "غیرمجاز",
          description: "شما از سیستم خارج شده‌اید. در حال ورود مجدد...",
          variant: "destructive",
        });
        setTimeout(() => {
          window.location.href = "/api/login";
        }, 500);
        return;
      }
      toast({
        title: "خطا",
        description: "خطا در ایجاد کاربر جدید",
        variant: "destructive",
      });
    },
  });

  // Update user mutation
  const updateUserMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: Partial<UserFormData> }) => {
      let finalData = { ...data };
      
      // Upload signature if selected
      if (selectedSignatureFile) {
        const signatureImageUrl = await uploadSignatureToBase64(selectedSignatureFile);
        finalData.signatureImageUrl = signatureImageUrl;
      }
      
      const response = await apiRequest("PUT", `/api/users/${id}`, finalData);
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "موفقیت",
        description: "کاربر با موفقیت ویرایش شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/users"] });
      setIsDialogOpen(false);
      setEditingUser(null);
      form.reset();
      setSelectedSignatureFile(null);
      setSignaturePreview(null);
    },
    onError: (error) => {
      if (isUnauthorizedError(error)) {
        toast({
          title: "غیرمجاز",
          description: "شما از سیستم خارج شده‌اید. در حال ورود مجدد...",
          variant: "destructive",
        });
        setTimeout(() => {
          window.location.href = "/api/login";
        }, 500);
        return;
      }
      toast({
        title: "خطا",
        description: "خطا در ویرایش کاربر",
        variant: "destructive",
      });
    },
  });

  // Delete user mutation
  const deleteUserMutation = useMutation({
    mutationFn: async (id: string) => {
      const response = await apiRequest("DELETE", `/api/users/${id}`, {});
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "موفقیت",
        description: "کاربر با موفقیت حذف شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/users"] });
    },
    onError: (error) => {
      if (isUnauthorizedError(error)) {
        toast({
          title: "غیرمجاز",
          description: "شما از سیستم خارج شده‌اید. در حال ورود مجدد...",
          variant: "destructive",
        });
        setTimeout(() => {
          window.location.href = "/api/login";
        }, 500);
        return;
      }
      toast({
        title: "خطا",
        description: "خطا در حذف کاربر",
        variant: "destructive",
      });
    },
  });

  // Update user access mutation
  const updateUserAccessMutation = useMutation({
    mutationFn: async ({ userId, departmentAccess }: { userId: string; departmentAccess: string[] }) => {
      const response = await apiRequest("PUT", `/api/users/${userId}`, { departmentAccess });
      return response.json();
    },
    onSuccess: () => {
      toast({
        title: "موفقیت",
        description: "دسترسی‌های کاربر با موفقیت به‌روزرسانی شد",
      });
      queryClient.invalidateQueries({ queryKey: ["/api/users"] });
      setIsAccessDialogOpen(false);
      setAccessManagementUser(null);
    },
    onError: (error) => {
      if (isUnauthorizedError(error)) {
        toast({
          title: "غیرمجاز",
          description: "شما از سیستم خارج شده‌اید. در حال ورود مجدد...",
          variant: "destructive",
        });
        setTimeout(() => {
          window.location.href = "/api/login";
        }, 500);
        return;
      }
      toast({
        title: "خطا",
        description: "خطا در به‌روزرسانی دسترسی‌ها",
        variant: "destructive",
      });
    },
  });

  const handleSubmit = (data: UserFormData) => {
    if (editingUser) {
      updateUserMutation.mutate({ id: editingUser.id, data });
    } else {
      createUserMutation.mutate(data);
    }
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    form.setValue("username", user.username);
    form.setValue("fullName", user.fullName);
    form.setValue("department", user.department);
    form.setValue("position", user.position || "");
    form.setValue("password", ""); // Don't pre-fill password
    setIsDialogOpen(true);
  };

  const handleDelete = (userId: string) => {
    if (confirm("آیا از حذف این کاربر اطمینان دارید؟")) {
      deleteUserMutation.mutate(userId);
    }
  };

  const handleNewUser = () => {
    setEditingUser(null);
    form.reset();
    setIsDialogOpen(true);
  };

  const openAccessManagementDialog = (user: User) => {
    setAccessManagementUser(user);
    setIsAccessDialogOpen(true);
  };

  const handleAccessChange = (departmentValue: string, checked: boolean) => {
    if (!accessManagementUser) return;
    
    const currentAccess = accessManagementUser.departmentAccess || [];
    let newAccess;
    
    if (checked) {
      newAccess = [...currentAccess, departmentValue];
    } else {
      newAccess = currentAccess.filter(dept => dept !== departmentValue);
    }
    
    setAccessManagementUser({
      ...accessManagementUser,
      departmentAccess: newAccess
    });
  };

  const saveAccessChanges = () => {
    if (!accessManagementUser) return;
    updateUserAccessMutation.mutate({
      userId: accessManagementUser.id,
      departmentAccess: accessManagementUser.departmentAccess || []
    });
  };

  const getDepartmentName = (dept: string) => {
    const names: Record<string, string> = {
      engineering: 'مهندسی',
      planning: 'برنامه‌ریزی',
      commercial: 'بازرگانی',
      quality: 'تضمین کیفیت',
      financial: 'مالی',
      laboratory: 'تست آزمایشگاهی',
      warehouse: 'انبار',
      admin: 'مدیریت'
    };
    return names[dept] || dept;
  };

  if (authLoading || usersLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
          <p>در حال بارگذاری...</p>
        </div>
      </div>
    );
  }

  if (!user || user.department !== 'admin') {
    return null;
  }

  return (
    <div className="min-h-screen bg-gray-50 page-transition">
      {/* Header */}
      <header className="bg-white shadow-sm border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <h1 className="text-lg font-semibold text-gray-900">مدیریت کاربران</h1>
            <Button
              variant="ghost"
              onClick={() => setLocation("/")}
              className="text-gray-500 hover:text-gray-700"
            >
              <ArrowRight className="w-4 h-4 ml-2" />
              بازگشت به داشبورد
            </Button>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <Card>
          <CardContent className="p-6">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-xl font-bold text-gray-900">لیست کاربران</h2>
              <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogTrigger asChild>
                  <Button onClick={handleNewUser} className="minty-primary border-0 hover:opacity-90 transition-opacity px-4 py-2 rounded-md font-medium">
                    <UserPlus className="w-4 h-4 ml-2" />
                    افزودن کاربر جدید
                  </Button>
                </DialogTrigger>
                <DialogContent className="sm:max-w-md minty-card">
                  <DialogHeader>
                    <DialogTitle className="minty-label text-lg">
                      {editingUser ? "ویرایش کاربر" : "افزودن کاربر جدید"}
                    </DialogTitle>
                  </DialogHeader>
                  <Form {...form}>
                    <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
                      <FormField
                        control={form.control}
                        name="username"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel className="minty-label">نام کاربری</FormLabel>
                            <FormControl>
                              <Input placeholder="نام کاربری" className="minty-input" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      
                      <FormField
                        control={form.control}
                        name="fullName"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel className="minty-label">نام و نام خانوادگی</FormLabel>
                            <FormControl>
                              <Input placeholder="نام و نام خانوادگی" className="minty-input" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      
                      <FormField
                        control={form.control}
                        name="department"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel className="minty-label">واحد</FormLabel>
                            <Select onValueChange={field.onChange} value={field.value}>
                              <FormControl>
                                <SelectTrigger className="minty-input">
                                  <SelectValue placeholder="انتخاب واحد" />
                                </SelectTrigger>
                              </FormControl>
                              <SelectContent>
                                <SelectItem value="engineering">مهندسی</SelectItem>
                                <SelectItem value="planning">برنامه‌ریزی</SelectItem>
                                <SelectItem value="commercial">بازرگانی</SelectItem>
                                <SelectItem value="quality">تضمین کیفیت</SelectItem>
                                <SelectItem value="financial">مالی</SelectItem>
                                <SelectItem value="laboratory">تست آزمایشگاهی</SelectItem>
                                <SelectItem value="warehouse">انبار</SelectItem>
                                <SelectItem value="admin">مدیریت</SelectItem>
                              </SelectContent>
                            </Select>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={form.control}
                        name="position"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel className="minty-label">سمت (اختیاری)</FormLabel>
                            <Select onValueChange={field.onChange} value={field.value}>
                              <FormControl>
                                <SelectTrigger className="minty-input">
                                  <SelectValue placeholder="انتخاب سمت" />
                                </SelectTrigger>
                              </FormControl>
                              <SelectContent>
                                <SelectItem value="مدیر">مدیر</SelectItem>
                                <SelectItem value="سرپرست">سرپرست</SelectItem>
                                <SelectItem value="کارشناس">کارشناس</SelectItem>
                                <SelectItem value="کارشناس ارشد">کارشناس ارشد</SelectItem>
                              </SelectContent>
                            </Select>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      
                      <FormField
                        control={form.control}
                        name="password"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel className="minty-label">
                              {editingUser ? "رمز عبور جدید (اختیاری)" : "رمز عبور"}
                            </FormLabel>
                            <FormControl>
                              <Input 
                                type="password" 
                                placeholder="رمز عبور" 
                                className="minty-input"
                                {...field} 
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      {/* Signature Upload Field */}
                      <div className="space-y-3">
                        <Label htmlFor="signature" className="minty-label">آپلود امضای دیجیتال</Label>
                        <div className="space-y-2">
                          <Input
                            id="signature"
                            type="file"
                            accept="image/*"
                            onChange={handleSignatureFileChange}
                            className="cursor-pointer minty-input"
                          />
                          <p className="text-sm minty-text">
                            فقط فایل‌های تصویری - حداکثر ۲ مگابایت
                          </p>
                          
                          {/* Signature Preview */}
                          {signaturePreview && (
                            <div className="border border-gray-300 rounded-lg p-3 bg-gray-50">
                              <p className="text-sm minty-text mb-2">پیش‌نمایش امضا:</p>
                              <div className="flex justify-center">
                                <img
                                  src={signaturePreview}
                                  alt="پیش‌نمایش امضا"
                                  className="max-h-16 max-w-32 object-contain border border-gray-300 rounded bg-white"
                                />
                              </div>
                            </div>
                          )}
                          
                          {/* Show existing signature for editing */}
                          {editingUser?.signatureImageUrl && !signaturePreview && (
                            <div className="border border-gray-300 rounded-lg p-3 bg-gray-50">
                              <p className="text-sm minty-text mb-2">امضای موجود:</p>
                              <div className="flex justify-center">
                                <img
                                  src={editingUser.signatureImageUrl}
                                  alt="امضای موجود"
                                  className="max-h-16 max-w-32 object-contain border border-gray-300 rounded bg-white"
                                />
                              </div>
                              <p className="text-xs text-orange-600 mt-2 text-center">
                                ⚠️ امضا پس از ذخیره غیرقابل حذف است
                              </p>
                            </div>
                          )}
                        </div>
                      </div>
                      
                      <div className="flex justify-end space-x-3 space-x-reverse pt-4">
                        <Button
                          type="button"
                          variant="outline"
                          onClick={() => setIsDialogOpen(false)}
                          className="border-gray-300 text-gray-700 hover:bg-gray-50"
                        >
                          لغو
                        </Button>
                        <Button
                          type="submit"
                          disabled={createUserMutation.isPending || updateUserMutation.isPending}
                          className="minty-primary border-0 hover:opacity-90 transition-opacity px-4 py-2 rounded-md font-medium"
                        >
                          {editingUser ? "ویرایش" : "ایجاد"}
                        </Button>
                      </div>
                    </form>
                  </Form>
                </DialogContent>
              </Dialog>
            </div>
            
            {/* Users Table */}
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      نام کاربری
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      نام و نام خانوادگی
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      واحد
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      سمت
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      مدیریت دسترسی
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      امضا
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      وضعیت
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      عملیات
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {users.map((user: User) => (
                    <tr key={user.id}>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                        {user.username}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {user.fullName}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {getDepartmentName(user.department)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {user.position || "-"}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-center">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => openAccessManagementDialog(user)}
                          className="text-xs"
                        >
                          <Settings className="w-3 h-3 ml-1" />
                          مدیریت دسترسی
                        </Button>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-center">
                        {user.signatureImageUrl ? (
                          <div className="flex justify-center">
                            <img
                              src={user.signatureImageUrl}
                              alt="امضای دیجیتال"
                              className="h-8 w-auto max-w-16 object-contain border border-gray-300 rounded bg-white"
                            />
                          </div>
                        ) : (
                          <span className="text-gray-400 text-xs">بدون امضا</span>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <Badge variant={user.isActive ? "default" : "secondary"}>
                          {user.isActive ? "فعال" : "غیرفعال"}
                        </Badge>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <div className="flex space-x-2 space-x-reverse">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleEdit(user)}
                            className="text-primary hover:text-blue-700"
                          >
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDelete(user.id)}
                            className="text-red-600 hover:text-red-700"
                            disabled={deleteUserMutation.isPending}
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            
            {users.length === 0 && (
              <div className="text-center py-8">
                <p className="text-gray-500">هیچ کاربری یافت نشد</p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Access Management Dialog */}
        <Dialog open={isAccessDialogOpen} onOpenChange={setIsAccessDialogOpen}>
          <DialogContent className="sm:max-w-lg">
            <DialogHeader>
              <DialogTitle>مدیریت دسترسی کاربر</DialogTitle>
            </DialogHeader>
            
            {accessManagementUser && (
              <div className="space-y-4">
                <div className="text-sm text-gray-600">
                  <strong>کاربر:</strong> {accessManagementUser.fullName} ({accessManagementUser.username})
                </div>
                
                <div className="space-y-3">
                  <Label className="text-base font-medium">انتخاب واحدهای قابل دسترسی:</Label>
                  <div className="grid grid-cols-2 gap-3">
                    {departments.map((dept) => (
                      <div key={dept.value} className="flex items-center space-x-2 space-x-reverse">
                        <Checkbox
                          id={dept.value}
                          checked={(accessManagementUser.departmentAccess || []).includes(dept.value)}
                          onCheckedChange={(checked) => handleAccessChange(dept.value, checked as boolean)}
                        />
                        <Label htmlFor={dept.value} className="text-sm cursor-pointer">
                          {dept.label}
                        </Label>
                      </div>
                    ))}
                  </div>
                </div>
                
                {accessManagementUser.departmentAccess && accessManagementUser.departmentAccess.length > 0 && (
                  <div className="bg-blue-50 p-3 rounded-lg">
                    <h4 className="text-sm font-medium text-blue-800 mb-2">واحدهای انتخاب شده:</h4>
                    <div className="flex flex-wrap gap-2">
                      {accessManagementUser.departmentAccess.map((deptValue) => {
                        const dept = departments.find(d => d.value === deptValue);
                        return (
                          <Badge key={deptValue} variant="secondary" className="text-xs">
                            {dept?.label || deptValue}
                          </Badge>
                        );
                      })}
                    </div>
                  </div>
                )}
                
                <div className="flex justify-end space-x-3 space-x-reverse pt-4">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setIsAccessDialogOpen(false)}
                  >
                    لغو
                  </Button>
                  <Button
                    onClick={saveAccessChanges}
                    disabled={updateUserAccessMutation.isPending}
                  >
                    {updateUserAccessMutation.isPending ? "در حال ذخیره..." : "ذخیره تغییرات"}
                  </Button>
                </div>
              </div>
            )}
          </DialogContent>
        </Dialog>
      </main>
    </div>
  );
}
