"use client"

import { useState, useEffect } from "react"
import { router } from "@inertiajs/react"
import AppLayout from "@/Layouts/AppLayout"
import DataTable from "@/Components/DataTable"
import { Modal } from "@/Components/UI/Modal"
import { Button } from "@/Components/UI/Button"
import { Input } from "@/Components/UI/Input"
import { Label } from "@/Components/UI/Label"
import DeleteModal from "@/Components/DeleteModal"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/Components/UI/Tabs"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/UI/Select"
import { Checkbox } from "@/Components/UI/Checkbox"
import { Card } from "@/Components/UI/Card"
import FileUpload from "@/Components/UI/FileUpload"
import { Plus, LogIn, Eye, Trash2, Users, Settings, Edit, Shield, Lock, Globe, FileText, Bell, Database, Key, Monitor, Layers } from "lucide-react" 
import { useDeleteHandler } from '@/hooks/useDeleteHandler';
import { useToggleHandler } from '@/hooks/useToggleHandler';
import { useBulkHandler } from '@/hooks/useBulkHandler';
import { Avatar, AvatarFallback, AvatarImage } from "@/Components/UI/Avatar"
import useTranslate from "@/hooks/useTranslate";
import { route } from "ziggy-js"
import { motion, AnimatePresence } from "framer-motion";


