import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "wouter";
import {
  useListApps,
  getListAppsQueryKey,
  useCreateApp,
  useUpdateApp,
  useDeleteApp,
  useListServices,
  getListServicesQueryKey,
  useCreateService,
  useUpdateService,
  useDeleteService,
  useListUsers,
  getListUsersQueryKey,
  useCreateUser,
  useUpdateUser,
  useDeleteUser,
  useGetAppSettings,
  getGetAppSettingsQueryKey,
  useUpdateAppSettings,
  useGetAdminStats,
  getGetAdminStatsQueryKey,
} from "@workspace/api-client-react";
import type { App, Service, UserProfile, AppSettings, AdminStats } from "@workspace/api-client-react";
import { useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/contexts/AuthContext";
import { useUpload, type UploadResponse } from "@workspace/object-storage-web";
import { resolveServiceImageUrl } from "@/lib/image-url";
import { ArrowRight, ArrowLeft, Settings, Plus, Pencil, Trash2, Shield, Upload, Loader2, LayoutDashboard, Grid2X2, Coffee, Users as UsersIcon, Menu as MenuIcon, TrendingUp, TrendingDown, UserPlus, Activity } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import { useToast } from "@/hooks/use-toast";
import { cn } from "@/lib/utils";

type AdminSection = "dashboard" | "apps" | "services" | "users" | "settings";

type AppForm = {
  nameAr: string;
  nameEn: string;
  slug: string;
  iconName: string;
  route: string;
  color: string;
  sortOrder: number;
};

type ServiceForm = {
  nameAr: string;
  nameEn: string;
  descriptionAr: string;
  descriptionEn: string;
  price: string;
  imageUrl: string;
  isAvailable: boolean;
};

export default function AdminPage() {
  const { t, i18n } = useTranslation();
  const [, setLocation] = useLocation();
  const { user } = useAuth();
  const lang = i18n.language;
  const isRtl = lang === "ar";
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const BackIcon = isRtl ? ArrowRight : ArrowLeft;
  const isAdmin = user?.roles?.includes("admin") ?? false;

  // Redirect non-admins using useEffect to avoid violating rules of hooks
  useEffect(() => {
    if (user && !isAdmin) {
      setLocation("/");
    }
  }, [user, isAdmin, setLocation]);

  const { data: apps } = useListApps({ query: { queryKey: getListAppsQueryKey() } });
  const { data: services } = useListServices({ query: { queryKey: getListServicesQueryKey() } });
  const { data: users } = useListUsers({ query: { queryKey: getListUsersQueryKey() } });
  const { data: appSettings } = useGetAppSettings({ query: { queryKey: getGetAppSettingsQueryKey() } });
  const { data: adminStats } = useGetAdminStats({
    query: { queryKey: getGetAdminStatsQueryKey(), enabled: isAdmin },
  });

  const createApp = useCreateApp();
  const updateApp = useUpdateApp();
  const deleteApp = useDeleteApp();
  const createService = useCreateService();
  const updateService = useUpdateService();
  const deleteService = useDeleteService();
  const createUser = useCreateUser();
  const updateUser = useUpdateUser();
  const deleteUser = useDeleteUser();

  const [editingApp, setEditingApp] = useState<{ id?: number; form: AppForm } | null>(null);
  const [editingService, setEditingService] = useState<{ id?: number; form: ServiceForm } | null>(null);
  const [newUserForm, setNewUserForm] = useState<{ username: string; email: string; password: string } | null>(null);
  const [section, setSection] = useState<AdminSection>("dashboard");
  const [mobileNavOpen, setMobileNavOpen] = useState(false);

  const navItems: { key: AdminSection; label: string; Icon: typeof LayoutDashboard }[] = [
    { key: "dashboard", label: t("admin.nav.dashboard"), Icon: LayoutDashboard },
    { key: "apps", label: t("admin.nav.apps"), Icon: Grid2X2 },
    { key: "services", label: t("admin.nav.services"), Icon: Coffee },
    { key: "users", label: t("admin.nav.users"), Icon: UsersIcon },
    { key: "settings", label: t("admin.nav.settings"), Icon: Settings },
  ];

  const renderNavList = (onSelect?: () => void) => (
    <nav className="flex flex-col gap-1">
      {navItems.map(({ key, label, Icon }) => {
        const active = section === key;
        return (
          <button
            key={key}
            onClick={() => {
              setSection(key);
              onSelect?.();
            }}
            className={cn(
              "flex items-center gap-3 w-full px-3 py-2.5 rounded-xl text-sm transition-all text-start relative",
              active
                ? "bg-primary text-primary-foreground font-semibold shadow-md shadow-primary/20"
                : "text-foreground/70 hover:bg-slate-100 hover:text-foreground",
            )}
          >
            <Icon size={18} className="shrink-0" />
            <span className="truncate">{label}</span>
          </button>
        );
      })}
    </nav>
  );

  const emptyAppForm: AppForm = { nameAr: "", nameEn: "", slug: "", iconName: "Grid2X2", route: "/", color: "#6366f1", sortOrder: 0 };
  const emptyServiceForm: ServiceForm = { nameAr: "", nameEn: "", descriptionAr: "", descriptionEn: "", price: "0.00", imageUrl: "", isAvailable: true };

  const handleSaveApp = () => {
    if (!editingApp) return;
    if (editingApp.id) {
      updateApp.mutate(
        { id: editingApp.id, data: editingApp.form },
        {
          onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: getListAppsQueryKey() });
            setEditingApp(null);
            toast({ title: t("common.success") });
          },
        },
      );
    } else {
      createApp.mutate(
        { data: editingApp.form },
        {
          onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: getListAppsQueryKey() });
            setEditingApp(null);
            toast({ title: t("common.success") });
          },
        },
      );
    }
  };

  const handleSaveService = () => {
    if (!editingService) return;
    if (editingService.id) {
      updateService.mutate(
        { id: editingService.id, data: editingService.form },
        {
          onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: getListServicesQueryKey() });
            setEditingService(null);
            toast({ title: t("common.success") });
          },
        },
      );
    } else {
      createService.mutate(
        { data: editingService.form },
        {
          onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: getListServicesQueryKey() });
            setEditingService(null);
            toast({ title: t("common.success") });
          },
        },
      );
    }
  };

  const handleCreateUser = () => {
    if (!newUserForm) return;
    createUser.mutate(
      { data: { username: newUserForm.username, email: newUserForm.email, password: newUserForm.password } },
      {
        onSuccess: () => {
          queryClient.invalidateQueries({ queryKey: getListUsersQueryKey() });
          setNewUserForm(null);
          toast({ title: t("common.success") });
        },
      },
    );
  };

  if (!user || !isAdmin) return null;

  return (
    <div className="min-h-screen os-bg flex flex-col">
      {/* Header */}
      <div className="glass-panel border-b border-slate-200/70 px-4 py-4 flex items-center gap-3 sticky top-0 z-10">
        <button
          onClick={() => setLocation("/")}
          className="p-2 rounded-xl hover:bg-slate-100 text-muted-foreground hover:text-foreground transition-colors"
        >
          <BackIcon size={20} />
        </button>
        <div className="flex items-center gap-2 flex-1 min-w-0">
          <Settings size={20} className="text-red-400 shrink-0" />
          <h1 className="text-lg font-semibold text-foreground truncate">{t("admin.title")}</h1>
        </div>
        <Sheet open={mobileNavOpen} onOpenChange={setMobileNavOpen}>
          <SheetTrigger asChild>
            <button
              className="md:hidden p-2 rounded-xl hover:bg-slate-100 text-muted-foreground hover:text-foreground transition-colors"
              aria-label={t("admin.nav.menu")}
            >
              <MenuIcon size={20} />
            </button>
          </SheetTrigger>
          <SheetContent side={isRtl ? "right" : "left"} className="w-full sm:w-72 p-4">
            <div className="flex items-center gap-2 mb-4 mt-2">
              <Settings size={18} className="text-red-400" />
              <h2 className="font-semibold text-foreground">{t("admin.title")}</h2>
            </div>
            {renderNavList(() => setMobileNavOpen(false))}
          </SheetContent>
        </Sheet>
      </div>

      {/* Edit App Modal */}
      {editingApp && (
        <div className="fixed inset-0 bg-slate-900/30 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="glass-panel rounded-3xl p-6 w-full max-w-sm space-y-4 max-h-[90vh] overflow-y-auto">
            <h2 className="font-semibold text-foreground">
              {editingApp.id ? t("admin.editApp") : t("admin.addApp")}
            </h2>
            {(
              [
                { field: "nameAr", label: t("admin.appNameAr") },
                { field: "nameEn", label: t("admin.appNameEn") },
                { field: "slug", label: t("admin.appSlug") },
                { field: "iconName", label: t("admin.appIcon") },
                { field: "route", label: t("admin.appRoute") },
                { field: "color", label: t("admin.appColor") },
              ] as { field: keyof AppForm; label: string }[]
            ).map(({ field, label }) => (
              <div key={field} className="space-y-1">
                <Label>{label}</Label>
                <Input
                  value={String(editingApp.form[field])}
                  onChange={(e) => setEditingApp({ ...editingApp, form: { ...editingApp.form, [field]: e.target.value } })}
                  className="bg-white/70 border-slate-200"
                />
              </div>
            ))}
            <div className="flex gap-2">
              <Button variant="outline" className="flex-1" onClick={() => setEditingApp(null)}>{t("common.cancel")}</Button>
              <Button className="flex-1" onClick={handleSaveApp}>{t("common.save")}</Button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Service Modal */}
      {editingService && (
        <div className="fixed inset-0 bg-slate-900/30 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="glass-panel rounded-3xl p-6 w-full max-w-sm space-y-4 max-h-[90vh] overflow-y-auto">
            <h2 className="font-semibold text-foreground">
              {editingService.id ? t("admin.editService") : t("admin.addService")}
            </h2>
            {(
              [
                { field: "nameAr", label: t("admin.serviceNameAr") },
                { field: "nameEn", label: t("admin.serviceNameEn") },
                { field: "descriptionAr", label: t("admin.serviceDescriptionAr") },
                { field: "descriptionEn", label: t("admin.serviceDescriptionEn") },
                { field: "price", label: t("admin.servicePrice") },
              ] as { field: keyof ServiceForm; label: string }[]
            ).map(({ field, label }) => (
              <div key={field} className="space-y-1">
                <Label>{label}</Label>
                <Input
                  value={String(editingService.form[field])}
                  onChange={(e) => setEditingService({ ...editingService, form: { ...editingService.form, [field]: e.target.value } })}
                  className="bg-white/70 border-slate-200"
                />
              </div>
            ))}

            <div className="space-y-2">
              <Label>{t("admin.serviceImage")}</Label>
              <ServiceImageUploader
                value={editingService.form.imageUrl}
                onChange={(url) =>
                  setEditingService({
                    ...editingService,
                    form: { ...editingService.form, imageUrl: url },
                  })
                }
              />
            </div>
            <div className="flex items-center justify-between">
              <Label>{t("admin.serviceAvailable")}</Label>
              <Switch
                checked={editingService.form.isAvailable}
                onCheckedChange={(v) => setEditingService({ ...editingService, form: { ...editingService.form, isAvailable: v } })}
              />
            </div>
            <div className="flex gap-2">
              <Button variant="outline" className="flex-1" onClick={() => setEditingService(null)}>{t("common.cancel")}</Button>
              <Button className="flex-1" onClick={handleSaveService}>{t("common.save")}</Button>
            </div>
          </div>
        </div>
      )}

      {/* Create User Modal */}
      {newUserForm && (
        <div className="fixed inset-0 bg-slate-900/30 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="glass-panel rounded-3xl p-6 w-full max-w-sm space-y-4">
            <h2 className="font-semibold text-foreground">{t("admin.addUser")}</h2>
            <div className="space-y-1">
              <Label>{t("admin.username")}</Label>
              <Input
                value={newUserForm.username}
                onChange={(e) => setNewUserForm({ ...newUserForm, username: e.target.value })}
                className="bg-white/70 border-slate-200"
              />
            </div>
            <div className="space-y-1">
              <Label>{t("admin.email")}</Label>
              <Input
                type="email"
                value={newUserForm.email}
                onChange={(e) => setNewUserForm({ ...newUserForm, email: e.target.value })}
                className="bg-white/70 border-slate-200"
              />
            </div>
            <div className="space-y-1">
              <Label>{t("admin.password")}</Label>
              <Input
                type="password"
                value={newUserForm.password}
                onChange={(e) => setNewUserForm({ ...newUserForm, password: e.target.value })}
                className="bg-white/70 border-slate-200"
              />
            </div>
            <div className="flex gap-2">
              <Button variant="outline" className="flex-1" onClick={() => setNewUserForm(null)}>{t("common.cancel")}</Button>
              <Button className="flex-1" onClick={handleCreateUser}>{t("common.save")}</Button>
            </div>
          </div>
        </div>
      )}

      <div className="flex-1 flex w-full">
        {/* Sidebar (desktop) */}
        <aside className="hidden md:flex flex-col w-64 shrink-0 border-e border-slate-200/70 bg-white/70 backdrop-blur-md">
          <div className="sticky top-[73px] p-4 space-y-4">
            <div className="flex items-center gap-2 px-2 pb-3 border-b border-slate-200/70">
              <Shield size={18} className="text-primary" />
              <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                {t("admin.nav.menu")}
              </span>
            </div>
            {renderNavList()}
          </div>
        </aside>

        {/* Main content */}
        <div className="flex-1 min-w-0 p-4 pb-8">
          {section === "dashboard" && (
            <DashboardSection
              apps={apps}
              services={services}
              users={users}
              appSettings={appSettings}
              adminStats={adminStats}
              lang={lang}
            />
          )}

          {section === "apps" && (
          <div className="space-y-3">
            <div className="flex justify-end">
              <Button size="sm" onClick={() => setEditingApp({ form: emptyAppForm })}>
                <Plus size={14} className="me-1" />
                {t("admin.addApp")}
              </Button>
            </div>
            {apps?.map((app) => (
              <div key={app.id} className="glass-panel rounded-2xl p-4 flex items-center justify-between gap-3">
                <div className="flex items-center gap-3 min-w-0">
                  <div
                    className="w-8 h-8 rounded-lg shrink-0"
                    style={{ backgroundColor: `${app.color}40` }}
                  />
                  <div className="min-w-0">
                    <div className="font-medium text-sm text-foreground truncate">
                      {lang === "ar" ? app.nameAr : app.nameEn}
                    </div>
                    <div className="text-xs text-muted-foreground">{app.route}</div>
                  </div>
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  <Switch
                    checked={app.isActive}
                    onCheckedChange={(v) => {
                      updateApp.mutate(
                        { id: app.id, data: { isActive: v } },
                        { onSuccess: () => queryClient.invalidateQueries({ queryKey: getListAppsQueryKey() }) },
                      );
                    }}
                  />
                  <button
                    onClick={() => setEditingApp({
                      id: app.id,
                      form: {
                        nameAr: app.nameAr ?? "",
                        nameEn: app.nameEn ?? "",
                        slug: app.slug ?? "",
                        iconName: app.iconName ?? "Grid2X2",
                        route: app.route ?? "/",
                        color: app.color ?? "#6366f1",
                        sortOrder: app.sortOrder ?? 0,
                      },
                    })}
                    className="p-1.5 hover:bg-slate-100 rounded-lg text-muted-foreground hover:text-foreground"
                  >
                    <Pencil size={14} />
                  </button>
                  <button
                    onClick={() => {
                      if (confirm(t("admin.deleteConfirm"))) {
                        deleteApp.mutate(
                          { id: app.id },
                          { onSuccess: () => queryClient.invalidateQueries({ queryKey: getListAppsQueryKey() }) },
                        );
                      }
                    }}
                    className="p-1.5 hover:bg-destructive/20 rounded-lg text-muted-foreground hover:text-destructive"
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              </div>
            ))}
          </div>
          )}

          {section === "services" && (
          <div className="space-y-3">
            <div className="flex justify-end">
              <Button size="sm" onClick={() => setEditingService({ form: emptyServiceForm })}>
                <Plus size={14} className="me-1" />
                {t("admin.addService")}
              </Button>
            </div>
            {services?.map((service) => (
              <div key={service.id} className="glass-panel rounded-2xl p-4 flex items-center justify-between gap-3">
                <div className="min-w-0 flex-1">
                  <div className="font-medium text-sm text-foreground truncate">
                    {lang === "ar" ? service.nameAr : service.nameEn}
                  </div>
                  <div className="text-xs text-muted-foreground">{service.price}</div>
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  <Switch
                    checked={service.isAvailable}
                    onCheckedChange={(v) => {
                      updateService.mutate(
                        { id: service.id, data: { isAvailable: v } },
                        { onSuccess: () => queryClient.invalidateQueries({ queryKey: getListServicesQueryKey() }) },
                      );
                    }}
                  />
                  <button
                    onClick={() => setEditingService({
                      id: service.id,
                      form: {
                        nameAr: service.nameAr ?? "",
                        nameEn: service.nameEn ?? "",
                        descriptionAr: service.descriptionAr ?? "",
                        descriptionEn: service.descriptionEn ?? "",
                        price: service.price ?? "0.00",
                        imageUrl: service.imageUrl ?? "",
                        isAvailable: service.isAvailable ?? true,
                      },
                    })}
                    className="p-1.5 hover:bg-slate-100 rounded-lg text-muted-foreground hover:text-foreground"
                  >
                    <Pencil size={14} />
                  </button>
                  <button
                    onClick={() => {
                      if (confirm(t("admin.deleteConfirm"))) {
                        deleteService.mutate(
                          { id: service.id },
                          { onSuccess: () => queryClient.invalidateQueries({ queryKey: getListServicesQueryKey() }) },
                        );
                      }
                    }}
                    className="p-1.5 hover:bg-destructive/20 rounded-lg text-muted-foreground hover:text-destructive"
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              </div>
            ))}
          </div>
          )}

          {section === "users" && (
          <div className="space-y-3">
            <Button
              size="sm"
              className="w-full"
              onClick={() => setNewUserForm({ username: "", email: "", password: "" })}
            >
              <Plus size={14} className="mr-1" />
              {t("admin.addUser")}
            </Button>
            {users?.map((u) => (
              <div key={u.id} className="glass-panel rounded-2xl p-4 flex items-center justify-between gap-3">
                <div className="min-w-0 flex-1">
                  <div className="font-medium text-sm text-foreground">{u.username}</div>
                  <div className="text-xs text-muted-foreground">{u.email}</div>
                  <div className="flex flex-wrap gap-1 mt-1">
                    {u.roles?.map((role) => (
                      <span key={role} className="text-xs px-2 py-0.5 rounded-full bg-primary/20 text-primary">
                        {role}
                      </span>
                    ))}
                  </div>
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  <Switch
                    checked={u.isActive}
                    onCheckedChange={(v) => {
                      updateUser.mutate(
                        { id: u.id, data: { isActive: v } },
                        { onSuccess: () => queryClient.invalidateQueries({ queryKey: getListUsersQueryKey() }) },
                      );
                    }}
                  />
                  {u.id !== user?.id && (
                    <button
                      onClick={() => {
                        if (confirm(t("admin.deleteConfirm"))) {
                          deleteUser.mutate(
                            { id: u.id },
                            { onSuccess: () => queryClient.invalidateQueries({ queryKey: getListUsersQueryKey() }) },
                          );
                        }
                      }}
                      className="p-1.5 hover:bg-destructive/20 rounded-lg text-muted-foreground hover:text-destructive"
                    >
                      <Trash2 size={14} />
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
          )}

          {section === "settings" && (
            <div className="space-y-3">
              <SiteSettingsPanel />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function SiteSettingsPanel() {
  const { t } = useTranslation();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const { data } = useGetAppSettings({ query: { queryKey: getGetAppSettingsQueryKey() } });
  const update = useUpdateAppSettings();
  const [form, setForm] = useState({
    siteNameAr: "",
    siteNameEn: "",
    registrationOpen: true,
    footerTextAr: "",
    footerTextEn: "",
  });

  useEffect(() => {
    if (data) setForm({
      siteNameAr: data.siteNameAr,
      siteNameEn: data.siteNameEn,
      registrationOpen: data.registrationOpen,
      footerTextAr: data.footerTextAr,
      footerTextEn: data.footerTextEn,
    });
  }, [data]);

  const handleSave = () => {
    update.mutate(
      { data: form },
      {
        onSuccess: () => {
          queryClient.invalidateQueries({ queryKey: getGetAppSettingsQueryKey() });
          toast({ title: t("common.success") });
        },
        onError: () => toast({ title: t("common.error"), variant: "destructive" }),
      },
    );
  };

  return (
    <div className="glass-panel rounded-2xl p-4 space-y-4">
      <div className="space-y-1">
        <Label>{t("admin.siteNameAr")}</Label>
        <Input
          value={form.siteNameAr}
          onChange={(e) => setForm({ ...form, siteNameAr: e.target.value })}
          className="bg-white/70 border-slate-200"
          dir="rtl"
        />
      </div>
      <div className="space-y-1">
        <Label>{t("admin.siteNameEn")}</Label>
        <Input
          value={form.siteNameEn}
          onChange={(e) => setForm({ ...form, siteNameEn: e.target.value })}
          className="bg-white/70 border-slate-200"
          dir="ltr"
        />
      </div>
      <div className="space-y-1">
        <Label>{t("admin.footerTextAr")}</Label>
        <Input
          value={form.footerTextAr}
          onChange={(e) => setForm({ ...form, footerTextAr: e.target.value })}
          className="bg-white/70 border-slate-200"
          dir="rtl"
        />
      </div>
      <div className="space-y-1">
        <Label>{t("admin.footerTextEn")}</Label>
        <Input
          value={form.footerTextEn}
          onChange={(e) => setForm({ ...form, footerTextEn: e.target.value })}
          className="bg-white/70 border-slate-200"
          dir="ltr"
        />
      </div>
      <div className="flex items-center justify-between pt-2">
        <div>
          <Label className="font-medium">{t("admin.registrationOpen")}</Label>
          <p className="text-xs text-muted-foreground">{t("admin.registrationOpenHint")}</p>
        </div>
        <Switch
          checked={form.registrationOpen}
          onCheckedChange={(v) => setForm({ ...form, registrationOpen: v })}
        />
      </div>
      <Button onClick={handleSave} disabled={update.isPending} className="w-full">
        {update.isPending ? t("common.loading") : t("common.save")}
      </Button>
    </div>
  );
}

function ServiceImageUploader({
  value,
  onChange,
}: {
  value: string;
  onChange: (url: string) => void;
}) {
  const { t } = useTranslation();
  const { toast } = useToast();
  const { uploadFile, isUploading, progress } = useUpload({
    onSuccess: (resp: UploadResponse) => {
      onChange(resp.objectPath);
    },
    onError: (err: Error) => {
      toast({ title: t("admin.uploadFailed"), description: err.message, variant: "destructive" });
    },
  });

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2">
        <label className="cursor-pointer">
          <input
            type="file"
            accept="image/*"
            disabled={isUploading}
            className="hidden"
            onChange={(e) => {
              const file = e.target.files?.[0];
              if (file) {
                void uploadFile(file);
              }
              e.currentTarget.value = "";
            }}
          />
          <span className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-slate-200 bg-white text-sm text-slate-700 hover:bg-slate-50 transition">
            {isUploading ? <Loader2 size={16} className="animate-spin" /> : <Upload size={16} />}
            {isUploading
              ? `${t("admin.uploading")} ${progress}%`
              : value
                ? t("admin.replaceImage")
                : t("admin.uploadImage")}
          </span>
        </label>
        {value && !isUploading && (
          <button
            type="button"
            onClick={() => onChange("")}
            className="px-3 py-2 rounded-lg border border-slate-200 bg-white text-sm text-slate-500 hover:text-destructive hover:border-destructive/40"
          >
            <Trash2 size={14} />
          </button>
        )}
      </div>
      {value && (
        <div className="rounded-xl overflow-hidden border border-slate-200 bg-slate-50">
          <img
            src={resolveServiceImageUrl(value) ?? ""}
            alt=""
            className="w-full h-32 object-cover"
            onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = "none"; }}
          />
        </div>
      )}
    </div>
  );
}

function DashboardSection({
  apps,
  services,
  users,
  appSettings,
  adminStats,
  lang,
}: {
  apps: App[] | undefined;
  services: Service[] | undefined;
  users: UserProfile[] | undefined;
  appSettings: AppSettings | undefined;
  adminStats: AdminStats | undefined;
  lang: string;
}) {
  const { t } = useTranslation();

  const totalApps = apps?.length ?? 0;
  const totalServices = services?.length ?? 0;
  const totalUsers = users?.length ?? 0;
  const registrationOpen = appSettings?.registrationOpen ?? false;

  const latestUser = users
    ? [...users].sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""))[0]
    : undefined;
  const latestApp = apps
    ? [...apps].sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""))[0]
    : undefined;

  const dateLocale = lang === "ar" ? "ar" : "en";
  const formatDate = (iso?: string) => {
    if (!iso) return "";
    try {
      return new Date(iso).toLocaleDateString(dateLocale, {
        year: "numeric",
        month: "short",
        day: "numeric",
      });
    } catch {
      return "";
    }
  };

  const stats: { label: string; value: string; Icon: typeof Grid2X2; tint: string }[] = [
    { label: t("admin.dashboard.totalApps"), value: String(totalApps), Icon: Grid2X2, tint: "text-indigo-500 bg-indigo-100/70" },
    { label: t("admin.dashboard.totalServices"), value: String(totalServices), Icon: Coffee, tint: "text-amber-600 bg-amber-100/70" },
    { label: t("admin.dashboard.totalUsers"), value: String(totalUsers), Icon: UsersIcon, tint: "text-emerald-600 bg-emerald-100/70" },
    {
      label: t("admin.dashboard.registration"),
      value: registrationOpen ? t("admin.dashboard.open") : t("admin.dashboard.closed"),
      Icon: Shield,
      tint: registrationOpen ? "text-green-600 bg-green-100/70" : "text-rose-600 bg-rose-100/70",
    },
  ];

  const newUsers = adminStats?.newUsersLast7Days ?? 0;
  const prevUsers = adminStats?.newUsersPrev7Days ?? 0;
  const userDelta = newUsers - prevUsers;
  const userDeltaPct = prevUsers > 0 ? Math.round((userDelta / prevUsers) * 100) : null;
  const activeServices = adminStats?.activeServices ?? 0;
  const inactiveServices = adminStats?.inactiveServices ?? 0;
  const signups = adminStats?.signupsByDay ?? [];
  const maxSignup = Math.max(1, ...signups.map((s) => s.count));
  const dayLabel = (iso: string) => {
    try {
      return new Date(iso + "T00:00:00Z").toLocaleDateString(dateLocale, {
        weekday: "short",
      });
    } catch {
      return "";
    }
  };

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
        {stats.map(({ label, value, Icon, tint }) => (
          <div key={label} className="glass-panel rounded-2xl p-4 flex items-center gap-3">
            <div className={cn("w-10 h-10 rounded-xl flex items-center justify-center shrink-0", tint)}>
              <Icon size={20} />
            </div>
            <div className="min-w-0">
              <div className="text-xs text-muted-foreground truncate">{label}</div>
              <div className="text-xl font-semibold text-foreground truncate">{value}</div>
            </div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <div className="glass-panel rounded-2xl p-4 flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0 text-sky-600 bg-sky-100/70">
            <UserPlus size={20} />
          </div>
          <div className="min-w-0 flex-1">
            <div className="text-xs text-muted-foreground truncate">{t("admin.dashboard.newUsers7d")}</div>
            <div className="flex items-baseline gap-2">
              <div className="text-xl font-semibold text-foreground">{newUsers}</div>
              {userDelta !== 0 && (
                <div
                  className={cn(
                    "text-xs flex items-center gap-0.5 font-medium",
                    userDelta > 0 ? "text-emerald-600" : "text-rose-600",
                  )}
                >
                  {userDelta > 0 ? <TrendingUp size={12} /> : <TrendingDown size={12} />}
                  {userDeltaPct !== null
                    ? `${userDelta > 0 ? "+" : ""}${userDeltaPct}%`
                    : `${userDelta > 0 ? "+" : ""}${userDelta}`}
                </div>
              )}
            </div>
            <div className="text-[11px] text-muted-foreground mt-0.5">
              {t("admin.dashboard.vsPrev7d", { count: prevUsers })}
            </div>
          </div>
        </div>

        <div className="glass-panel rounded-2xl p-4 flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0 text-amber-600 bg-amber-100/70">
            <Activity size={20} />
          </div>
          <div className="min-w-0 flex-1">
            <div className="text-xs text-muted-foreground truncate">{t("admin.dashboard.activeServices")}</div>
            <div className="flex items-baseline gap-2">
              <div className="text-xl font-semibold text-foreground">{activeServices}</div>
              <div className="text-xs text-muted-foreground">
                / {activeServices + inactiveServices}
              </div>
            </div>
            <div className="text-[11px] text-muted-foreground mt-0.5">
              {t("admin.dashboard.inactiveServices", { count: inactiveServices })}
            </div>
          </div>
        </div>
      </div>

      <div className="glass-panel rounded-2xl p-4 space-y-3">
        <div className="flex items-center justify-between">
          <div className="text-sm font-semibold text-foreground">
            {t("admin.dashboard.signupsTrend")}
          </div>
          <div className="text-xs text-muted-foreground">{t("admin.dashboard.last7Days")}</div>
        </div>
        <div className="flex items-end justify-between gap-1.5 h-28 px-1" dir="ltr">
          {signups.map((s) => {
            const heightPct = (s.count / maxSignup) * 100;
            return (
              <div key={s.date} className="flex-1 flex flex-col items-center gap-1.5 min-w-0">
                <div className="text-[10px] font-medium text-foreground leading-none">{s.count}</div>
                <div className="w-full flex-1 flex items-end">
                  <div
                    className="w-full rounded-t-md bg-gradient-to-t from-primary/40 to-primary transition-all"
                    style={{ height: `${Math.max(heightPct, s.count > 0 ? 6 : 2)}%` }}
                  />
                </div>
                <div className="text-[10px] text-muted-foreground truncate w-full text-center">
                  {dayLabel(s.date)}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div className="glass-panel rounded-2xl p-4 space-y-3">
        <div className="text-sm font-semibold text-foreground">
          {t("admin.dashboard.recentActivity")}
        </div>
        <div className="space-y-2">
          <div className="flex items-center gap-3 p-3 rounded-xl bg-white/60 border border-slate-200/60">
            <div className="w-9 h-9 rounded-lg flex items-center justify-center bg-emerald-100/70 text-emerald-600 shrink-0">
              <UsersIcon size={16} />
            </div>
            <div className="min-w-0 flex-1">
              <div className="text-xs text-muted-foreground">{t("admin.dashboard.latestUser")}</div>
              <div className="text-sm font-medium text-foreground truncate">
                {latestUser?.username ?? t("admin.dashboard.none")}
              </div>
            </div>
            {latestUser?.createdAt && (
              <div className="text-xs text-muted-foreground shrink-0">{formatDate(latestUser.createdAt)}</div>
            )}
          </div>
          <div className="flex items-center gap-3 p-3 rounded-xl bg-white/60 border border-slate-200/60">
            <div className="w-9 h-9 rounded-lg flex items-center justify-center bg-indigo-100/70 text-indigo-600 shrink-0">
              <Grid2X2 size={16} />
            </div>
            <div className="min-w-0 flex-1">
              <div className="text-xs text-muted-foreground">{t("admin.dashboard.latestApp")}</div>
              <div className="text-sm font-medium text-foreground truncate">
                {latestApp ? (lang === "ar" ? latestApp.nameAr : latestApp.nameEn) : t("admin.dashboard.none")}
              </div>
            </div>
            {latestApp?.createdAt && (
              <div className="text-xs text-muted-foreground shrink-0">{formatDate(latestApp.createdAt)}</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
