import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useAuth } from "@/hooks/use-auth";
import { supabase } from "@/integrations/supabase/client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { createUserFn, deleteUserFn, listAdminUsersFn, resetUserPasswordFn } from "@/lib/users.functions";
import {
  Users,
  Shield,
  Settings,
  Activity,
  Search,
  Save,
  UserPlus,
  Trash2,
  Clock,
  AlertCircle,
  Lock,
  Edit,
  Ban,
  CheckCircle,
  Key,
} from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/admin")({
  head: () => ({
    meta: [
      { title: "Admin Panel — Niyamah Electric & Hardware" },
      { name: "description", content: "Admin panel for managing users, roles, settings and activity logs" },
    ],
  }),
  component: AdminPage,
});

type Tab = "users" | "roles" | "permissions" | "settings" | "activity";

function AdminPage() {
  const { tr } = useLanguage();
  const [activeTab, setActiveTab] = useState<Tab>("users");

  const tabs = [
    { key: "users" as Tab, labelKey: "adminUsers", icon: Users },
    { key: "roles" as Tab, labelKey: "roleManagement", icon: Shield },
    { key: "permissions" as Tab, labelKey: "permissionMatrix", icon: Lock },
    { key: "settings" as Tab, labelKey: "adminBusinessSettings", icon: Settings },
    { key: "activity" as Tab, labelKey: "adminActivityLog", icon: Activity },
  ];

  return (
    <PageLayout>
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold text-foreground">{tr("adminPanel")}</h1>
          <p className="text-sm text-muted-foreground mt-1">{tr("adminPanelDesc")}</p>
        </div>

        <div className="flex gap-1 border-b border-border overflow-x-auto">
          {tabs.map((tab) => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={`flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
                activeTab === tab.key
                  ? "border-primary text-primary"
                  : "border-transparent text-muted-foreground hover:text-foreground"
              }`}
            >
              <tab.icon className="h-4 w-4" />
              {tr(tab.labelKey)}
            </button>
          ))}
        </div>

        {activeTab === "users" && <UserManagement />}
        {activeTab === "roles" && <RoleManagement />}
        {activeTab === "permissions" && <PermissionMatrix />}
        {activeTab === "settings" && <BusinessSettings />}
        {activeTab === "activity" && <ActivityLog />}
      </div>
    </PageLayout>
  );
}