export default function AccessControlPage({ users, roles, allRoles, statusEnum, rolePermissions }) {
  const t = useTranslate();
  const [userList, setUserList] = useState(users.data || [])
  const [searchQueryUsers, setSearchQueryUsers] = useState("");
  const [statusFilterUsers, setStatusFilterUsers] = useState("all");
  const [userToDelete, setUserToDelete] = useState(null)
  const [isDeleteUserModalOpen, setIsDeleteUserModalOpen] = useState(false)
  const [userToShow, setUserToShow] = useState(null)
  const [isShowUserModalOpen, setIsShowUserModalOpen] = useState(false)



  const [roleList, setRoleList] = useState(roles.data || [])
  const [searchQueryRoles, setSearchQueryRoles] = useState("");
  const [statusFilterRoles, setStatusFilterRoles] = useState("all");
  const [roleToDelete, setRoleToDelete] = useState(null)
  const [isDeleteRoleModalOpen, setIsDeleteRoleModalOpen] = useState(false)

  const [isCreateUserModalOpen, setIsCreateUserModalOpen] = useState(false)
  const [isCreateRoleModalOpen, setIsCreateRoleModalOpen] = useState(false)
  const [isEditUserModalOpen, setIsEditUserModalOpen] = useState(false)
  const [isEditRoleModalOpen, setIsEditRoleModalOpen] = useState(false)
  const [userToEdit, setUserToEdit] = useState(null)
  const [roleToEdit, setRoleToEdit] = useState(null)

  const [activeTab, setActiveTab] = useState("users")
  const [newUserData, setNewUserData] = useState({
    name: "",
    email: "",
    status: "",
    role_id: "0",
    profile_image: null,
    password: "",
    password_confirmation: "",
  })
  const [editUserData, setEditUserData] = useState({
    id: "",
    name: "",
    email: "",
    status: "",
    role_id: "0",
    profile_image: null,
  })
  const [newRoleData, setNewRoleData] = useState({
    name: "",
    description: "",
  })
  const [editRoleData, setEditRoleData] = useState({
    id: "",
    name: "",
    permissions: {},
  })

  const breadcrumbs = [{ label: t("Home"), href: route("user.home") }, { label: t("Access Control") }]

  // User table configuration
  const userColumns = [
    {
      key: "id",
      label: "No",
      className: "w-16",
      cellClassName: "font-medium",
      render: (_item, index) => index + 1,
    },
    {
      key: "name",
      label: "Name",
      render: (user) => (
        <div className="flex items-center space-x-3">

          <Avatar className="h-8 w-8 bg-gradient-to-br from-primary/20 to-secondary/20 border border-gray-200 dark:border-gray-600">
            <AvatarImage src={user.avatar_url} alt={user.name} />
            <AvatarFallback className="bg-gradient-to-br from-primary to-secondary text-white font-semibold text-sm">
              {user.name?.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2) || 'U'}
            </AvatarFallback>
          </Avatar>
          <span className="font-medium">{user.name}</span>
        </div>
      ),
    },
    {
      key: "status",
      label: "Status",
      render: (user) => (
        <div className="flex w-full items-center gap-3">
          {/* Status Badge */}
          <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${
            user.status === '1' 
              ? 'bg-green-50 text-green-700 border border-green-200 dark:bg-green-900/20 dark:text-green-400 dark:border-green-800' 
              : 'bg-red-50 text-red-700 border border-red-200 dark:bg-red-900/20 dark:text-red-400 dark:border-red-800'
          }`}>
            <div className={`w-2 h-2 rounded-full ${
              user.status === '1' ? 'bg-green-500' : 'bg-red-500'
            }`} />
            {user.status === '1' ? 'Active' : 'Inactive'}
          </span>
          {/* Toggle switch for user status */}
          <button
            className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${
              user.status === '1' 
                ? "bg-gradient-to-r from-green-500 to-green-600" 
                : "bg-gray-300 dark:bg-gray-600"
            }`}
            onClick={() => handleToggleUserStatus(user.id)}
          >
            <span
              className={`inline-block h-3 w-3 transform rounded-full bg-white transition-transform shadow-sm ${
                user.status === '1' ? "translate-x-5" : "translate-x-1"
              }`}
            />
          </button>
        </div>
      ),
    },
    {
      key: "email",
      label: "Email",
      render: (user) => (
        <div className="space-y-1">
          <span className="text-gray-900 dark:text-gray-200 text-sm font-medium">{user.email}</span>
          <div className="text-xs text-gray-500 dark:text-gray-400">Member since {new Date(user.created_at).toLocaleDateString()}</div>
        </div>
      ),
    },
    {
      key: "role",
      label: "Role & Permissions",
      render: (user) => (
        <div className="space-y-1">
          <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs font-medium bg-blue-50 text-blue-700 border border-blue-200 dark:bg-blue-900/20 dark:text-blue-400 dark:border-blue-800">
            <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clipRule="evenodd" />
            </svg>
            {user.role ? user.role.name : 'supperadmin'}
          </span>
          <div className="text-xs text-gray-500 dark:text-gray-400">
            {user.role ? (user.role.permissions_count || Object.keys(user.role.permissions || {}).reduce((total, category) => total + (user.role.permissions[category]?.length || 0), 0) || 0) : 'All'} permissions
          </div>
        </div>
      ),
    },
  ]

  // Role table configuration
  const roleColumns = [
    {
      key: "id",
      label: "No",
      className: "w-16",
      cellClassName: "font-medium",
      render: (_item, index) => index + 1,
    },
    {
      key: "name",
      label: "Role Name",
      render: (role) => <span className="font-medium">{role.name}</span>,
    },
    {
      key: "status",
      label: "Status",
      render: (role) => (
        <div className="flex w-full items-center gap-3">
          {/* Status Badge */}
          <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${
            role.status === '1' 
              ? 'bg-green-50 text-green-700 border border-green-200 dark:bg-green-900/20 dark:text-green-400 dark:border-green-800' 
              : 'bg-red-50 text-red-700 border border-red-200 dark:bg-red-900/20 dark:text-red-400 dark:border-red-800'
          }`}>
            <div className={`w-2 h-2 rounded-full ${
              role.status === '1' ? 'bg-green-500' : 'bg-red-500'
            }`} />
            {role.status === '1' ? 'Active' : 'Inactive'}
          </span>
          {/* Toggle switch */}
          <button
            className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${
              role.status === '1' 
                ? "bg-gradient-to-r from-green-500 to-green-600" 
                : "bg-gray-300 dark:bg-gray-600"
            }`}
            onClick={() => handleToggleRoleStatus(role.id)}
          >
            <span
              className={`inline-block h-3 w-3 transform rounded-full bg-white transition-transform shadow-sm ${
                role.status === '1' ? "translate-x-5" : "translate-x-1"
              }`}
            />
          </button>
        </div>
      ),
    },
    {
      key: "created_by",
      label: "Created By & Date",
      render: (role) => (
        <div className="space-y-1">
          <div className="flex items-center gap-2">
            <Avatar className="h-6 w-6 bg-gradient-to-br from-primary/20 to-secondary/20">
              <AvatarImage src={role.created_by?.avatar_url} alt={role.created_by?.name} />
              <AvatarFallback className="bg-gradient-to-br from-primary to-secondary text-white font-semibold text-xs">
                {role.created_by?.name?.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2) || 'S'}
              </AvatarFallback>
            </Avatar>
            <span className="text-gray-900 dark:text-gray-200 text-sm font-medium">
              {role.created_by?.name || 'System'}
            </span>
          </div>
          <div className="text-xs text-gray-500 dark:text-gray-400">
            {new Date(role.created_at).toLocaleDateString()}
          </div>
        </div>
      ),
    },
    {
      key: "permissions",
      label: "Permissions",
      render: (role) => (
        <div className="space-y-1">
          <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs font-medium bg-purple-50 text-purple-700 border border-purple-200 dark:bg-purple-900/20 dark:text-purple-400 dark:border-purple-800">
            <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clipRule="evenodd" />
            </svg>
            {role.permissions_count || Object.keys(role.permissions || {}).reduce((total, category) => total + (role.permissions[category]?.length || 0), 0) || 0} permissions
          </span>
          <div className="text-xs text-gray-500 dark:text-gray-400">
            {role.description || 'No description'}
          </div>
        </div>
      ),
    },
  ]

  const userActionMenuItems = [
    { key: "login", label: "Login", icon: LogIn, },
    { key: "edit", label: "Edit", icon: Edit, },
    { key: "show", label: "Show", icon: Eye, },
    { key: "delete", label: "Delete", icon: Trash2, className: "text-red-600 hover:text-red-700", },
  ]

  const roleActionMenuItems = [
    { key: "edit", label: "Edit", icon: Eye, },
    { key: "delete", label: "Delete", icon: Trash2, className: "text-red-600 hover:text-red-700", },
  ]

  const userFilterOptions = [
    { label: "Active", value: "1" },
    { label: "Inactive", value: "0" },
  ]

  const roleFilterOptions = [
    { label: "Active", value: "1" },
    { label: "Inactive", value: "0" },
  ]



  //User
  const handleSearchUsers = (value) => {
    setSearchQueryUsers(value);
    router.get(route("user.access-control.index"), {
      key: "user-search",
      search: value,
      status: statusFilterUsers !== "all" ? statusFilterUsers : undefined,
      page: 1,
    }, { preserveState: true, replace: true });
  };

  const handleFilterUsers = (value) => {
    setStatusFilterUsers(value);
    router.get(route("user.access-control.index"), {
      key: "user-search",
      search: searchQueryUsers,
      status: value !== "all" ? value : undefined,
      page: 1,
    }, { preserveState: true, replace: true });
  };


  const { handleToggle: handleUserToggle, isToggling: isToggleingUser } = useToggleHandler(
    "user.access-control.status.update",
    (id, newStatus) => {
      setUserList((prev) =>
        prev.map((user) =>
          user.id === id ? { ...user, status: newStatus } : user
        )
      );
    }
  );

  const handleToggleUserStatus = (userId) => {
    const user = userList.find((u) => u.id === userId);
    if (user) {
      handleUserToggle(userId, String(user.status));
    }
  };


  const { handleDelete: handleUserDelete, isDeleting: isUserDeleting } = useDeleteHandler('user.access-control.delete', (deletedId) => {
    setUserList((prev) => prev.filter((u) => u.id !== deletedId));
    setIsDeleteUserModalOpen(false);
    setUserToDelete(null);
  });

  const { handleBulkAction: handleUserBulkAction, isBulkProcessing: isUserBulkProcessing } = useBulkHandler(
    "user.access-control.bulk",
    (action, ids, statusEnum) => {
      setUserList((prev) => {
        switch (action) {
          case "active":
            return prev.map((u) =>
              ids.includes(u.id) ? { ...u, status: statusEnum.Active } : u
            )
          case "inactive":
            return prev.map((u) =>
              ids.includes(u.id) ? { ...u, status: statusEnum.Inactive } : u
            )
          case "delete":
            return prev.filter((u) => !ids.includes(u.id))
          default:
            return prev
        }
      })
    }
  )




  const handleUserRowAction = (action, user) => {

    switch (action) {

      case 'login': handleLoginAsUser(user.id); break;
      case 'edit': handleEditUser(user); break;
      case 'show': handleShowUser(user); break;
      case 'delete': handleDeleteUserClick(user); break;
    }
  };

  const handleLoginAsUser = (userId) => {
    router.post(route("user.access-control.login"), {
      id: userId
    })
  }

  const handleShowUser = (user) => {
    setUserToShow(user)
    setIsShowUserModalOpen(true)
  }

  const handleEditUser = (user) => {
    setUserToEdit(user)
    setEditUserData({
      id: user.id,
      name: user.name,
      email: user.email,
      status: user.status,
      role_id: user.role && user.role.id ? user.role.id.toString() : "0",
      profile_image: null,
    })
    setIsEditUserModalOpen(true)
  }

  const handleDeleteUserClick = (user) => {
    setUserToDelete(user)
    setIsDeleteUserModalOpen(true)
  }

  const handleCreateUser = () => {
    const formData = new FormData()
    formData.append("name", newUserData.name)
    formData.append("email", newUserData.email)
    formData.append("status", newUserData.status)
    formData.append("role_id", newUserData.role_id)
    formData.append("password", newUserData.password)
    formData.append("password_confirmation", newUserData.password_confirmation)
    if (newUserData.profile_image) {
      formData.append("profile_image", newUserData.profile_image)
    }

    router.post(route("user.access-control.store"), formData, {
      onSuccess: () => {
        setIsCreateUserModalOpen(false)
        setNewUserData({
          name: "",
          email: "",
          status: "",
          role_id: "0",
          profile_image: null,
          password: "",
          password_confirmation: "",
        })
      },
    })
  }

  const handleUpdateUser = () => {
    const formData = new FormData()
    formData.append("id", editUserData.id)
    formData.append("name", editUserData.name)
    formData.append("email", editUserData.email)
    formData.append("status", editUserData.status)
    formData.append("role_id", editUserData.role_id)
    if (editUserData.profile_image) {
      formData.append("profile_image", editUserData.profile_image)
    }

    router.post(route("user.access-control.update"), formData, {
      onSuccess: () => {
        setIsEditUserModalOpen(false)
        setEditUserData({
          id: "",
          name: "",
          email: "",
          status: "",
          role_id: "0",
          profile_image: null,
        })
        setUserToEdit(null)
      },
    })
  }

  const handleNewUserInputChange = (e) => {
    const { name, value } = e.target
    setNewUserData((prev) => ({
      ...prev,
      [name]: value,
    }))
  }

  const handleEditUserInputChange = (e) => {
    const { name, value } = e.target
    setEditUserData((prev) => ({
      ...prev,
      [name]: value,
    }))
  }

  //Roles
  const handleSearchRoles = (value) => {
    setSearchQueryRoles(value);
    router.get(route("user.access-control.index"), {
      key: "role-search",
      search: value,
      status: statusFilterRoles !== "all" ? statusFilterRoles : undefined,
      page: 1,
    }, { preserveState: true, replace: true });
  };

  const handleFilterRoles = (value) => {
    setStatusFilterRoles(value);
    router.get(route("user.access-control.index"), {
      key: "role-search",
      search: searchQueryRoles,
      status: value !== "all" ? value : undefined,
      page: 1,
    }, { preserveState: true, replace: true });
  };

  const { handleToggle: handleRoleToggle, isToggling: isTogglingRole } = useToggleHandler(
    "user.role.status.update",
    (id, newStatus) => {
      setRoleList((prev) =>
        prev.map((role) =>
          role.id === id ? { ...role, status: newStatus } : role
        )
      );
    }
  );

  const handleToggleRoleStatus = (roleId) => {
    const role = roleList.find((r) => r.id === roleId);
    if (role) {
      handleRoleToggle(roleId, String(role.status));
    }
  };

  const { handleDelete: handleRoleDelete, isDeleting: isRoleDeleting } = useDeleteHandler('user.role.delete', (deletedId) => {
    setRoleList((prev) => prev.filter((r) => r.id !== deletedId));
    setIsDeleteRoleModalOpen(false);
    setRoleToDelete(null);
  });

  const { handleBulkAction: handleRoleBulkAction, isBulkProcessing: isRoleBulkProcessing } = useBulkHandler(
    "user.role.bulk",
    (action, ids, statusEnum) => {
      setUserList((prev) => {
        switch (action) {
          case "active":
            return prev.map((r) =>
              ids.includes(r.id) ? { ...r, status: statusEnum.Active } : r
            )
          case "inactive":
            return prev.map((r) =>
              ids.includes(r.id) ? { ...r, status: statusEnum.Inactive } : r
            )
          case "delete":
            return prev.filter((r) => !ids.includes(r.id))
          default:
            return prev
        }
      })
    }
  )

  const handleRoleRowAction = (action, role) => {
    switch (action) {
      case 'edit': handleEditRole(role.id); break;
      case 'delete': handleDeleteRoleClick(role); break;
    }
  };

  // Helper function to convert flat permissions array to categorized structure
  const convertPermissionsToCategories = (flatPermissions) => {
    if (!flatPermissions || !Array.isArray(flatPermissions)) return {}

    const categorizedPermissions = {}

    // Initialize all categories as empty arrays
    if (rolePermissions) {
      Object.keys(rolePermissions).forEach(category => {
        categorizedPermissions[category] = []
      })
    }

    // Categorize each permission
    flatPermissions.forEach(permission => {
      if (rolePermissions) {
        Object.entries(rolePermissions).forEach(([category, permissions]) => {
          if (permissions.includes(permission)) {
            categorizedPermissions[category].push(permission)
          }
        })
      }
    })

    return categorizedPermissions
  }

  const handleEditRole = (roleId) => {
    const role = roleList.find(r => r.id === roleId)
    if (role) {
      setRoleToEdit(role)
      setEditRoleData({
        id: role.id,
        name: role.name,
        permissions: convertPermissionsToCategories(role.permissions),
      })
      setIsEditRoleModalOpen(true)
    }
  }

  const handleDeleteRoleClick = (role) => {
    setRoleToDelete(role)
    setIsDeleteRoleModalOpen(true)
  }

  const handleCreateRole = () => {
    router.post(route("user.role.store"), newRoleData, {
      onSuccess: () => {
        setIsCreateRoleModalOpen(false)
        setNewRoleData({ name: "", description: "" })
      },
    })
  }

  // Helper function to convert categorized permissions back to flat array
  const convertCategoriesToFlat = (categorizedPermissions) => {
    const flatPermissions = []

    Object.values(categorizedPermissions).forEach(categoryPermissions => {
      if (Array.isArray(categoryPermissions)) {
        flatPermissions.push(...categoryPermissions)
      }
    })

    return flatPermissions
  }

  const handleUpdateRole = () => {
    const dataToSend = {
      ...editRoleData,
      permissions: convertCategoriesToFlat(editRoleData.permissions)
    }

    router.post(route("user.role.update"), dataToSend, {
      onSuccess: () => {
        setIsEditRoleModalOpen(false)
        setEditRoleData({ id: "", name: "", permissions: {} })
        setRoleToEdit(null)
      },
    })
  }

  const handleRolePermissionChange = (category, permission, checked) => {
    setEditRoleData((prev) => ({
      ...prev,
      permissions: {
        ...prev.permissions,
        [category]: checked
          ? [...(prev.permissions[category] || []), permission]
          : (prev.permissions[category] || []).filter((p) => p !== permission),
      },
    }))
  }

  const handleRoleCategoryToggle = (category, checked) => {
    if (!rolePermissions || !rolePermissions[category]) return

    setEditRoleData((prev) => ({
      ...prev,
      permissions: {
        ...prev.permissions,
        [category]: checked ? rolePermissions[category] : [],
      },
    }))
  }

  const isRolePermissionChecked = (category, permission) => {
    return (editRoleData.permissions[category] || []).includes(permission)
  }

  const isRoleCategoryChecked = (category) => {
    if (!rolePermissions || !rolePermissions[category]) return false
    const categoryPermissions = rolePermissions[category] || []
    const selectedPermissions = editRoleData.permissions[category] || []
    return categoryPermissions.length > 0 && categoryPermissions.length === selectedPermissions.length
  }

  const isRoleCategoryIndeterminate = (category) => {
    if (!rolePermissions || !rolePermissions[category]) return false
    const categoryPermissions = rolePermissions[category] || []
    const selectedPermissions = editRoleData.permissions[category] || []
    return selectedPermissions.length > 0 && selectedPermissions.length < categoryPermissions.length
  }

  // Check if all permissions across all categories are selected
  const isAllPermissionsChecked = () => {
    if (!rolePermissions) return false

    return Object.entries(rolePermissions).every(([category, permissions]) => {
      const selectedPermissions = editRoleData.permissions[category] || []
      return permissions.length > 0 && selectedPermissions.length === permissions.length
    })
  }

  // Check if some but not all permissions are selected
  const isAllPermissionsIndeterminate = () => {
    if (!rolePermissions) return false

    let hasSelected = false
    let hasUnselected = false

    Object.entries(rolePermissions).forEach(([category, permissions]) => {
      const selectedPermissions = editRoleData.permissions[category] || []
      if (selectedPermissions.length > 0) hasSelected = true
      if (selectedPermissions.length < permissions.length) hasUnselected = true
    })

    return hasSelected && hasUnselected
  }

  // Toggle all permissions across all categories
  const handleAllPermissionsToggle = (checked) => {
    if (!rolePermissions) return

    const newPermissions = {}

    Object.entries(rolePermissions).forEach(([category, permissions]) => {
      newPermissions[category] = checked ? [...permissions] : []
    })

    setEditRoleData((prev) => ({
      ...prev,
      permissions: newPermissions
    }))
  }

  const formatPermissionName = (permission) => {
    return permission
      .split("_")
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(" ")
  }

  const formatCategoryName = (category) => {
    return category
      .split("_")
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(" ")
  }

  const getCategoryIcon = (category) => {
    const icons = {
      language: Globe,
      staff: Users,
      social_account: Layers,
      social_post: FileText,
      user: Users,
      role: Shield,
      category: Database,
      ai_template: Monitor,
      content: FileText,
      security_settings: Lock,
      platform: Globe,
      gateway: Key,
      notification_template: Bell,
      notification: Bell,
      settings: Settings,
      dashboard: Monitor
    }
    return icons[category] || Shield
  }


  const handleCreateButtonClick = () => {
    if (activeTab === "users") {
      setIsCreateUserModalOpen(true)
    } else {
      setIsCreateRoleModalOpen(true)
    }
  }

  useEffect(() => {
    setUserList(users.data || [])
  }, [users])

  useEffect(() => {
    setRoleList(roles.data || [])
  }, [roles])



  return (
    <AppLayout breadcrumbs={breadcrumbs}>
      <div className="flex-1 p-6 overflow-auto bg-gray-50 dark:bg-black">
        {/* Header */}
        <div className="mb-6">
          <div className="flex items-center gap-3 mb-2">
            <div>
              <Users className="h-6 w-6 text-primary" />
            </div>
            <h1 className="text-xl sm:text-2xl dark:text-gray-200 font-bold">
              {t("Access Control")}
            </h1>
          </div>
          <p className="text-gray-500 dark:text-gray-200">
            {t("Manage users, roles, and permissions across your organization")}
          </p>
        </div>

        {/* Campaign-style Tabs */}
        <Tabs defaultValue="users" onValueChange={setActiveTab} className="space-y-6">
          <div className="flex justify-between items-center mb-6">
            <div className="flex gap-1">
              <TabsList className="inline-flex bg-white dark:bg-zinc-900 rounded-lg p-1 shadow-sm gap-1">
                <TabsTrigger
                  value="users"
                  className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-4 py-2 text-sm font-medium transition-colors flex items-center gap-2"
                >
                  <Users className="w-4 h-4" />
                  Users
                  <span className="bg-white/20 text-current text-xs px-2 py-0.5 rounded-full">
                    {userList.length}
                  </span>
                </TabsTrigger>
                <TabsTrigger
                  value="roles"
                  className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-4 py-2 text-sm font-medium transition-colors flex items-center gap-2"
                >
                  <Settings className="w-4 h-4" />
                  Roles
                  <span className="bg-white/20 text-current text-xs px-2 py-0.5 rounded-full">
                    {roleList.length}
                  </span>
                </TabsTrigger>
              </TabsList>
            </div>
          </div>

          {/* Users Tab */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}>
            <TabsContent value="users">
              <DataTable
                data={userList}
                propName="users"
                paginationData={users}
                columns={userColumns}
                searchFields={["name", "email"]}
                searchPlaceholder={t("Search by name or email")}
                filterOptions={userFilterOptions}
                actionMenuItems={userActionMenuItems}
                onSearch={handleSearchUsers}
                onFilterChange={handleFilterUsers}
                onBulkActive={(ids) => handleUserBulkAction("active", ids)}
                onBulkInactive={(ids) => handleUserBulkAction("inactive", ids)}
                onBulkDelete={(ids) => handleUserBulkAction("delete", ids)}
                onRowAction={handleUserRowAction}
                actionButton={
                  <Button
                    onClick={() => setIsCreateUserModalOpen(true)}
                    className="bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary shadow-md hover:shadow-lg transition-all duration-200"
                    size="sm"
                  >
                    <Plus className="h-4 w-4 mr-2" />
                    {t("Add User")}
                  </Button>
                }
              />
            </TabsContent>
          </motion.div>
          {/* Roles Tab */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}>
            <TabsContent value="roles">
              <DataTable
                data={roleList}
                propName="roles"
                paginationData={roles}
                columns={roleColumns}
                searchFields={["name", "description"]}
                searchPlaceholder={t("Search by name")}
                filterOptions={roleFilterOptions}
                actionMenuItems={roleActionMenuItems}
                onSearch={handleSearchRoles}
                onFilterChange={handleFilterRoles}
                onBulkActive={(ids) => handleRoleBulkAction("active", ids)}
                onBulkInactive={(ids) => handleRoleBulkAction("inactive", ids)}
                onBulkDelete={(ids) => handleRoleBulkAction("delete", ids)}
                onRowAction={handleRoleRowAction}
                actionButton={
                  <Button
                    onClick={() => setIsCreateRoleModalOpen(true)}
                    className="bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary shadow-md hover:shadow-lg transition-all duration-200"
                    size="sm"
                  >
                    <Plus className="h-4 w-4 mr-2" />
                    {t("Create Role")}
                  </Button>
                }
              />
            </TabsContent>
          </motion.div>
        </Tabs>

        {/* Create User Modal */}
        <Modal
          isOpen={isCreateUserModalOpen}
          onClose={() => setIsCreateUserModalOpen(false)}
          title={
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 bg-gradient-to-r from-primary to-secondary rounded-lg flex items-center justify-center">
                <Plus className="w-4 h-4 text-white" />
              </div>
              <div>
                <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">{t("Add User")}</h2>
              </div>
            </div>
          }
          onSubmit={handleCreateUser}
          submitText={t("Add User")}
        >
          <div className="space-y-4">
            <p className="text-sm text-gray-500 dark:text-gray-400 text-start">
              {t("Create a new user account with appropriate permissions")}
            </p>
          </div>

          <div className="space-y-4">

            {/* Form */}
            <div className="grid lg:grid-cols-2 grid-cols-1 gap-4">
              <div className="space-y-2">
                <Label htmlFor="name" className="dark:text-neutral-200">{t("Name")}</Label>
                <Input
                  id="name"
                  placeholder={t("Enter name")}
                  value={newUserData.name}
                  onChange={(e) => setNewUserData((prev) => ({ ...prev, name: e.target.value }))}
                />
                <p className="text-xs text-gray-500 dark:text-gray-400">{t("Enter the full name of the user")}.</p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="email" className="dark:text-neutral-200">{t("Email")}</Label>
                <Input
                  id="email"
                  type="email"
                  placeholder={t("Enter email")}
                  value={newUserData.email}
                  onChange={(e) => setNewUserData((prev) => ({ ...prev, email: e.target.value }))}
                />
                <p className="text-xs text-gray-500 dark:text-gray-400">{t("Enter a valid email address")}.</p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="status" className="dark:text-neutral-200">{t("Status")}</Label>
                <Select
                  value={newUserData.status}
                  onValueChange={(value) => setNewUserData((prev) => ({ ...prev, status: value }))}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder={t("Status")} />
                  </SelectTrigger>
                  <SelectContent>
                    {Object.entries(statusEnum).map(([label, value]) => (
                      <SelectItem key={value} value={value}>
                        {label}
                      </SelectItem>
                    ))}

                  </SelectContent>
                </Select>
                <p className="text-xs text-gray-500 dark:text-gray-400">{t("Select the user's account status")}.</p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="role" className="dark:text-neutral-200">{t("Role")}</Label>
                <Select
                  value={newUserData.role_id}
                  onValueChange={(value) => setNewUserData((prev) => ({ ...prev, role_id: value }))}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder={t("Select Role")} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="0">{t("No Role Assigned")}</SelectItem>
                    {allRoles && allRoles.map((role) => (
                      <SelectItem key={role.id} value={role.id.toString()}>
                        {role.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <p className="text-xs text-gray-500 dark:text-gray-400">{t("Assign a role to define user permissions")}.</p>
              </div>

              <div className="col-span-full">
                <FileUpload
                  label={t("Profile Image")}
                  value={newUserData.profile_image}
                  onChange={(file) => setNewUserData((prev) => ({ ...prev, profile_image: file }))}
                  accept="image/*"
                  helperText={t("Upload a profile picture (optional)")}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="password" className="dark:text-neutral-200">{t("Password")}</Label>
                <Input
                  id="password"
                  type="password"
                  placeholder={t("Enter password")}
                  value={newUserData.password}
                  onChange={(e) => setNewUserData((prev) => ({ ...prev, password: e.target.value }))}
                />
                <p className="text-xs text-gray-500 dark:text-gray-400">{t("Enter a secure password for the user")}.</p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="password_confirmation" className="dark:text-neutral-200">{t("Confirm Password")}</Label>
                <Input
                  id="password_confirmation"
                  type="password"
                  placeholder={t("Confirm password")}
                  value={newUserData.password_confirmation}
                  onChange={(e) => setNewUserData((prev) => ({ ...prev, password_confirmation: e.target.value }))}
                />
                <p className="text-xs text-gray-500 dark:text-gray-400">{t("Re-enter the password to confirm")}.</p>
              </div>
            </div>
          </div>
        </Modal>

        {/* Show User Modal */}
        <Modal
          isOpen={isShowUserModalOpen}
          onClose={() => setIsShowUserModalOpen(false)}
          title="User Information"
          showSubmit={false}
        >
          <div className="space-y-4">
            {/* User Avatar */}
            <div className="flex items-center gap-4">
              <Avatar className="h-12 w-12 bg-gradient-to-br from-primary/20 to-secondary/20 border border-gray-200 dark:border-gray-600">
                <AvatarImage src={userToShow?.avatar_url} alt={userToShow?.name} />
                <AvatarFallback className="bg-gradient-to-br from-primary to-secondary text-white font-semibold text-lg">
                  {userToShow?.name?.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2) || 'U'}
                </AvatarFallback>
              </Avatar>
              <div>
                <h2 className="text-lg font-semibold dark:text-gray-200">{userToShow?.name}</h2>
              </div>
            </div>

            {/* User Details */}
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <p className="text-gray-500 dark:text-gray-400">Email</p>
                <p className="font-medium dark:text-gray-200">{userToShow?.email}</p>
              </div>
              <div>
                <p className="text-gray-500 dark:text-gray-400">Phone</p>
                <p className="font-medium dark:text-gray-200">{userToShow?.phone ?? "-"}</p>
              </div>
              <div>
                <p className="text-gray-500 dark:text-gray-400">Joined</p>
                <p className="font-medium dark:text-gray-200">{userToShow?.created_at}</p>
              </div>
              <div>
                <p className="text-gray-500 dark:text-gray-400">Status</p>
                <span
                  className={`px-2 py-1 text-xs rounded-full ${userToShow?.status === '1' ? "bg-green-100 text-green-700 dark:bg-gray-400" : "bg-red-100 text-red-700"
                    }`}
                >
                  {userToShow?.status === '1' ? "Active" : "Inactive"}
                </span>
              </div>
            </div>
          </div>

        </Modal>

        {/* Edit User Modal */}
        <Modal
          isOpen={isEditUserModalOpen}
          onClose={() => setIsEditUserModalOpen(false)}
          title={
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 bg-gradient-to-r from-primary to-secondary rounded-lg flex items-center justify-center">
                <Edit className="w-4 h-4 text-white" />
              </div>
              <div>
                <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">{t("Edit User")}</h2>
              </div>
            </div>
          }
          onSubmit={handleUpdateUser}
          submitText={t("Update User")}
        >
          <div className="space-y-4">
            <p className="text-sm text-gray-500 dark:text-gray-400 text-center">
              {t("Update user information and permissions")}
            </p>
          </div>

          <div className="space-y-4">

            {/* Form */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="edit_name" className="dark:text-neutral-200">{t("Name")}</Label>
                <Input
                  id="edit_name"
                  name="name"
                  placeholder={t("Enter name")}
                  value={editUserData.name}
                  onChange={handleEditUserInputChange}
                />
                <p className="text-sm text-gray-500 dark:text-gray-400">{t("Enter the full name of the user")}.</p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="edit_email" className="dark:text-neutral-200">{t("Email")}</Label>
                <Input
                  id="edit_email"
                  name="email"
                  type="email"
                  placeholder={t("Enter email")}
                  value={editUserData.email}
                  onChange={handleEditUserInputChange}
                />
                <p className="text-sm text-gray-500 dark:text-gray-400">{t("Enter a valid email address")}.</p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="edit_status" className="dark:text-neutral-200">{t("Status")}</Label>
                <Select
                  value={editUserData.status}
                  onValueChange={(value) => setEditUserData((prev) => ({ ...prev, status: value }))}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder={t("Status")} />
                  </SelectTrigger>
                  <SelectContent>
                    {Object.entries(statusEnum).map(([label, value]) => (
                      <SelectItem key={value} value={value}>
                        {label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <p className="text-sm text-gray-500 dark:text-gray-400">{t("Select the user's account status")}.</p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="edit_role" className="dark:text-neutral-200">{t("Role")}</Label>
                <Select
                  value={editUserData.role_id}
                  onValueChange={(value) => setEditUserData((prev) => ({ ...prev, role_id: value }))}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder={t("Select Role")} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="0">{t("No Role Assigned")}</SelectItem>
                    {allRoles && allRoles.map((role) => (
                      <SelectItem key={role.id} value={role.id.toString()}>
                        {role.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <p className="text-sm text-gray-500 dark:text-gray-400">{t("Assign a role to define user permissions")}.</p>
              </div>

              <div className="col-span-2">
                <FileUpload
                  label={t("Profile Image")}
                  value={editUserData.profile_image}
                  onChange={(file) => setEditUserData((prev) => ({ ...prev, profile_image: file }))}
                  accept="image/*"
                  helperText={t("Upload a new profile picture (optional)")}
                />
              </div>
            </div>
          </div>
        </Modal>

        {/* Delete User Modal */}
        <DeleteModal
          isOpen={isDeleteUserModalOpen}
          onClose={() => setIsDeleteUserModalOpen(false)}
          title="Delete this user?"
          description="Are you really sure you want to delete this user?"
          onConfirm={() => handleUserDelete(userToDelete?.id)}
          isDeleting={isUserDeleting}
        />

        {/* Create Role Modal */}
        <Modal
          isOpen={isCreateRoleModalOpen}
          onClose={() => setIsCreateRoleModalOpen(false)}
          title={
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 bg-gradient-to-r from-primary to-secondary rounded-lg flex items-center justify-center">
                <Settings className="w-4 h-4 text-white" />
              </div>
              <div>
                <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">{t("Create Role")}</h2>
              </div>
            </div>
          }
          onSubmit={handleCreateRole}
          submitText={t("Create Role")}
          width="w-[28rem]"
          buttonWidth="w-full"
        >
          <div className="space-y-4">
            <p className="text-sm text-gray-500 dark:text-gray-400 text-center">
              {t("Create a new role to organize user permissions and access levels")}
            </p>
          </div>

          {/* Form */}
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="roleName" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                {t("Role Name")}
              </Label>
              <Input
                id="roleName"
                placeholder={t("Enter role name")}
                value={newRoleData.name}
                onChange={(e) => setNewRoleData((prev) => ({ ...prev, name: e.target.value }))}
                className="w-full"
              />
              <p className="text-xs text-gray-500 dark:text-gray-400">
                {t("Choose a descriptive name for this role")}
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="roleDescription" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                {t("Description")} <span className="text-gray-400">({t("Optional")})</span>
              </Label>
              <Input
                id="roleDescription"
                placeholder={t("Brief description of this role")}
                value={newRoleData.description}
                onChange={(e) => setNewRoleData((prev) => ({ ...prev, description: e.target.value }))}
                className="w-full"
              />
              <p className="text-xs text-gray-500 dark:text-gray-400">
                {t("Briefly describe what this role is for")}
              </p>
            </div>
          </div>
        </Modal>

        {/* Edit Role Modal */}
        <Modal
          isOpen={isEditRoleModalOpen}
          onClose={() => setIsEditRoleModalOpen(false)}
          title={
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-gradient-to-r from-primary to-secondary rounded-xl flex items-center justify-center shadow-lg">
                <Shield className="w-5 h-5 text-white" />
              </div>
              <div>
                <h2 className="text-xl font-bold text-gray-900 dark:text-gray-100">{t("Edit Role")}</h2>
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                  {t("Configure role permissions and access levels")}
                </p>
              </div>
            </div>
          }
          onSubmit={handleUpdateRole}
          submitText={t("Update Role")}
          width="w-[72rem] max-w-xl"
          maxHeight="max-h-[85vh]"
        >
          <div className="space-y-5">
            {/* Role Name Section */}
            <div className="bg-gray-50 dark:bg-gray-800/50 rounded-xl p-5">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 bg-primary/10 dark:bg-primary/20 rounded-lg flex items-center justify-center">
                  <Edit className="h-5 w-5 text-primary" />
                </div>
                <div>
                  <Label className="text-base font-semibold dark:text-gray-200">
                    {t("Role Name")}
                  </Label>
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    {t("Define the role identifier")}
                  </p>
                </div>
              </div>
              <div className="max-w-md">
                <Input
                  id="editRoleName"
                  placeholder={t("Enter role name")}
                  value={editRoleData.name}
                  onChange={(e) => setEditRoleData((prev) => ({ ...prev, name: e.target.value }))}
                  className="bg-white dark:bg-gray-900 text-base"
                />
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
                  {t("Choose a descriptive name for this role that clearly identifies its purpose")}
                </p>
              </div>
            </div>

            {/* Permissions Section */}
            <div>
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-2">
                  <div className="w-8 h-8 bg-primary/10 dark:bg-primary/20 rounded-lg flex items-center justify-center">
                    <Lock className="h-4 w-4 text-primary" />
                  </div>
                  <div>
                    <Label className="text-base font-medium dark:text-gray-200">
                      {t("Permissions")}
                    </Label>
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      {t("Select the modules and actions this role can access")}
                    </p>
                  </div>
                </div>

                {/* All Permissions Checkbox */}
                <div className="flex items-center gap-3">
                  <Checkbox
                    id="all-permissions"
                    checked={isAllPermissionsChecked()}
                    indeterminate={isAllPermissionsIndeterminate()}
                    onCheckedChange={handleAllPermissionsToggle}
                    className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
                  />
                  <Label
                    htmlFor="all-permissions"
                    className="text-sm font-medium cursor-pointer select-none dark:text-gray-200"
                  >
                    {t("All")}
                  </Label>
                </div>
              </div>

              <div className="space-y-3 max-h-[55vh] overflow-y-auto pr-2 custom-scrollbar">
                {rolePermissions && Object.entries(rolePermissions).map(([category, permissions]) => {
                  const CategoryIcon = getCategoryIcon(category)
                  const isChecked = isRoleCategoryChecked(category)
                  const isIndeterminate = isRoleCategoryIndeterminate(category)

                  return (
                    <div key={category} className="group">
                      <div className={`border rounded-xl transition-all duration-200 ${
                        isChecked
                          ? 'border-primary/30 bg-primary/5 dark:border-primary/40 dark:bg-primary/10'
                          : 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/50'
                      }`}>
                        {/* Category Header */}
                        <div className="px-5 py-4 border-b border-gray-100 dark:border-gray-700/50">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-3">
                              <div className={`w-8 h-8 rounded-lg flex items-center justify-center transition-colors ${
                                isChecked
                                  ? 'bg-primary/20 dark:bg-primary/30'
                                  : 'bg-gray-100 dark:bg-gray-700/50'
                              }`}>
                                <CategoryIcon className={`h-4 w-4 ${
                                  isChecked ? 'text-primary' : 'text-gray-500 dark:text-gray-400'
                                }`} />
                              </div>
                              <div className="flex items-center gap-3">
                                <Checkbox
                                  id={`edit-category-${category}`}
                                  checked={isChecked}
                                  indeterminate={isIndeterminate}
                                  onCheckedChange={(checked) => handleRoleCategoryToggle(category, checked)}
                                  className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
                                />
                                <Label
                                  htmlFor={`edit-category-${category}`}
                                  className="text-base font-medium dark:text-gray-200 cursor-pointer select-none"
                                >
                                  {formatCategoryName(category)}
                                </Label>
                              </div>
                            </div>
                            <div className="flex items-center gap-2">
                              <span className="text-xs px-2 py-1 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400">
                                {(editRoleData.permissions[category] || []).length}/{permissions.length}
                              </span>
                            </div>
                          </div>
                        </div>

                        {/* Permissions Grid */}
                        <div className={`px-5 py-4 ${isChecked || isIndeterminate ? '' : 'opacity-60'}`}>
                          <div className="grid grid-cols-3 gap-x-8 gap-y-2.5">
                            {permissions.map((permission) => {
                              const isPermissionChecked = isRolePermissionChecked(category, permission)
                              return (
                                <div key={permission} className="flex items-center gap-2 py-1">
                                  <Checkbox
                                    id={`edit-${category}-${permission}`}
                                    checked={isPermissionChecked}
                                    onCheckedChange={(checked) =>
                                      handleRolePermissionChange(category, permission, checked)
                                    }
                                    className="data-[state=checked]:bg-primary data-[state=checked]:border-primary"
                                  />
                                  <Label
                                    htmlFor={`edit-${category}-${permission}`}
                                    className={`text-xs cursor-pointer select-none ${
                                      isPermissionChecked
                                        ? 'text-gray-700 dark:text-gray-200 font-medium'
                                        : 'text-gray-500 dark:text-gray-400'
                                    }`}
                                  >
                                    {formatPermissionName(permission)}
                                  </Label>
                                </div>
                              )
                            })}
                          </div>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>
          </div>
        </Modal>

        {/* Delete Role Modal */}
        <DeleteModal
          isOpen={isDeleteRoleModalOpen}
          onClose={() => setIsDeleteRoleModalOpen(false)}
          title="Delete this role?"
          description="Are you really sure you want to delete this role?"
          onConfirm={() => handleRoleDelete(roleToDelete?.id)}
          isDeleting={isRoleDeleting}
        />
      </div>
    </AppLayout>
  )
}
