import { useEffect, useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom";
import {
  TextInput,
  Textarea,
  Switch,
  Stack,
  Paper,
  Text,
  Loader,
  Group,
  MultiSelect,
  Badge,
  SegmentedControl,
  Select,
} from "@mantine/core";
import { alert } from "@app/components/toast";
import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";
import { useRestartServer } from "@app/components/shared/config/useRestartServer";
import { useAdminSettings } from "@app/hooks/useAdminSettings";
import { useSettingsDirty } from "@app/hooks/useSettingsDirty";
import PendingBadge from "@app/components/shared/config/PendingBadge";
import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";
import apiClient from "@app/services/apiClient";
import { useLoginRequired } from "@app/hooks/useLoginRequired";
import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";
import { usePreferences } from "@app/contexts/PreferencesContext";
import { useUnsavedChanges } from "@app/contexts/UnsavedChangesContext";
import {
  supportedLanguages,
  toUnderscoreFormat,
  toUnderscoreLanguages,
} from "@app/i18n";
import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";

interface GeneralSettingsData {
  ui: {
    appNameNavbar?: string;
    languages?: string[];
    logoStyle?: "modern" | "classic";
    hideDisabledTools?: {
      googleDrive?: boolean;
      mobileQRScanner?: boolean;
    };
  };
  system: {
    defaultLocale?: string;
    showUpdate?: boolean;
    showUpdateOnlyAdmin?: boolean;
    customHTMLFiles?: boolean;
    fileUploadLimit?: string;
    frontendUrl?: string;
  };
  customPaths?: {
    pipeline?: {
      pipelineDir?: string;
      watchedFoldersDir?: string;
      watchedFoldersDirs?: string[];
      finishedFoldersDir?: string;
    };
    operations?: {
      weasyprint?: string;
      unoconvert?: string;
    };
  };
  customMetadata?: {
    autoUpdateMetadata?: boolean;
    author?: string;
    creator?: string;
    producer?: string;
  };
}

export default function AdminGeneralSection() {
  const { t } = useTranslation();
  const location = useLocation();
  const navigate = useNavigate();
  const { loginEnabled, validateLoginEnabled } = useLoginRequired();
  const {
    restartModalOpened,
    showRestartModal,
    closeRestartModal,
    restartServer,
  } = useRestartServer();
  const { preferences, updatePreference } = usePreferences();
  const { markClean } = useUnsavedChanges();
  const languageOptions = useMemo(
    () =>
      Object.entries(supportedLanguages)
        .map(([code, label]) => ({
          value: toUnderscoreFormat(code),
          label: `${label} (${code})`,
        }))
        .sort((a, b) => a.label.localeCompare(b.label)),
    [],
  );
  const parseWatchedFoldersInput = useCallback((value: string) => {
    const paths = value
      .split(/[\n,;]+/)
      .map((entry) => entry.trim())
      .filter(Boolean);

    // Deduplicate paths (case-sensitive, exact match)
    const uniquePaths = Array.from(new Set(paths));

    return uniquePaths;
  }, []);

  const {
    settings,
    setSettings,
    loading,
    saving,
    fetchSettings,
    saveSettings,
    isFieldPending,
  } = useAdminSettings<GeneralSettingsData>({
    sectionName: "general",
    fetchTransformer: async (): Promise<
      GeneralSettingsData & { _pending?: Record<string, unknown> }
    > => {
      const [uiResponse, systemResponse, premiumResponse] = await Promise.all([
        apiClient.get("/api/v1/admin/settings/section/ui"),
        apiClient.get("/api/v1/admin/settings/section/system"),
        apiClient.get("/api/v1/admin/settings/section/premium"),
      ]);

      const ui = { ...(uiResponse.data || {}) };
      const system = { ...(systemResponse.data || {}) };
      const premium = { ...(premiumResponse.data || {}) };

      ui.languages = Array.isArray(ui.languages)
        ? toUnderscoreLanguages(ui.languages)
        : [];

      const pipelinePaths = system.customPaths?.pipeline || {};
      const watchedFoldersDirs = Array.isArray(pipelinePaths.watchedFoldersDirs)
        ? pipelinePaths.watchedFoldersDirs
        : [];
      const normalizedWatchedFoldersDirs =
        watchedFoldersDirs.length > 0
          ? watchedFoldersDirs
          : pipelinePaths.watchedFoldersDir
            ? [pipelinePaths.watchedFoldersDir]
            : [];

      const result: GeneralSettingsData & {
        _pending?: Record<string, unknown>;
      } = {
        ui,
        system,
        customPaths: {
          ...(system.customPaths || {}),
          pipeline: {
            ...pipelinePaths,
            pipelineDir: pipelinePaths.pipelineDir || "",
            watchedFoldersDir: pipelinePaths.watchedFoldersDir || "",
            watchedFoldersDirs: normalizedWatchedFoldersDirs,
            finishedFoldersDir: pipelinePaths.finishedFoldersDir || "",
          },
          operations: {
            ...(system.customPaths?.operations || {}),
            weasyprint: system.customPaths?.operations?.weasyprint || "",
            unoconvert: system.customPaths?.operations?.unoconvert || "",
          },
        },
        customMetadata: premium.proFeatures?.customMetadata || {
          autoUpdateMetadata: false,
          author: "",
          creator: "",
          producer: "",
        },
      };

      // Merge pending blocks from all three endpoints
      const pendingBlock: Record<string, unknown> = {};
      if (ui._pending) {
        pendingBlock.ui = ui._pending;
      }
      if (system._pending) {
        pendingBlock.system = system._pending;
      }
      if (system._pending?.customPaths) {
        pendingBlock.customPaths = system._pending.customPaths;
      }
      if (premium._pending?.proFeatures?.customMetadata) {
        pendingBlock.customMetadata =
          premium._pending.proFeatures.customMetadata;
      }

      if (Object.keys(pendingBlock).length > 0) {
        result._pending = pendingBlock;
      }

      return result;
    },
    saveTransformer: (settings: GeneralSettingsData) => {
      const deltaSettings: Record<string, unknown> = {
        // UI settings
        "ui.appNameNavbar": settings.ui?.appNameNavbar,
        "ui.languages": settings.ui?.languages,
        "ui.logoStyle": settings.ui?.logoStyle,
        "ui.hideDisabledTools.googleDrive":
          settings.ui?.hideDisabledTools?.googleDrive,
        "ui.hideDisabledTools.mobileQRScanner":
          settings.ui?.hideDisabledTools?.mobileQRScanner,
        // System settings
        "system.defaultLocale": settings.system?.defaultLocale,
        "system.showUpdate": settings.system?.showUpdate,
        "system.showUpdateOnlyAdmin": settings.system?.showUpdateOnlyAdmin,
        "system.customHTMLFiles": settings.system?.customHTMLFiles,
        "system.fileUploadLimit": settings.system?.fileUploadLimit,
        "system.frontendUrl": settings.system?.frontendUrl,
        // Premium custom metadata
        "premium.proFeatures.customMetadata.autoUpdateMetadata":
          settings.customMetadata?.autoUpdateMetadata,
        "premium.proFeatures.customMetadata.author":
          settings.customMetadata?.author,
        "premium.proFeatures.customMetadata.creator":
          settings.customMetadata?.creator,
        "premium.proFeatures.customMetadata.producer":
          settings.customMetadata?.producer,
      };

      if (settings.customPaths) {
        deltaSettings["system.customPaths.pipeline.pipelineDir"] =
          settings.customPaths?.pipeline?.pipelineDir;
        deltaSettings["system.customPaths.pipeline.watchedFoldersDir"] =
          settings.customPaths?.pipeline?.watchedFoldersDir;
        deltaSettings["system.customPaths.pipeline.watchedFoldersDirs"] =
          settings.customPaths?.pipeline?.watchedFoldersDirs;
        deltaSettings["system.customPaths.pipeline.finishedFoldersDir"] =
          settings.customPaths?.pipeline?.finishedFoldersDir;
        deltaSettings["system.customPaths.operations.weasyprint"] =
          settings.customPaths?.operations?.weasyprint;
        deltaSettings["system.customPaths.operations.unoconvert"] =
          settings.customPaths?.operations?.unoconvert;
      }

      return {
        sectionData: {},
        deltaSettings,
      };
    },
  });

  const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(
    settings,
    loading,
  );

  const selectedLanguages = useMemo(
    () => toUnderscoreLanguages(settings.ui?.languages || []),
    [settings.ui?.languages],
  );
  const watchedFoldersInput = useMemo(
    () => (settings.customPaths?.pipeline?.watchedFoldersDirs || []).join("\n"),
    [settings.customPaths?.pipeline?.watchedFoldersDirs],
  );

  const watchedFoldersValidation = useMemo(() => {
    const paths = settings.customPaths?.pipeline?.watchedFoldersDirs || [];
    const finishedPath =
      settings.customPaths?.pipeline?.finishedFoldersDir || "";
    const warnings: string[] = [];

    // Normalize paths for comparison (handle both Windows and Unix paths)
    const normalizePath = (p: string) =>
      p.replace(/\\/g, "/").replace(/\/+$/, "");

    // Check for overlapping watched folders
    if (paths.length >= 2) {
      for (let i = 0; i < paths.length; i++) {
        for (let j = i + 1; j < paths.length; j++) {
          const path1 = normalizePath(paths[i]);
          const path2 = normalizePath(paths[j]);

          if (path1 === path2) {
            warnings.push(`Duplicate path detected: '${paths[i]}'`);
          } else if (path1.startsWith(path2 + "/")) {
            warnings.push(
              `'${paths[i]}' is nested inside '${paths[j]}' - may cause duplicate processing`,
            );
          } else if (path2.startsWith(path1 + "/")) {
            warnings.push(
              `'${paths[j]}' is nested inside '${paths[i]}' - may cause duplicate processing`,
            );
          }
        }
      }
    }

    // Check for conflicts with finished folder
    if (finishedPath && paths.length > 0) {
      const normalizedFinished = normalizePath(finishedPath);
      for (const watchedPath of paths) {
        const normalizedWatched = normalizePath(watchedPath);

        if (normalizedWatched === normalizedFinished) {
          warnings.push(
            `CRITICAL: Watched folder '${watchedPath}' is the same as finished folder - will cause processing loops!`,
          );
        } else if (normalizedFinished.startsWith(normalizedWatched + "/")) {
          warnings.push(
            `Finished folder is nested inside watched folder '${watchedPath}' - may cause issues`,
          );
        } else if (normalizedWatched.startsWith(normalizedFinished + "/")) {
          warnings.push(
            `CRITICAL: Watched folder '${watchedPath}' is nested inside finished folder - will cause processing loops!`,
          );
        }
      }
    }

    return warnings.length > 0 ? warnings : null;
  }, [
    settings.customPaths?.pipeline?.watchedFoldersDirs,
    settings.customPaths?.pipeline?.finishedFoldersDir,
  ]);

  // Filter default locale options based on available languages setting
  const defaultLocaleOptions = useMemo(() => {
    // If no languages are selected (empty), show all languages
    if (!selectedLanguages || selectedLanguages.length === 0) {
      return languageOptions;
    }
    // Otherwise, only show languages that are in the selected list
    return languageOptions.filter((option) =>
      selectedLanguages.includes(option.value),
    );
  }, [selectedLanguages, languageOptions]);

  useEffect(() => {
    // Only fetch real settings if login is enabled
    if (loginEnabled) {
      fetchSettings();
    }
  }, [loginEnabled, fetchSettings]);

  // Sync local preference with server setting on initial load
  useEffect(() => {
    if (loading || !loginEnabled || !settings.ui?.logoStyle) return;

    // This ensures localStorage always reflects the server's authoritative value
    updatePreference("logoVariant", settings.ui.logoStyle);
  }, [loading, loginEnabled, settings.ui?.logoStyle, updatePreference]);

  // Handle hash navigation for deep linking to specific fields
  useEffect(() => {
    if (location.hash && !loading) {
      const elementId = location.hash.substring(1); // Remove the #
      const element = document.getElementById(elementId);
      if (element) {
        setTimeout(() => {
          element.scrollIntoView({ behavior: "smooth", block: "start" });
        }, 100);
      }
    }
  }, [location.hash, loading]);

  const handleDiscard = useCallback(() => {
    const original = resetToSnapshot();
    setSettings(original);
  }, [resetToSnapshot, setSettings]);

  // Override loading state when login is disabled
  const actualLoading = loginEnabled ? loading : false;

  // Show the server setting when loaded (for admin config), otherwise show user's preference
  // Note: User's preference in localStorage is separate and takes precedence in the app via useLogoVariant hook
  const logoStyleValue = loginEnabled
    ? (settings.ui?.logoStyle ?? preferences.logoVariant ?? "classic")
    : (preferences.logoVariant ?? "classic");

  const handleLogoStyleChange = (value: string) => {
    const nextValue = value === "modern" ? "modern" : "classic";

    // Only update local settings state - don't update the actual preference until save
    // When login is disabled, update preference immediately since there's no server to save to
    if (!loginEnabled) {
      updatePreference("logoVariant", nextValue);
      return;
    }

    setSettings({
      ...settings,
      ui: {
        ...settings.ui,
        logoStyle: nextValue,
      },
    });
  };

  const handleSave = async () => {
    // Block save if login is disabled
    if (!validateLoginEnabled()) {
      return;
    }

    try {
      // Mark that we just saved - the snapshot will be updated when refetch completes
      markSaved();

      await saveSettings();

      // Update local preference after successful save so the app reflects the saved logo style
      if (settings.ui?.logoStyle) {
        updatePreference("logoVariant", settings.ui.logoStyle);
      }

      markClean();
      showRestartModal();
    } catch (_error) {
      alert({
        alertType: "error",
        title: t("admin.error", "Error"),
        body: t("admin.settings.saveError", "Failed to save settings"),
      });
    }
  };

  if (actualLoading) {
    return (
      <Stack align="center" justify="center" h={200}>
        <Loader size="lg" />
      </Stack>
    );
  }

  return (
    <div className="settings-section-container">
      <Stack gap="lg" className="settings-section-content">
        <LoginRequiredBanner show={!loginEnabled} />

        <div>
          <Text fw={600} size="lg">
            {t("admin.settings.general.title", "System Settings")}
          </Text>
          <Text size="sm" c="dimmed">
            {t(
              "admin.settings.general.description",
              "Configure system-wide application settings including branding and default behaviour.",
            )}
          </Text>
        </div>

        {/* System Settings */}
        <Paper withBorder p="md" radius="md">
          <Stack gap="md">
            <Text fw={600} size="sm" mb="xs">
              {t("admin.settings.general.system", "System")}
            </Text>

            <div>
              <TextInput
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.appNameNavbar.label",
                        "Navbar Brand",
                      )}
                    </span>
                    <PendingBadge show={isFieldPending("ui.appNameNavbar")} />
                  </Group>
                }
                description={t(
                  "admin.settings.general.appNameNavbar.description",
                  "The name displayed in the navigation bar",
                )}
                value={settings.ui?.appNameNavbar || ""}
                onChange={(e) =>
                  setSettings({
                    ...settings,
                    ui: { ...settings.ui, appNameNavbar: e.target.value },
                  })
                }
                placeholder="Stirling PDF"
                disabled={!loginEnabled}
              />
            </div>

            <div>
              <Text size="sm" fw={500} mb={4}>
                <Group gap="xs">
                  <span>
                    {t("admin.settings.general.logoStyle.label", "Logo Style")}
                  </span>
                  <PendingBadge show={isFieldPending("ui.logoStyle")} />
                </Group>
              </Text>
              <Text size="xs" c="dimmed" mb="xs">
                {t(
                  "admin.settings.general.logoStyle.description",
                  "Choose between the modern minimalist logo or the classic S icon",
                )}
              </Text>
              <SegmentedControl
                value={logoStyleValue}
                onChange={handleLogoStyleChange}
                data={[
                  {
                    value: "classic",
                    label: (
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: "0.5rem",
                          padding: "0.25rem 0",
                        }}
                      >
                        <img
                          src="classic-logo/favicon.ico"
                          alt={t(
                            "admin.settings.general.logoStyle.classicAlt",
                            "Classic logo",
                          )}
                          style={{ width: "24px", height: "24px" }}
                        />
                        <span>
                          {t(
                            "admin.settings.general.logoStyle.classic",
                            "Classic",
                          )}
                        </span>
                      </div>
                    ),
                  },
                  {
                    value: "modern",
                    label: (
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: "0.5rem",
                          padding: "0.25rem 0",
                        }}
                      >
                        <img
                          src="modern-logo/StirlingPDFLogoNoTextLight.svg"
                          alt={t(
                            "admin.settings.general.logoStyle.modernAlt",
                            "Modern logo",
                          )}
                          style={{ width: "24px", height: "24px" }}
                        />
                        <span>
                          {t(
                            "admin.settings.general.logoStyle.modern",
                            "Modern",
                          )}
                        </span>
                      </div>
                    ),
                  },
                ]}
              />
            </div>

            <div>
              <MultiSelect
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.languages.label",
                        "Available Languages",
                      )}
                    </span>
                    <PendingBadge show={isFieldPending("ui.languages")} />
                  </Group>
                }
                description={t(
                  "admin.settings.general.languages.description",
                  "Limit which languages are available (empty = all languages)",
                )}
                value={selectedLanguages}
                onChange={(value) =>
                  setSettings({
                    ...settings,
                    ui: { ...settings.ui, languages: value },
                  })
                }
                data={languageOptions}
                searchable
                clearable
                placeholder={t(
                  "admin.settings.general.languages.placeholder",
                  "Select languages",
                )}
                comboboxProps={{
                  withinPortal: true,
                  zIndex: Z_INDEX_OVER_CONFIG_MODAL,
                }}
                disabled={!loginEnabled}
              />
            </div>

            <div>
              <Select
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.defaultLocale.label",
                        "Default Locale",
                      )}
                    </span>
                    <PendingBadge
                      show={isFieldPending("system.defaultLocale")}
                    />
                  </Group>
                }
                description={t(
                  "admin.settings.general.defaultLocale.description",
                  "The default language for new users (e.g., en_US, es_ES)",
                )}
                value={settings.system?.defaultLocale || ""}
                onChange={(value) =>
                  setSettings({
                    ...settings,
                    system: { ...settings.system, defaultLocale: value || "" },
                  })
                }
                data={defaultLocaleOptions}
                searchable
                clearable
                placeholder="en_US"
                comboboxProps={{
                  withinPortal: true,
                  zIndex: Z_INDEX_OVER_CONFIG_MODAL,
                }}
                disabled={!loginEnabled}
              />
            </div>

            <div>
              <TextInput
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.fileUploadLimit.label",
                        "File Upload Limit",
                      )}
                    </span>
                    <PendingBadge
                      show={isFieldPending("system.fileUploadLimit")}
                    />
                  </Group>
                }
                description={t(
                  "admin.settings.general.fileUploadLimit.description",
                  "Maximum file upload size (e.g., 100MB, 1GB)",
                )}
                value={settings.system?.fileUploadLimit || ""}
                onChange={(e) =>
                  setSettings({
                    ...settings,
                    system: {
                      ...settings.system,
                      fileUploadLimit: e.target.value,
                    },
                  })
                }
                placeholder="100MB"
                disabled={!loginEnabled}
              />
            </div>

            <div id="frontendUrl">
              <TextInput
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.frontendUrl.label",
                        "Frontend URL",
                      )}
                    </span>
                    <PendingBadge show={isFieldPending("system.frontendUrl")} />
                  </Group>
                }
                description={t(
                  "admin.settings.general.frontendUrl.description",
                  "Base URL for frontend (e.g., https://pdf.example.com). Used for email invite links and mobile QR code uploads. Leave empty to use backend URL.",
                )}
                value={settings.system?.frontendUrl || ""}
                onChange={(e) =>
                  setSettings({
                    ...settings,
                    system: { ...settings.system, frontendUrl: e.target.value },
                  })
                }
                placeholder="https://pdf.example.com"
                disabled={!loginEnabled}
              />
            </div>

            {/* Hide Disabled Tools Settings */}
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                marginBottom: "1rem",
              }}
            >
              <div style={{ flex: 1, minWidth: 0 }}>
                <Text fw={500} size="sm">
                  {t(
                    "admin.settings.general.hideDisabledTools.googleDrive.label",
                    "Hide Google Drive",
                  )}
                </Text>
                <Text size="xs" c="dimmed" mt={4}>
                  {t(
                    "admin.settings.general.hideDisabledTools.googleDrive.description",
                    "Hide Google Drive button when not enabled",
                  )}
                </Text>
              </div>
              <Group gap="xs">
                <Switch
                  checked={settings.ui?.hideDisabledTools?.googleDrive || false}
                  onChange={(e) =>
                    setSettings({
                      ...settings,
                      ui: {
                        ...settings.ui,
                        hideDisabledTools: {
                          ...settings.ui?.hideDisabledTools,
                          googleDrive: e.target.checked,
                        },
                      },
                    })
                  }
                  disabled={!loginEnabled}
                />
                <PendingBadge
                  show={isFieldPending("ui.hideDisabledTools.googleDrive")}
                />
              </Group>
            </div>

            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <div style={{ flex: 1, minWidth: 0 }}>
                <Text fw={500} size="sm">
                  {t(
                    "admin.settings.general.hideDisabledTools.mobileScanner.label",
                    "Hide Mobile Scanner",
                  )}
                </Text>
                <Text size="xs" c="dimmed" mt={4}>
                  {t(
                    "admin.settings.general.hideDisabledTools.mobileScanner.description",
                    "Hide mobile QR scanner button when not enabled",
                  )}
                </Text>
              </div>
              <Group gap="xs">
                <Switch
                  checked={
                    settings.ui?.hideDisabledTools?.mobileQRScanner || false
                  }
                  onChange={(e) =>
                    setSettings({
                      ...settings,
                      ui: {
                        ...settings.ui,
                        hideDisabledTools: {
                          ...settings.ui?.hideDisabledTools,
                          mobileQRScanner: e.target.checked,
                        },
                      },
                    })
                  }
                  disabled={!loginEnabled}
                />
                <PendingBadge
                  show={isFieldPending("ui.hideDisabledTools.mobileQRScanner")}
                />
              </Group>
            </div>

            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <div style={{ flex: 1, minWidth: 0 }}>
                <Text fw={500} size="sm">
                  {t(
                    "admin.settings.general.showUpdate.label",
                    "Show Update Notifications",
                  )}
                </Text>
                <Text size="xs" c="dimmed" mt={4}>
                  {t(
                    "admin.settings.general.showUpdate.description",
                    "Display notifications when a new version is available",
                  )}
                </Text>
              </div>
              <Group gap="xs">
                <Switch
                  checked={settings.system?.showUpdate || false}
                  onChange={(e) =>
                    setSettings({
                      ...settings,
                      system: {
                        ...settings.system,
                        showUpdate: e.target.checked,
                      },
                    })
                  }
                  disabled={!loginEnabled}
                />
                <PendingBadge show={isFieldPending("system.showUpdate")} />
              </Group>
            </div>

            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <div style={{ flex: 1, minWidth: 0 }}>
                <Text fw={500} size="sm">
                  {t(
                    "admin.settings.general.showUpdateOnlyAdmin.label",
                    "Show Updates to Admins Only",
                  )}
                </Text>
                <Text size="xs" c="dimmed" mt={4}>
                  {t(
                    "admin.settings.general.showUpdateOnlyAdmin.description",
                    "Restrict update notifications to admin users only",
                  )}
                </Text>
              </div>
              <Group gap="xs">
                <Switch
                  checked={settings.system?.showUpdateOnlyAdmin || false}
                  onChange={(e) =>
                    setSettings({
                      ...settings,
                      system: {
                        ...settings.system,
                        showUpdateOnlyAdmin: e.target.checked,
                      },
                    })
                  }
                  disabled={!loginEnabled}
                />
                <PendingBadge
                  show={isFieldPending("system.showUpdateOnlyAdmin")}
                />
              </Group>
            </div>

            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <div style={{ flex: 1, minWidth: 0 }}>
                <Text fw={500} size="sm">
                  {t(
                    "admin.settings.general.customHTMLFiles.label",
                    "Custom HTML Files",
                  )}
                </Text>
                <Text size="xs" c="dimmed" mt={4}>
                  {t(
                    "admin.settings.general.customHTMLFiles.description",
                    "Allow serving custom HTML files from the customFiles directory",
                  )}
                </Text>
              </div>
              <Group gap="xs">
                <Switch
                  checked={settings.system?.customHTMLFiles || false}
                  onChange={(e) =>
                    setSettings({
                      ...settings,
                      system: {
                        ...settings.system,
                        customHTMLFiles: e.target.checked,
                      },
                    })
                  }
                  disabled={!loginEnabled}
                />
                <PendingBadge show={isFieldPending("system.customHTMLFiles")} />
              </Group>
            </div>
          </Stack>
        </Paper>

        {/* Custom Metadata - Premium Feature */}
        <Paper withBorder p="md" radius="md">
          <Stack gap="md">
            <Group justify="space-between" align="center">
              <Text fw={600} size="sm">
                {t(
                  "admin.settings.general.customMetadata.label",
                  "Custom Metadata",
                )}
              </Text>
              <Badge
                color="grape"
                size="sm"
                style={{ cursor: "pointer" }}
                onClick={() => navigate("/settings/adminPlan")}
                title={t(
                  "admin.settings.badge.clickToUpgrade",
                  "Click to view plan details",
                )}
              >
                PRO
              </Badge>
            </Group>

            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <div style={{ flex: 1, minWidth: 0 }}>
                <Text fw={500} size="sm">
                  {t(
                    "admin.settings.general.customMetadata.autoUpdate.label",
                    "Auto Update Metadata",
                  )}
                </Text>
                <Text size="xs" c="dimmed" mt={4}>
                  {t(
                    "admin.settings.general.customMetadata.autoUpdate.description",
                    "Automatically update PDF metadata on all processed documents",
                  )}
                </Text>
              </div>
              <Group gap="xs">
                <Switch
                  checked={settings.customMetadata?.autoUpdateMetadata || false}
                  onChange={(e) =>
                    setSettings({
                      ...settings,
                      customMetadata: {
                        ...settings.customMetadata,
                        autoUpdateMetadata: e.target.checked,
                      },
                    })
                  }
                  disabled={!loginEnabled}
                />
                <PendingBadge
                  show={isFieldPending("customMetadata.autoUpdateMetadata")}
                />
              </Group>
            </div>

            <div>
              <TextInput
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.customMetadata.author.label",
                        "Default Author",
                      )}
                    </span>
                    <PendingBadge
                      show={isFieldPending("customMetadata.author")}
                    />
                  </Group>
                }
                description={t(
                  "admin.settings.general.customMetadata.author.description",
                  "Default author for PDF metadata (e.g., username)",
                )}
                value={settings.customMetadata?.author || ""}
                onChange={(e) =>
                  setSettings({
                    ...settings,
                    customMetadata: {
                      ...settings.customMetadata,
                      author: e.target.value,
                    },
                  })
                }
                placeholder="username"
                disabled={!loginEnabled}
              />
            </div>

            <div>
              <TextInput
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.customMetadata.creator.label",
                        "Default Creator",
                      )}
                    </span>
                    <PendingBadge
                      show={isFieldPending("customMetadata.creator")}
                    />
                  </Group>
                }
                description={t(
                  "admin.settings.general.customMetadata.creator.description",
                  "Default creator for PDF metadata",
                )}
                value={settings.customMetadata?.creator || ""}
                onChange={(e) =>
                  setSettings({
                    ...settings,
                    customMetadata: {
                      ...settings.customMetadata,
                      creator: e.target.value,
                    },
                  })
                }
                placeholder="Stirling-PDF"
                disabled={!loginEnabled}
              />
            </div>

            <div>
              <TextInput
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.customMetadata.producer.label",
                        "Default Producer",
                      )}
                    </span>
                    <PendingBadge
                      show={isFieldPending("customMetadata.producer")}
                    />
                  </Group>
                }
                description={t(
                  "admin.settings.general.customMetadata.producer.description",
                  "Default producer for PDF metadata",
                )}
                value={settings.customMetadata?.producer || ""}
                onChange={(e) =>
                  setSettings({
                    ...settings,
                    customMetadata: {
                      ...settings.customMetadata,
                      producer: e.target.value,
                    },
                  })
                }
                placeholder="Stirling-PDF"
                disabled={!loginEnabled}
              />
            </div>
          </Stack>
        </Paper>

        {/* Custom Paths */}
        <Paper withBorder p="md" radius="md">
          <Stack gap="md">
            <div>
              <Text fw={600} size="sm" mb="xs">
                {t("admin.settings.general.customPaths.label", "Custom Paths")}
              </Text>
              <Text size="xs" c="dimmed">
                {t(
                  "admin.settings.general.customPaths.description",
                  "Configure custom file system paths for pipeline processing and external tools",
                )}
              </Text>
            </div>

            <Text fw={500} size="sm" mt="xs">
              {t(
                "admin.settings.general.customPaths.pipeline.label",
                "Pipeline Directories",
              )}
            </Text>

            <div>
              <TextInput
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.customPaths.pipeline.pipelineDir.label",
                        "Pipeline Directory",
                      )}
                    </span>
                    <PendingBadge
                      show={isFieldPending("customPaths.pipeline.pipelineDir")}
                    />
                  </Group>
                }
                description={t(
                  "admin.settings.general.customPaths.pipeline.pipelineDir.description",
                  "Base directory for pipeline resources (leave empty for default: /pipeline)",
                )}
                value={settings.customPaths?.pipeline?.pipelineDir || ""}
                onChange={(e) =>
                  setSettings({
                    ...settings,
                    customPaths: {
                      ...settings.customPaths,
                      pipeline: {
                        ...settings.customPaths?.pipeline,
                        pipelineDir: e.target.value,
                      },
                    },
                  })
                }
                placeholder="/pipeline"
                disabled={!loginEnabled}
              />
            </div>

            <div>
              <Textarea
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.customPaths.pipeline.watchedFoldersDirs.label",
                        "Watched Folders Directories",
                      )}
                    </span>
                    <PendingBadge
                      show={
                        isFieldPending(
                          "customPaths.pipeline.watchedFoldersDirs",
                        ) ||
                        isFieldPending("customPaths.pipeline.watchedFoldersDir")
                      }
                    />
                  </Group>
                }
                description={t(
                  "admin.settings.general.customPaths.pipeline.watchedFoldersDirs.description",
                  "Directories where pipeline monitors for incoming PDFs (one per line or comma-separated; leave empty for default: /pipeline/watchedFolders)",
                )}
                value={watchedFoldersInput}
                onChange={(e) => {
                  const parsedDirs = parseWatchedFoldersInput(e.target.value);
                  setSettings({
                    ...settings,
                    customPaths: {
                      ...settings.customPaths,
                      pipeline: {
                        ...settings.customPaths?.pipeline,
                        watchedFoldersDir: parsedDirs[0] || "",
                        watchedFoldersDirs: parsedDirs,
                      },
                    },
                  });
                }}
                placeholder="/pipeline/watchedFolders"
                minRows={3}
                autosize
                disabled={!loginEnabled}
              />
              {watchedFoldersValidation && (
                <Stack gap="xs" mt="xs">
                  {watchedFoldersValidation.map((warning, idx) => (
                    <Text
                      key={idx}
                      size="sm"
                      c={warning.includes("CRITICAL") ? "red" : "yellow"}
                    >
                      {warning}
                    </Text>
                  ))}
                </Stack>
              )}
            </div>

            <div>
              <TextInput
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.customPaths.pipeline.finishedFoldersDir.label",
                        "Finished Folders Directory",
                      )}
                    </span>
                    <PendingBadge
                      show={isFieldPending(
                        "customPaths.pipeline.finishedFoldersDir",
                      )}
                    />
                  </Group>
                }
                description={t(
                  "admin.settings.general.customPaths.pipeline.finishedFoldersDir.description",
                  "Directory where processed PDFs are outputted (leave empty for default: /pipeline/finishedFolders)",
                )}
                value={settings.customPaths?.pipeline?.finishedFoldersDir || ""}
                onChange={(e) =>
                  setSettings({
                    ...settings,
                    customPaths: {
                      ...settings.customPaths,
                      pipeline: {
                        ...settings.customPaths?.pipeline,
                        finishedFoldersDir: e.target.value,
                      },
                    },
                  })
                }
                placeholder="/pipeline/finishedFolders"
                disabled={!loginEnabled}
              />
            </div>

            <Text fw={500} size="sm" mt="md">
              {t(
                "admin.settings.general.customPaths.operations.label",
                "External Tool Paths",
              )}
            </Text>

            <div>
              <TextInput
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.customPaths.operations.weasyprint.label",
                        "WeasyPrint Executable",
                      )}
                    </span>
                    <PendingBadge
                      show={isFieldPending("customPaths.operations.weasyprint")}
                    />
                  </Group>
                }
                description={t(
                  "admin.settings.general.customPaths.operations.weasyprint.description",
                  "Path to WeasyPrint executable for HTML to PDF conversion (leave empty for default: /opt/venv/bin/weasyprint)",
                )}
                value={settings.customPaths?.operations?.weasyprint || ""}
                onChange={(e) =>
                  setSettings({
                    ...settings,
                    customPaths: {
                      ...settings.customPaths,
                      operations: {
                        ...settings.customPaths?.operations,
                        weasyprint: e.target.value,
                      },
                    },
                  })
                }
                placeholder="/opt/venv/bin/weasyprint"
                disabled={!loginEnabled}
              />
            </div>

            <div>
              <TextInput
                label={
                  <Group gap="xs">
                    <span>
                      {t(
                        "admin.settings.general.customPaths.operations.unoconvert.label",
                        "Unoconvert Executable",
                      )}
                    </span>
                    <PendingBadge
                      show={isFieldPending("customPaths.operations.unoconvert")}
                    />
                  </Group>
                }
                description={t(
                  "admin.settings.general.customPaths.operations.unoconvert.description",
                  "Path to LibreOffice unoconvert for document conversions (leave empty for default: /opt/venv/bin/unoconvert)",
                )}
                value={settings.customPaths?.operations?.unoconvert || ""}
                onChange={(e) =>
                  setSettings({
                    ...settings,
                    customPaths: {
                      ...settings.customPaths,
                      operations: {
                        ...settings.customPaths?.operations,
                        unoconvert: e.target.value,
                      },
                    },
                  })
                }
                placeholder="/opt/venv/bin/unoconvert"
                disabled={!loginEnabled}
              />
            </div>
          </Stack>
        </Paper>
      </Stack>

      <SettingsStickyFooter
        isDirty={isDirty}
        saving={saving}
        loginEnabled={loginEnabled}
        onSave={handleSave}
        onDiscard={handleDiscard}
      />

      {/* Restart Confirmation Modal */}
      <RestartConfirmationModal
        opened={restartModalOpened}
        onClose={closeRestartModal}
        onRestart={restartServer}
      />
    </div>
  );
}