/* ─── User Management ─── */
function UserManagement() {
  const { tr, lang } = useLanguage();
  const queryClient = useQueryClient();
  const { user: currentUser } = useAuth();
  const [searchTerm, setSearchTerm] = useState("");
  const [showAddUser, setShowAddUser] = useState(false);
  const [selectedStatus, setSelectedStatus] = useState("all");
  const [selectedSystemRole, setSelectedSystemRole] = useState("all");
  const [selectedBranchId, setSelectedBranchId] = useState("all");
  const [newRoleUserId, setNewRoleUserId] = useState("");
  const [newRole, setNewRole] = useState<"admin" | "staff" | "user">("staff");
  const [editingUser, setEditingUser] = useState<string | null>(null);
  const [editForm, setEditForm] = useState({ mobile: "", username: "", custom_role_id: "", branch_id: "" });
  const [resetPwdUserId, setResetPwdUserId] = useState<string | null>(null);
  const [resetPwdValue, setResetPwdValue] = useState("");
  const [newUserForm, setNewUserForm] = useState({
    email: "", password: "", full_name: "", mobile: "", username: "",
    branch_id: "",
    system_role: "staff" as "admin" | "staff" | "user",
    custom_role_id: "",
  });

  const callCreateUser = useServerFn(createUserFn);
  const callDeleteUser = useServerFn(deleteUserFn);
  const callResetPassword = useServerFn(resetUserPasswordFn);
  const callListAdminUsers = useServerFn(listAdminUsersFn);

  const { data: usersRaw, isLoading: loadingUsers } = useQuery({
    queryKey: ["admin-users"],
    queryFn: async () => {
      return await callListAdminUsers();
    },
  });
  const users = Array.isArray(usersRaw) ? usersRaw : [];

  const { data: userRolesRaw } = useQuery({
    queryKey: ["admin-user-roles"],
    queryFn: async () => {
      const { data, error } = await supabase.from("user_roles").select("*");
      if (error) throw error;
      return data ?? [];
    },
  });
  const userRoles = Array.isArray(userRolesRaw) ? userRolesRaw : [];

  const { data: customRolesRaw } = useQuery({
    queryKey: ["custom-roles"],
    queryFn: async () => {
      const { data, error } = await supabase.from("custom_roles").select("*").eq("status", "active");
      if (error) throw error;
      return data ?? [];
    },
  });
  const customRoles = Array.isArray(customRolesRaw) ? customRolesRaw : [];

  const { data: branchesRaw } = useQuery({
    queryKey: ["branches"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("branches")
        .select("id, name, status")
        .is("deleted_at", null)
        .order("name");
      if (error) throw error;
      return data ?? [];
    },
  });
  const branches = Array.isArray(branchesRaw) ? branchesRaw : [];



  const addRoleMutation = useMutation({
    mutationFn: async ({ userId, role }: { userId: string; role: string }) => {
      const { error } = await supabase.from("user_roles").insert([{ user_id: userId, role: role as "admin" | "staff" | "user" }]);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      queryClient.invalidateQueries({ queryKey: ["admin-user-roles"] });
      toast.success(tr("roleAdded"));
      setNewRoleUserId("");
    },
    onError: (err: any) => toast.error(err.message),
  });

  const removeRoleMutation = useMutation({
    mutationFn: async (roleId: string) => {
      const { error } = await supabase.from("user_roles").delete().eq("id", roleId);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      queryClient.invalidateQueries({ queryKey: ["admin-user-roles"] });
      toast.success(tr("roleRemoved"));
    },
    onError: (err: any) => toast.error(err.message),
  });

  const updateProfileMutation = useMutation({
    mutationFn: async ({ userId, data }: { userId: string; data: any }) => {
      const { error } = await supabase.from("profiles").update(data).eq("id", userId);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      toast.success(tr("userUpdated"));
      setEditingUser(null);
    },
    onError: (err: any) => toast.error(err.message),
  });

  const toggleStatusMutation = useMutation({
    mutationFn: async ({ userId, status }: { userId: string; status: string }) => {
      const { error } = await supabase.from("profiles").update({ status }).eq("id", userId);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      toast.success(tr("statusUpdated"));
    },
    onError: (err: any) => toast.error(err.message),
  });

  const createUserMutation = useMutation({
    mutationFn: async () => {
      if (!newUserForm.email.trim() || !newUserForm.password.trim() || !newUserForm.full_name.trim()) {
        throw new Error("Email, Password ও পুরো নাম প্রয়োজন");
      }
      return await callCreateUser({
        data: {
          email: newUserForm.email.trim(),
          password: newUserForm.password,
          full_name: newUserForm.full_name.trim(),
          mobile: newUserForm.mobile.trim(),
          username: newUserForm.username.trim(),
          branch_id: newUserForm.branch_id || null,
          system_role: newUserForm.system_role,
          custom_role_id: newUserForm.custom_role_id || null,
        },
      });
    },
    onSuccess: (createdUser) => {
      queryClient.setQueryData(["admin-users"], (existing: any[] | undefined) => {
        const safeExisting = Array.isArray(existing) ? existing : [];
        const withoutDuplicate = safeExisting.filter((user) => user.id !== createdUser.id);
        return [createdUser, ...withoutDuplicate];
      });
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      queryClient.invalidateQueries({ queryKey: ["admin-user-roles"] });
      toast.success("নতুন ইউজার তৈরি হয়েছে");
      setShowAddUser(false);
      setNewUserForm({
        email: "", password: "", full_name: "", mobile: "", username: "",
        branch_id: "", system_role: "staff", custom_role_id: "",
      });
    },
    onError: (err: any) => toast.error(err.message || "ইউজার তৈরি ব্যর্থ"),
  });

  const deleteUserMutation = useMutation({
    mutationFn: async (userId: string) => {
      return await callDeleteUser({ data: { user_id: userId } });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      queryClient.invalidateQueries({ queryKey: ["admin-user-roles"] });
      toast.success("ইউজার ডিলিট হয়েছে");
    },
    onError: (err: any) => toast.error(err.message),
  });

  const resetPasswordMutation = useMutation({
    mutationFn: async () => {
      if (!resetPwdUserId || resetPwdValue.length < 6) {
        throw new Error("কমপক্ষে ৬ অক্ষরের পাসওয়ার্ড দিন");
      }
      return await callResetPassword({
        data: { user_id: resetPwdUserId, new_password: resetPwdValue },
      });
    },
    onSuccess: () => {
      toast.success("পাসওয়ার্ড পরিবর্তন হয়েছে");
      setResetPwdUserId(null);
      setResetPwdValue("");
    },
    onError: (err: any) => toast.error(err.message),
  });

  const getRolesForUser = (userId: string) => {
    const fromList = users.find((u: any) => u.id === userId)?.roles ?? [];
    const fromQuery = userRoles.filter((r) => r.user_id === userId);
    const merged = [...fromList, ...fromQuery];
    return merged.filter((role: any, index: number, arr: any[]) => {
      const roleKey = role.id || `${role.user_id}-${role.role}`;
      return arr.findIndex((item) => (item.id || `${item.user_id}-${item.role}`) === roleKey) === index;
    });
  };
  const getCustomRoleName = (roleId: string | null) => customRoles.find((r) => r.id === roleId)?.name || "—";
  const getBranchName = (branchId: string | null) => branches.find((b: any) => b.id === branchId)?.name || "—";

  const normalizedSearch = searchTerm.trim().toLowerCase();
  const filteredUsers = users.filter((user) => {
    const row = user as any;
    const searchMatches = !normalizedSearch || [
      row.full_name,
      row.email,
      row.mobile,
      row.username,
      getCustomRoleName(row.custom_role_id),
      getBranchName(row.branch_id),
      ...(getRolesForUser(row.id).map((role: any) => role.role)),
    ]
      .filter(Boolean)
      .some((value) => String(value).toLowerCase().includes(normalizedSearch));

    const statusMatches = selectedStatus === "all" || (row.status || "active") === selectedStatus;
    const roleMatches = selectedSystemRole === "all" || getRolesForUser(row.id).some((role: any) => role.role === selectedSystemRole);
    const branchMatches = selectedBranchId === "all" || (row.branch_id || "") === selectedBranchId;

    return searchMatches && statusMatches && roleMatches && branchMatches;
  });

  const totalUsers = users.length;
  const activeUsers = users.filter((user: any) => (user.status || "active") === "active").length;
  const inactiveUsers = users.filter((user: any) => (user.status || "active") !== "active").length;

  return (
    <div className="space-y-5">
      {/* Create New User */}
      <div className="grid gap-4 sm:grid-cols-3">
        <div className="rounded-xl border border-border bg-card p-4">
          <div className="text-xs text-muted-foreground">মোট ইউজার</div>
          <div className="mt-1 text-2xl font-semibold text-foreground">{totalUsers}</div>
        </div>
        <div className="rounded-xl border border-border bg-card p-4">
          <div className="text-xs text-muted-foreground">Active</div>
          <div className="mt-1 text-2xl font-semibold text-foreground">{activeUsers}</div>
        </div>
        <div className="rounded-xl border border-border bg-card p-4">
          <div className="text-xs text-muted-foreground">Inactive / Blocked</div>
          <div className="mt-1 text-2xl font-semibold text-foreground">{inactiveUsers}</div>
        </div>
      </div>

      <div className="flex justify-end">
        <button
          onClick={() => setShowAddUser(true)}
          className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
        >
          <UserPlus className="h-4 w-4" /> নতুন ইউজার তৈরি
        </button>
      </div>

      {/* Add System Role */}
      <div className="rounded-xl border border-border bg-card p-5">
        <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
          <UserPlus className="h-4 w-4" />
          {tr("assignSystemRole")}
        </h3>
        <div className="flex flex-wrap gap-3">
          <select value={newRoleUserId} onChange={(e) => setNewRoleUserId(e.target.value)}
            className="flex-1 min-w-[200px] rounded-lg border border-input bg-background px-3 py-2 text-sm">
            <option value="">{tr("selectUser")}</option>
            {users.map((p: any) => (
              <option key={p.id} value={p.id}>{p.full_name || p.id.slice(0, 8)}</option>
            ))}
          </select>
          <select value={newRole} onChange={(e) => setNewRole(e.target.value as any)}
            className="rounded-lg border border-input bg-background px-3 py-2 text-sm">
            <option value="admin">Admin</option>
            <option value="staff">Staff</option>
            <option value="user">User</option>
          </select>
          <button onClick={() => newRoleUserId && addRoleMutation.mutate({ userId: newRoleUserId, role: newRole })}
            disabled={!newRoleUserId || addRoleMutation.isPending}
            className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50">
            {tr("addRole")}
          </button>
        </div>
      </div>

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <input type="text" placeholder="নাম / email / mobile / username / role / branch দিয়ে search করুন" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)}
          className="w-full rounded-lg border border-input bg-background pl-10 pr-4 py-2.5 text-sm" />
      </div>

      <div className="grid gap-3 sm:grid-cols-2">
        <select
          value={selectedStatus}
          onChange={(e) => setSelectedStatus(e.target.value)}
          className="rounded-lg border border-input bg-background px-3 py-2 text-sm"
        >
          <option value="all">সব status</option>
          <option value="active">Active</option>
          <option value="inactive">Inactive</option>
          <option value="blocked">Blocked</option>
        </select>
        <select
          value={selectedSystemRole}
          onChange={(e) => setSelectedSystemRole(e.target.value)}
          className="rounded-lg border border-input bg-background px-3 py-2 text-sm"
        >
          <option value="all">সব system role</option>
          <option value="admin">Admin</option>
          <option value="staff">Staff</option>
          <option value="user">User</option>
        </select>
      </div>

      <select
        value={selectedBranchId}
        onChange={(e) => setSelectedBranchId(e.target.value)}
        className="rounded-lg border border-input bg-background px-3 py-2 text-sm"
      >
        <option value="all">সব branch</option>
        <option value="">Branch ছাড়া</option>
        {branches.map((branch: any) => (
          <option key={branch.id} value={branch.id}>{branch.name}</option>
        ))}
      </select>

      {/* Users Table */}
      <div className="rounded-xl border border-border bg-card overflow-hidden">
        {loadingUsers ? (
          <div className="p-8 text-center text-muted-foreground text-sm">{tr("loading")}...</div>
        ) : filteredUsers.length === 0 ? (
          <div className="p-8 text-center text-muted-foreground text-sm">{tr("noResults")}</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border bg-muted/30">
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("userName")}</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">Email</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("mobile")}</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("usernameLabel")}</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">Branch</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("customRole")}</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("systemRoles")}</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("status")}</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("actions")}</th>
                </tr>
              </thead>
              <tbody>
                {filteredUsers.map((profile: any) => {
                  const roles = getRolesForUser(profile.id);
                  const p = profile as any;
                  const isEditing = editingUser === profile.id;

                  return (
                    <tr key={profile.id} className="border-b border-border/50 hover:bg-muted/20">
                      <td className="px-4 py-3">
                        <div className="font-medium text-foreground">{profile.full_name || "—"}</div>
                        <div className="text-[10px] text-muted-foreground">{p.last_login ? new Date(p.last_login).toLocaleString(lang === "bn" ? "bn-BD" : "en-US") : tr("neverLoggedIn")}</div>
                      </td>
                      <td className="px-4 py-3 text-muted-foreground">{p.email || "—"}</td>
                      <td className="px-4 py-3 text-muted-foreground">
                        {isEditing ? (
                          <input value={editForm.mobile} onChange={(e) => setEditForm(f => ({ ...f, mobile: e.target.value }))}
                            className="w-28 rounded border border-input bg-background px-2 py-1 text-xs" />
                        ) : p.mobile || "—"}
                      </td>
                      <td className="px-4 py-3 text-muted-foreground">
                        {isEditing ? (
                          <input value={editForm.username} onChange={(e) => setEditForm(f => ({ ...f, username: e.target.value }))}
                            className="w-28 rounded border border-input bg-background px-2 py-1 text-xs" />
                        ) : p.username || "—"}
                      </td>
                      <td className="px-4 py-3 text-muted-foreground">
                        {isEditing ? (
                          <select value={editForm.branch_id} onChange={(e) => setEditForm(f => ({ ...f, branch_id: e.target.value }))}
                            className="rounded border border-input bg-background px-2 py-1 text-xs">
                            <option value="">—</option>
                            {branches.map((branch: any) => <option key={branch.id} value={branch.id}>{branch.name}</option>)}
                          </select>
                        ) : getBranchName(p.branch_id)}
                      </td>
                      <td className="px-4 py-3">
                        {isEditing ? (
                          <select value={editForm.custom_role_id} onChange={(e) => setEditForm(f => ({ ...f, custom_role_id: e.target.value }))}
                            className="rounded border border-input bg-background px-2 py-1 text-xs">
                            <option value="">—</option>
                            {customRoles.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
                          </select>
                        ) : (
                          <span className="text-xs bg-accent/50 rounded-full px-2 py-0.5">{getCustomRoleName(p.custom_role_id)}</span>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex flex-wrap gap-1">
                          {roles.length === 0 ? (
                            <span className="text-xs text-muted-foreground italic">{tr("noRole")}</span>
                          ) : roles.map((r: any) => (
                            <span key={r.id || `${profile.id}-${r.role}`} className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium ${
                              r.role === "admin" ? "bg-destructive/10 text-destructive" : r.role === "staff" ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground"
                            }`}>
                              <Shield className="h-2.5 w-2.5" />{r.role}
                            </span>
                          ))}
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <span className={`text-[10px] font-medium rounded-full px-2 py-0.5 ${
                          p.status === "active" ? "bg-green-500/10 text-green-600" :
                          p.status === "blocked" ? "bg-red-500/10 text-red-600" : "bg-yellow-500/10 text-yellow-600"
                        }`}>{p.status || "active"}</span>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex gap-1">
                          {isEditing ? (
                            <>
                              <button onClick={() => updateProfileMutation.mutate({
                                userId: profile.id,
                                data: { mobile: editForm.mobile || null, username: editForm.username || null, custom_role_id: editForm.custom_role_id || null, branch_id: editForm.branch_id || null }
                              })} className="rounded p-1.5 text-green-600 hover:bg-green-500/10"><Save className="h-3.5 w-3.5" /></button>
                              <button onClick={() => setEditingUser(null)} className="rounded p-1.5 text-muted-foreground hover:bg-muted">✕</button>
                            </>
                          ) : (
                            <>
                              <button onClick={() => { setEditingUser(profile.id); setEditForm({ mobile: p.mobile || "", username: p.username || "", custom_role_id: p.custom_role_id || "", branch_id: p.branch_id || "" }); }}
                                className="rounded p-1.5 text-primary hover:bg-primary/10" title="Edit"><Edit className="h-3.5 w-3.5" /></button>
                              {p.status !== "blocked" ? (
                                <button onClick={() => toggleStatusMutation.mutate({ userId: profile.id, status: "blocked" })}
                                  className="rounded p-1.5 text-destructive hover:bg-destructive/10" title="Block"><Ban className="h-3.5 w-3.5" /></button>
                              ) : (
                                <button onClick={() => toggleStatusMutation.mutate({ userId: profile.id, status: "active" })}
                                  className="rounded p-1.5 text-green-600 hover:bg-green-500/10" title="Activate"><CheckCircle className="h-3.5 w-3.5" /></button>
                              )}
                              {roles.map((r: any) => (
                                <button key={r.id} onClick={() => removeRoleMutation.mutate(r.id)}
                                  className="rounded p-1.5 text-destructive hover:bg-destructive/10" title={`Remove ${r.role}`}><Trash2 className="h-3.5 w-3.5" /></button>
                              ))}
                              <button onClick={() => { setResetPwdUserId(profile.id); setResetPwdValue(""); }}
                                className="rounded p-1.5 text-amber-600 hover:bg-amber-500/10" title="Reset Password"><Key className="h-3.5 w-3.5" /></button>
                              {profile.id !== currentUser?.id && (
                                <button onClick={() => { if (confirm("এই ইউজারকে স্থায়ীভাবে ডিলিট করতে চান?")) deleteUserMutation.mutate(profile.id); }}
                                  className="rounded p-1.5 text-destructive hover:bg-destructive/10" title="Delete User"><Trash2 className="h-3.5 w-3.5" /></button>
                              )}
                            </>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Create User Modal */}
      {showAddUser && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setShowAddUser(false)}>
          <div className="w-full max-w-lg rounded-xl bg-card p-6 shadow-xl" onClick={(e) => e.stopPropagation()}>
            <h3 className="text-lg font-semibold mb-4 flex items-center gap-2"><UserPlus className="h-5 w-5" /> নতুন ইউজার তৈরি</h3>
            <div className="space-y-3">
              <div>
                <label className="text-xs font-medium text-muted-foreground">পুরো নাম *</label>
                <input value={newUserForm.full_name} onChange={(e) => setNewUserForm(f => ({ ...f, full_name: e.target.value }))}
                  className="w-full mt-1 rounded-lg border border-input bg-background px-3 py-2 text-sm" />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-medium text-muted-foreground">Email *</label>
                  <input type="email" value={newUserForm.email} onChange={(e) => setNewUserForm(f => ({ ...f, email: e.target.value }))}
                    className="w-full mt-1 rounded-lg border border-input bg-background px-3 py-2 text-sm" />
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground">Password *</label>
                  <input type="text" value={newUserForm.password} onChange={(e) => setNewUserForm(f => ({ ...f, password: e.target.value }))}
                    className="w-full mt-1 rounded-lg border border-input bg-background px-3 py-2 text-sm" placeholder="min 6 chars" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-medium text-muted-foreground">মোবাইল</label>
                  <input value={newUserForm.mobile} onChange={(e) => setNewUserForm(f => ({ ...f, mobile: e.target.value }))}
                    className="w-full mt-1 rounded-lg border border-input bg-background px-3 py-2 text-sm" />
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground">Username</label>
                  <input value={newUserForm.username} onChange={(e) => setNewUserForm(f => ({ ...f, username: e.target.value }))}
                    className="w-full mt-1 rounded-lg border border-input bg-background px-3 py-2 text-sm" />
                </div>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground">Branch</label>
                <select value={newUserForm.branch_id} onChange={(e) => setNewUserForm(f => ({ ...f, branch_id: e.target.value }))}
                  className="w-full mt-1 rounded-lg border border-input bg-background px-3 py-2 text-sm">
                  <option value="">— None —</option>
                  {branches.map((branch: any) => <option key={branch.id} value={branch.id}>{branch.name}</option>)}
                </select>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs font-medium text-muted-foreground">System Role</label>
                  <select value={newUserForm.system_role} onChange={(e) => setNewUserForm(f => ({ ...f, system_role: e.target.value as any }))}
                    className="w-full mt-1 rounded-lg border border-input bg-background px-3 py-2 text-sm">
                    <option value="admin">Admin</option>
                    <option value="staff">Staff</option>
                    <option value="user">User</option>
                  </select>
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground">Custom Role</label>
                  <select value={newUserForm.custom_role_id} onChange={(e) => setNewUserForm(f => ({ ...f, custom_role_id: e.target.value }))}
                    className="w-full mt-1 rounded-lg border border-input bg-background px-3 py-2 text-sm">
                    <option value="">— None —</option>
                    {customRoles.map((r: any) => <option key={r.id} value={r.id}>{r.name}</option>)}
                  </select>
                </div>
              </div>
            </div>
            <div className="flex justify-end gap-2 mt-5">
              <button onClick={() => setShowAddUser(false)} className="rounded-lg border border-input px-4 py-2 text-sm">বাতিল</button>
              <button onClick={() => createUserMutation.mutate()} disabled={createUserMutation.isPending}
                className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50">
                {createUserMutation.isPending ? "তৈরি হচ্ছে..." : "তৈরি করুন"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Reset Password Modal */}
      {resetPwdUserId && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setResetPwdUserId(null)}>
          <div className="w-full max-w-sm rounded-xl bg-card p-6 shadow-xl" onClick={(e) => e.stopPropagation()}>
            <h3 className="text-lg font-semibold mb-4 flex items-center gap-2"><Key className="h-5 w-5" /> পাসওয়ার্ড রিসেট</h3>
            <input type="text" value={resetPwdValue} onChange={(e) => setResetPwdValue(e.target.value)}
              placeholder="নতুন পাসওয়ার্ড (min 6 chars)"
              className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm" />
            <div className="flex justify-end gap-2 mt-4">
              <button onClick={() => setResetPwdUserId(null)} className="rounded-lg border border-input px-4 py-2 text-sm">বাতিল</button>
              <button onClick={() => resetPasswordMutation.mutate()} disabled={resetPasswordMutation.isPending}
                className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50">
                {resetPasswordMutation.isPending ? "..." : "পরিবর্তন করুন"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ─── Role Management ─── */
function RoleManagement() {
  const { tr } = useLanguage();
  const queryClient = useQueryClient();
  const [newRoleName, setNewRoleName] = useState("");
  const [newRoleDesc, setNewRoleDesc] = useState("");
  const [editingRole, setEditingRole] = useState<string | null>(null);
  const [editForm, setEditForm] = useState({ name: "", description: "" });

  const { data: roles = [], isLoading } = useQuery({
    queryKey: ["custom-roles-all"],
    queryFn: async () => {
      const { data, error } = await supabase.from("custom_roles").select("*").order("created_at");
      if (error) throw error;
      return data;
    },
  });

  const { data: profiles = [] } = useQuery({
    queryKey: ["admin-profiles"],
    queryFn: async () => {
      const { data, error } = await supabase.from("profiles").select("*");
      if (error) throw error;
      return data;
    },
  });

  const addMutation = useMutation({
    mutationFn: async () => {
      if (!newRoleName.trim()) throw new Error("Role name required");
      const { error } = await supabase.from("custom_roles").insert({ name: newRoleName.trim(), description: newRoleDesc.trim() });
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["custom-roles-all"] });
      queryClient.invalidateQueries({ queryKey: ["custom-roles"] });
      toast.success(tr("roleAdded"));
      setNewRoleName("");
      setNewRoleDesc("");
    },
    onError: (err: any) => toast.error(err.message),
  });

  const updateMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("custom_roles").update({ name: editForm.name, description: editForm.description }).eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["custom-roles-all"] });
      queryClient.invalidateQueries({ queryKey: ["custom-roles"] });
      toast.success(tr("roleUpdated"));
      setEditingRole(null);
    },
    onError: (err: any) => toast.error(err.message),
  });

  const toggleStatusMutation = useMutation({
    mutationFn: async ({ id, status }: { id: string; status: string }) => {
      const next = status === "active" ? "inactive" : "active";
      const { error } = await supabase.from("custom_roles").update({ status: next }).eq("id", id);
      if (error) throw error;
      return next;
    },
    onSuccess: (next) => {
      queryClient.invalidateQueries({ queryKey: ["custom-roles-all"] });
      queryClient.invalidateQueries({ queryKey: ["custom-roles"] });
      toast.success(next === "active" ? "Role activated" : "Role deactivated");
    },
    onError: (err: any) => toast.error(err.message),
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("custom_roles").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["custom-roles-all"] });
      queryClient.invalidateQueries({ queryKey: ["custom-roles"] });
      toast.success(tr("roleRemoved"));
    },
    onError: (err: any) => toast.error(err.message),
  });

  const getUserCountForRole = (roleId: string) =>
    (profiles as any[]).filter(p => p.custom_role_id === roleId).length;

  return (
    <div className="space-y-5">
      {/* Add Role */}
      <div className="rounded-xl border border-border bg-card p-5">
        <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
          <Shield className="h-4 w-4" />{tr("addCustomRole")}
        </h3>
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
          <input value={newRoleName} onChange={(e) => setNewRoleName(e.target.value)}
            placeholder={tr("roleName")} className="rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          <input value={newRoleDesc} onChange={(e) => setNewRoleDesc(e.target.value)}
            placeholder={tr("roleDescription")} className="rounded-lg border border-input bg-background px-3 py-2 text-sm" />
          <button onClick={() => addMutation.mutate()} disabled={!newRoleName.trim() || addMutation.isPending}
            className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50">
            {tr("addCustomRole")}
          </button>
        </div>
      </div>

      {/* Roles List */}
      <div className="rounded-xl border border-border bg-card overflow-hidden">
        {isLoading ? (
          <div className="p-8 text-center text-muted-foreground text-sm">{tr("loading")}...</div>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-muted/30">
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("roleName")}</th>
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("roleDescription")}</th>
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("assignedUsers")}</th>
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("status")}</th>
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("actions")}</th>
              </tr>
            </thead>
            <tbody>
              {roles.map((role) => {
                const isEditing = editingRole === role.id;
                return (
                  <tr key={role.id} className="border-b border-border/50 hover:bg-muted/20">
                    <td className="px-4 py-3 font-medium text-foreground">
                      {isEditing ? (
                        <input value={editForm.name} onChange={(e) => setEditForm(f => ({ ...f, name: e.target.value }))}
                          className="w-full rounded border border-input bg-background px-2 py-1 text-xs" />
                      ) : role.name}
                    </td>
                    <td className="px-4 py-3 text-muted-foreground text-xs">
                      {isEditing ? (
                        <input value={editForm.description} onChange={(e) => setEditForm(f => ({ ...f, description: e.target.value }))}
                          className="w-full rounded border border-input bg-background px-2 py-1 text-xs" />
                      ) : role.description || "—"}
                    </td>
                    <td className="px-4 py-3">
                      <span className="bg-primary/10 text-primary rounded-full px-2 py-0.5 text-xs font-medium">{getUserCountForRole(role.id)}</span>
                    </td>
                    <td className="px-4 py-3">
                      {role.name === "Admin" ? (
                        <span title="Admin is a protected system role"
                          className="text-[10px] rounded-full px-2 py-0.5 bg-green-500/10 text-green-600 inline-flex items-center gap-1">
                          🔒 Protected
                        </span>
                      ) : (
                        <button
                          onClick={() => toggleStatusMutation.mutate({ id: role.id, status: role.status })}
                          disabled={toggleStatusMutation.isPending}
                          title={role.status === "active" ? "Click to deactivate" : "Click to activate"}
                          className={`text-[10px] rounded-full px-2 py-0.5 cursor-pointer transition hover:opacity-80 disabled:opacity-50 ${role.status === "active" ? "bg-green-500/10 text-green-600" : "bg-red-500/10 text-red-600"}`}
                        >
                          {role.status === "active" ? "● Active" : "○ Inactive"}
                        </button>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex gap-1">
                        {isEditing ? (
                          <>
                            <button onClick={() => updateMutation.mutate(role.id)} className="rounded p-1.5 text-green-600 hover:bg-green-500/10"><Save className="h-3.5 w-3.5" /></button>
                            <button onClick={() => setEditingRole(null)} className="rounded p-1.5 text-muted-foreground hover:bg-muted">✕</button>
                          </>
                        ) : (
                          <>
                            <button onClick={() => { setEditingRole(role.id); setEditForm({ name: role.name, description: role.description || "" }); }}
                              className="rounded p-1.5 text-primary hover:bg-primary/10"><Edit className="h-3.5 w-3.5" /></button>
                            {role.name !== "Admin" && (
                              <button onClick={() => deleteMutation.mutate(role.id)}
                                className="rounded p-1.5 text-destructive hover:bg-destructive/10"><Trash2 className="h-3.5 w-3.5" /></button>
                            )}
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

/* ─── Permission Matrix ─── */
function PermissionMatrix() {
  const { tr } = useLanguage();
  const queryClient = useQueryClient();

  const { data: roles = [] } = useQuery({
    queryKey: ["custom-roles-all"],
    queryFn: async () => {
      const { data, error } = await supabase.from("custom_roles").select("*").order("created_at");
      if (error) throw error;
      return data;
    },
  });

  const { data: permissions = [] } = useQuery({
    queryKey: ["permissions"],
    queryFn: async () => {
      const { data, error } = await supabase.from("permissions").select("*").order("module, name");
      if (error) throw error;
      return data;
    },
  });

  const { data: rolePermissions = [] } = useQuery({
    queryKey: ["role-permissions"],
    queryFn: async () => {
      const { data, error } = await supabase.from("role_permissions").select("*");
      if (error) throw error;
      return data;
    },
  });

  const togglePermission = useMutation({
    mutationFn: async ({ roleId, permissionId, hasIt }: { roleId: string; permissionId: string; hasIt: boolean }) => {
      if (hasIt) {
        const { error } = await supabase.from("role_permissions").delete().eq("role_id", roleId).eq("permission_id", permissionId);
        if (error) throw error;
      } else {
        const { error } = await supabase.from("role_permissions").insert({ role_id: roleId, permission_id: permissionId });
        if (error) throw error;
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["role-permissions"] });
    },
    onError: (err: any) => toast.error(err.message),
  });

  const hasPermission = (roleId: string, permId: string) =>
    rolePermissions.some(rp => rp.role_id === roleId && rp.permission_id === permId);

  // Group permissions by module
  const modules = permissions.reduce<Record<string, typeof permissions>>((acc, p) => {
    if (!acc[p.module]) acc[p.module] = [];
    acc[p.module].push(p);
    return acc;
  }, {});

  const moduleLabels: Record<string, string> = {
    sales: "🛒 Sales",
    product: "📦 Product",
    customer: "👥 Customer",
    accounts: "💰 Accounts",
    admin: "⚙️ Admin",
    returns: "🔁 Returns",
    reports: "📊 Reports",
  };

  return (
    <div className="space-y-5">
      <div className="rounded-xl border border-border bg-card p-5">
        <h3 className="text-sm font-semibold text-foreground mb-1 flex items-center gap-2">
          <Key className="h-4 w-4" />{tr("permissionMatrix")}
        </h3>
        <p className="text-xs text-muted-foreground mb-4">{tr("permissionMatrixDesc")}</p>

        {roles.length === 0 || permissions.length === 0 ? (
          <p className="text-sm text-muted-foreground text-center py-8">{tr("noResults")}</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm border-collapse">
              <thead>
                <tr className="border-b border-border">
                  <th className="px-3 py-2 text-left font-medium text-muted-foreground sticky left-0 bg-card z-10 min-w-[200px]">{tr("permissionName")}</th>
                  {roles.map(r => (
                    <th key={r.id} className="px-3 py-2 text-center font-medium text-muted-foreground min-w-[100px]">
                      <div className="text-xs">{r.name}</div>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {Object.entries(modules).map(([mod, perms]) => (
                  <>
                    <tr key={`mod-${mod}`} className="bg-muted/40">
                      <td colSpan={roles.length + 1} className="px-3 py-2 text-xs font-bold text-foreground">
                        {moduleLabels[mod] || mod}
                      </td>
                    </tr>
                    {perms.map((perm) => (
                      <tr key={perm.id} className="border-b border-border/30 hover:bg-muted/20">
                        <td className="px-3 py-2 text-xs text-foreground sticky left-0 bg-card z-10">
                          <div>{perm.name.replace(/_/g, " ")}</div>
                          <div className="text-[10px] text-muted-foreground">{perm.description}</div>
                        </td>
                        {roles.map(r => {
                          const has = hasPermission(r.id, perm.id);
                          return (
                            <td key={r.id} className="px-3 py-2 text-center">
                              <button
                                onClick={() => togglePermission.mutate({ roleId: r.id, permissionId: perm.id, hasIt: has })}
                                className={`h-5 w-5 rounded border-2 transition-all inline-flex items-center justify-center ${
                                  has ? "bg-primary border-primary text-primary-foreground" : "border-muted-foreground/30 hover:border-primary/50"
                                }`}
                              >
                                {has && <CheckCircle className="h-3 w-3" />}
                              </button>
                            </td>
                          );
                        })}
                      </tr>
                    ))}
                  </>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

/* ─── Business Settings ─── */
function BusinessSettings() {
  const { tr } = useLanguage();
  const queryClient = useQueryClient();

  const { data: settings = [], isLoading } = useQuery({
    queryKey: ["business-settings"],
    queryFn: async () => {
      const { data, error } = await supabase.from("business_settings").select("*");
      if (error) throw error;
      return data;
    },
  });

  const [editValues, setEditValues] = useState<Record<string, string>>({});

  const getVal = (key: string) =>
    editValues[key] ?? settings.find((s) => s.setting_key === key)?.setting_value ?? "";

  const updateMutation = useMutation({
    mutationFn: async () => {
      for (const [key, value] of Object.entries(editValues)) {
        const { error } = await supabase.from("business_settings").update({ setting_value: value }).eq("setting_key", key);
        if (error) throw error;
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["business-settings"] });
      setEditValues({});
      toast.success(tr("settingsSaved"));
    },
    onError: (err: any) => toast.error(err.message),
  });

  const settingFields = [
    { key: "business_name", labelKey: "businessName", type: "text" },
    { key: "business_name_bn", labelKey: "businessNameBn", type: "text" },
    { key: "address", labelKey: "address", type: "text" },
    { key: "phone", labelKey: "phoneNumber", type: "text" },
    { key: "email", labelKey: "email", type: "email" },
    { key: "commission_rate", labelKey: "commissionRate", type: "number" },
    { key: "currency", labelKey: "currency", type: "text" },
    { key: "vat_rate", labelKey: "vatRate", type: "number" },
    { key: "invoice_footer_terms", label: "Invoice Footer — শর্তাবলী", type: "textarea", full: true },
    { key: "invoice_footer_thanks", label: "Invoice Footer — ধন্যবাদ বার্তা", type: "textarea", full: true },
  ];

  if (isLoading) return <div className="p-8 text-center text-muted-foreground text-sm">{tr("loading")}...</div>;

  const currentLogo = settings.find((s) => s.setting_key === "company_logo_url")?.setting_value || "/niyamah-logo.jpg";

  const uploadLogo = async (file: File) => {
    const ext = (file.name.split(".").pop() || "png").toLowerCase();
    const path = `company-logo-${Date.now()}.${ext}`;
    const { error: upErr } = await supabase.storage.from("brand-logos").upload(path, file, { upsert: true, contentType: file.type });
    if (upErr) { toast.error(upErr.message); return; }
    const { data: pub } = supabase.storage.from("brand-logos").getPublicUrl(path);
    const url = pub.publicUrl;
    const { error: updErr } = await supabase.from("business_settings")
      .upsert({ setting_key: "company_logo_url", setting_value: url }, { onConflict: "setting_key" });
    if (updErr) { toast.error(updErr.message); return; }
    queryClient.invalidateQueries({ queryKey: ["business-settings"] });
    queryClient.invalidateQueries({ queryKey: ["company-logo"] });
    toast.success("Logo updated");
  };

  const removeLogo = async () => {
    const { error } = await supabase.from("business_settings")
      .upsert({ setting_key: "company_logo_url", setting_value: "" }, { onConflict: "setting_key" });
    if (error) { toast.error(error.message); return; }
    queryClient.invalidateQueries({ queryKey: ["business-settings"] });
    queryClient.invalidateQueries({ queryKey: ["company-logo"] });
    toast.success("Logo removed");
  };

  return (
    <div className="rounded-xl border border-border bg-card p-6">
      <h3 className="text-sm font-semibold text-foreground mb-5 flex items-center gap-2">
        <Settings className="h-4 w-4" />{tr("adminBusinessSettings")}
      </h3>

      <div className="mb-6 rounded-lg border border-border bg-muted/30 p-4">
        <label className="block text-xs font-medium text-muted-foreground mb-2">Company Logo</label>
        <div className="flex items-center gap-4 flex-wrap">
          <div className="h-20 w-20 rounded-lg bg-white border flex items-center justify-center overflow-hidden">
            <img src={currentLogo} alt="Logo" className="h-full w-full object-contain" />
          </div>
          <div className="flex items-center gap-2">
            <label className="cursor-pointer rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90">
              Upload Logo
              <input
                type="file"
                accept="image/png,image/jpeg,image/jpg,image/svg+xml,image/webp"
                className="hidden"
                onChange={(e) => { const f = e.target.files?.[0]; if (f) uploadLogo(f); e.target.value = ""; }}
              />
            </label>
            <button onClick={removeLogo} className="rounded-lg border border-border px-4 py-2 text-sm hover:bg-muted">
              Remove
            </button>
          </div>
          <p className="text-xs text-muted-foreground w-full">PNG / JPG / SVG / WebP supported. Transparent background OK. Used in sidebar, login, invoices and PDFs.</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {settingFields.map((field) => (
          <div key={field.key} className={(field as any).full ? "md:col-span-2" : ""}>
            <label className="block text-xs font-medium text-muted-foreground mb-1.5">{(field as any).label ?? tr(field.labelKey as string)}</label>
            {field.type === "textarea" ? (
              <textarea rows={2} value={getVal(field.key)} onChange={(e) => setEditValues((prev) => ({ ...prev, [field.key]: e.target.value }))}
                className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none resize-y" />
            ) : (
              <input type={field.type} value={getVal(field.key)} onChange={(e) => setEditValues((prev) => ({ ...prev, [field.key]: e.target.value }))}
                className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none" />
            )}
          </div>
        ))}
      </div>
      <div className="mt-6 flex justify-end">
        <button onClick={() => updateMutation.mutate()} disabled={Object.keys(editValues).length === 0 || updateMutation.isPending}
          className="flex items-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50">
          <Save className="h-4 w-4" />{tr("saveSettings")}
        </button>
      </div>
    </div>
  );
}

/* ─── Activity Log ─── */
function ActivityLog() {
  const { tr } = useLanguage();
  const [search, setSearch] = useState("");

  const { data: logs = [], isLoading } = useQuery({
    queryKey: ["activity-log"],
    queryFn: async () => {
      const { data, error } = await supabase.from("activity_log").select("*").order("created_at", { ascending: false }).limit(100);
      if (error) throw error;
      return data;
    },
  });

  const { data: profiles = [] } = useQuery({
    queryKey: ["admin-profiles"],
    queryFn: async () => {
      const { data, error } = await supabase.from("profiles").select("*");
      if (error) throw error;
      return data;
    },
  });

  const getProfileName = (userId: string) => profiles.find((p) => p.id === userId)?.full_name || userId.slice(0, 8);

  const filteredLogs = logs.filter((log) =>
    log.action.toLowerCase().includes(search.toLowerCase()) ||
    log.entity_type.toLowerCase().includes(search.toLowerCase()) ||
    getProfileName(log.user_id).toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="space-y-4">
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <input type="text" placeholder={tr("searchActivity")} value={search} onChange={(e) => setSearch(e.target.value)}
          className="w-full rounded-lg border border-input bg-background pl-10 pr-4 py-2.5 text-sm" />
      </div>

      <div className="rounded-xl border border-border bg-card overflow-hidden">
        {isLoading ? (
          <div className="p-8 text-center text-muted-foreground text-sm">{tr("loading")}...</div>
        ) : filteredLogs.length === 0 ? (
          <div className="p-12 text-center">
            <AlertCircle className="h-8 w-8 text-muted-foreground/40 mx-auto mb-3" />
            <p className="text-sm text-muted-foreground">{tr("noActivityLogs")}</p>
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-muted/30">
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("time")}</th>
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("userName")}</th>
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("actionLabel")}</th>
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("entityType")}</th>
                <th className="px-4 py-3 text-left font-medium text-muted-foreground">{tr("details")}</th>
              </tr>
            </thead>
            <tbody>
              {filteredLogs.map((log) => (
                <tr key={log.id} className="border-b border-border/50 hover:bg-muted/20">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
                      <Clock className="h-3 w-3" />
                      {new Date(log.created_at).toLocaleString("bn-BD")}
                    </div>
                  </td>
                  <td className="px-4 py-3 font-medium text-foreground">{getProfileName(log.user_id)}</td>
                  <td className="px-4 py-3">
                    <span className="rounded-full bg-primary/10 text-primary px-2.5 py-0.5 text-xs font-medium">{log.action}</span>
                  </td>
                  <td className="px-4 py-3 text-muted-foreground">{log.entity_type || "—"}</td>
                  <td className="px-4 py-3 text-xs text-muted-foreground max-w-[200px] truncate">
                    {log.details ? JSON.stringify(log.details) : "—"}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
