import { useState, useEffect, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import { Navigate, useSearchParams } from "react-router-dom";
import { motion } from "framer-motion";
import ConfirmModal from "../components/ConfirmModal";
import FormModal from "../components/FormModal";
import FormField from "../components/FormField";
import CompanySettings from "./CompanySettings";
import {
  companySettingsOptions,
  systemInfoOptions,
  require2FAOptions,
} from "../lib/queries/settings";

import { useApiMutation } from "../lib/queries/mutations";
import apiFetch from "../utils/api";
const API_BASE = "/api/admin";

interface SystemSettingsData {
  break_threshold_hours: number;
  break_duration_short: number;
  break_duration_long: number;
  clock_rounding_minutes: number;
  invoice_alert_email: string;
  leave_notify_email: string;
  smtp_from: string;
  smtp_from_name: string;
  max_login_attempts: number;
  lockout_minutes: number;
  max_requests_per_minute: number;
  default_currency: string;
  default_vat_rate: number;
  available_vat_rates: number[];
  available_currencies: string[];
  quotation_prefix: string;
  order_type_code: string;
  invoice_type_code: string;
  offer_number_pattern: string;
  order_number_pattern: string;
  invoice_number_pattern: string;
  app_version: string;
}

const MODULE_LABELS: Record<string, string> = {
  attendance: "Docházka",
  trips: "Kniha jízd",
  vehicles: "Vozidla",
  offers: "Nabídky",
  orders: "Objednávky",
  projects: "Projekty",
  invoices: "Faktury",
  customers: "Zákazníci",
  users: "Uživatelé",
  settings: "Nastavení",
};

interface Permission {
  id: number;
  name: string;
  display_name: string;
  description?: string;
}

interface Role {
  id: number;
  name: string;
  display_name: string;
  description: string | null;
  permissions: Permission[];
  role_permissions?: unknown[];
  user_count?: number;
}

interface RoleForm {
  name: string;
  display_name: string;
  description: string;
  permissions: string[];
}

const DEFAULT_SYS_FORM: Omit<SystemSettingsData, "app_version"> = {
  break_threshold_hours: 6,
  break_duration_short: 15,
  break_duration_long: 30,
  clock_rounding_minutes: 15,
  invoice_alert_email: "",
  leave_notify_email: "",
  smtp_from: "",
  smtp_from_name: "",
  max_login_attempts: 5,
  lockout_minutes: 15,
  max_requests_per_minute: 300,
  default_currency: "CZK",
  default_vat_rate: 21,
  available_vat_rates: [0, 10, 12, 15, 21],
  available_currencies: ["CZK", "EUR", "USD", "GBP"],
  quotation_prefix: "NA",
  order_type_code: "71",
  invoice_type_code: "81",
  offer_number_pattern: "{YYYY}/{PREFIX}/{NNN}",
  order_number_pattern: "{YY}{CODE}{NNNN}",
  invoice_number_pattern: "{YY}{CODE}{NNNN}",
};

export default function Settings() {
  const alert = useAlert();
  const { hasPermission } = useAuth();

  const canManageRoles = hasPermission("settings.roles");
  const canManageCompany = hasPermission("settings.company");
  const canManageSystem = hasPermission("settings.system");
  const canManageBanking = hasPermission("settings.banking");
  const canAccessSettings =
    canManageRoles || canManageCompany || canManageSystem || canManageBanking;

  const availableTabs = useMemo(() => {
    const tabs: Array<"roles" | "system" | "firma"> = [];
    if (canManageRoles) tabs.push("roles");
    if (canManageSystem) tabs.push("system");
    if (canManageCompany || canManageBanking) tabs.push("firma");
    return tabs;
  }, [canManageRoles, canManageCompany, canManageSystem, canManageBanking]);

  // ── TanStack Query: roles, permissions ──
  const { data: rolesData, isPending: rolesLoading } = useQuery({
    queryKey: ["settings", "roles"],
    queryFn: async () => {
      const [rolesRes, permsRes] = await Promise.all([
        apiFetch(`${API_BASE}/roles`).then((r) => r.json()),
        apiFetch(`${API_BASE}/roles/permissions`).then((r) => r.json()),
      ]);
      const rolesResult = await rolesRes;
      const permsResult = await permsRes;
      if (!rolesResult.success)
        throw new Error(rolesResult.error || "Nepodařilo se načíst role");
      if (!permsResult.success)
        throw new Error(permsResult.error || "Nepodařilo se načíst oprávnění");
      return {
        roles: Array.isArray(rolesResult.data) ? rolesResult.data : [],
        permissions: Array.isArray(permsResult.data) ? permsResult.data : [],
      };
    },
    enabled: canManageRoles,
  });

  const roles = rolesData?.roles ?? [];
  // Group permissions by module
  const permissionGroups = useMemo<Record<string, Permission[]>>(() => {
    const perms: Permission[] = rolesData?.permissions ?? [];
    const groups: Record<string, Permission[]> = {};
    for (const p of perms) {
      const mod = p.name.split(".")[0] || "other";
      if (!groups[mod]) groups[mod] = [];
      groups[mod].push(p);
    }
    return groups;
  }, [rolesData?.permissions]);

  // ── TanStack Query: 2FA required ──
  const { data: totpData, isPending: require2FALoading } =
    useQuery(require2FAOptions());
  const require2FA = totpData?.require_2fa ?? false;

  // ── TanStack Query: system settings (lazy, only on system/roles tab) ──
  const [searchParams, setSearchParams] = useSearchParams();
  const tabParam = searchParams.get("tab");
  const defaultTab = availableTabs[0] ?? "roles";
  const activeTab = (
    tabParam === "roles" && availableTabs.includes("roles")
      ? "roles"
      : tabParam === "system" && availableTabs.includes("system")
        ? "system"
        : tabParam === "firma" && availableTabs.includes("firma")
          ? "firma"
          : defaultTab
  ) as "roles" | "system" | "firma";
  const setActiveTab = (tab: "roles" | "system" | "firma") =>
    setSearchParams({ tab }, { replace: true });

  const { data: sysSettingsData, isPending: sysSettingsLoading } = useQuery({
    ...companySettingsOptions(),
    enabled:
      (canManageRoles || canManageSystem) &&
      (activeTab === "system" || activeTab === "roles"),
  });

  const { data: systemInfo } = useQuery({
    ...systemInfoOptions(),
    enabled: canManageSystem && activeTab === "system",
  });

  // ── Local state ──
  const [showModal, setShowModal] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [form, setForm] = useState<RoleForm>({
    name: "",
    display_name: "",
    description: "",
    permissions: [],
  });

  const [deleteConfirm, setDeleteConfirm] = useState<{
    show: boolean;
    role: Role | null;
  }>({ show: false, role: null });

  const [sysForm, setSysForm] = useState(DEFAULT_SYS_FORM);
  const [sysFormInitialized, setSysFormInitialized] = useState(false);

  // ── Populate sysForm from query data ──
  useEffect(() => {
    if (!sysSettingsData || sysFormInitialized) return;
    setSysForm({
      break_threshold_hours: sysSettingsData.break_threshold_hours ?? 6,
      break_duration_short: sysSettingsData.break_duration_short ?? 15,
      break_duration_long: sysSettingsData.break_duration_long ?? 30,
      clock_rounding_minutes: sysSettingsData.clock_rounding_minutes ?? 15,
      invoice_alert_email: sysSettingsData.invoice_alert_email || "",
      leave_notify_email: sysSettingsData.leave_notify_email || "",
      smtp_from: sysSettingsData.smtp_from || "",
      smtp_from_name: sysSettingsData.smtp_from_name || "",
      max_login_attempts: sysSettingsData.max_login_attempts ?? 5,
      lockout_minutes: sysSettingsData.lockout_minutes ?? 15,
      max_requests_per_minute: sysSettingsData.max_requests_per_minute ?? 300,
      default_currency: sysSettingsData.default_currency || "CZK",
      default_vat_rate: sysSettingsData.default_vat_rate ?? 21,
      available_vat_rates:
        Array.isArray(sysSettingsData.available_vat_rates) &&
        sysSettingsData.available_vat_rates.length > 0
          ? sysSettingsData.available_vat_rates
          : [0, 10, 12, 15, 21],
      available_currencies:
        Array.isArray(sysSettingsData.available_currencies) &&
        sysSettingsData.available_currencies.length > 0
          ? sysSettingsData.available_currencies
          : ["CZK", "EUR", "USD", "GBP"],
      quotation_prefix: sysSettingsData.quotation_prefix || "NA",
      order_type_code: sysSettingsData.order_type_code || "71",
      invoice_type_code: sysSettingsData.invoice_type_code || "81",
      offer_number_pattern:
        sysSettingsData.offer_number_pattern || "{YYYY}/{PREFIX}/{NNN}",
      order_number_pattern:
        sysSettingsData.order_number_pattern || "{YY}{CODE}{NNNN}",
      invoice_number_pattern:
        sysSettingsData.invoice_number_pattern || "{YY}{CODE}{NNNN}",
    });
    setSysFormInitialized(true);
  }, [sysSettingsData, sysFormInitialized]);

  // ── Early return after all hooks ──
  if (!canAccessSettings) {
    return <Navigate to="/" replace />;
  }

  const saveSystemSettingsMutation = useApiMutation<
    typeof sysForm,
    { message?: string; error?: string }
  >({
    url: () => `${API_BASE}/company-settings`,
    method: () => "PUT",
    invalidate: [
      "settings",
      "company-settings",
      "attendance",
      "offers",
      "orders",
      "invoices",
      "leave",
    ],
    onSuccess: (data) => {
      alert.success(data?.message || "Systémová nastavení byla uložena");
    },
  });

  const toggle2FARoleMutation = useApiMutation<
    { required: boolean },
    { message?: string; error?: string }
  >({
    url: () => `${API_BASE}/totp/required`,
    method: () => "POST",
    invalidate: ["settings", "company-settings", "dashboard", "users"],
    onSuccess: (data) => {
      alert.success(data?.message || "2FA nastavení uloženo");
    },
  });

  // useApiMutation JSON.stringifies the whole TIn as the request body, so
  // TIn must match the backend schema shape (CreateRoleSchema / UpdateRoleSchema)
  // directly — NOT a wrapper that nests the body. id is captured in the URL closure.
  const createRoleMutation = useApiMutation<
    {
      name: string;
      display_name: string;
      description?: string;
      permission_ids: number[];
    },
    { message?: string; error?: string }
  >({
    url: () => `${API_BASE}/roles`,
    method: () => "POST",
    invalidate: ["settings", "users"],
    onSuccess: (data) => {
      closeModal();
      alert.success(data?.message || "Role byla vytvořena");
    },
  });

  const updateRoleMutation = useApiMutation<
    {
      id: number;
      display_name?: string;
      description?: string;
      permission_ids: number[];
    },
    { message?: string; error?: string }
  >({
    url: ({ id }) => `${API_BASE}/roles/${id}`,
    method: () => "PUT",
    invalidate: ["settings", "users"],
    onSuccess: (data) => {
      closeModal();
      alert.success(data?.message || "Role byla aktualizována");
    },
  });

  const deleteRoleMutation = useApiMutation<
    number,
    { message?: string; error?: string }
  >({
    url: (id) => `${API_BASE}/roles/${id}`,
    method: () => "DELETE",
    invalidate: ["settings", "users"],
    onSuccess: (data) => {
      setDeleteConfirm({ show: false, role: null });
      alert.success(data?.message || "Role byla smazána");
    },
  });

  const handleSaveSystemSettings = async () => {
    try {
      await saveSystemSettingsMutation.mutateAsync(sysForm);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

  const handleToggle2FARequired = async () => {
    try {
      await toggle2FARoleMutation.mutateAsync({ required: !require2FA });
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

  const generateSlug = (text: string): string => {
    return text
      .toLowerCase()
      .normalize("NFD")
      .replace(/[̀-ͯ]/g, "")
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-+|-+$/g, "");
  };

  const openCreateModal = () => {
    setEditingRole(null);
    setForm({ name: "", display_name: "", description: "", permissions: [] });
    setShowModal(true);
  };

  const openEditModal = (role: Role) => {
    setEditingRole(role);
    setForm({
      name: role.name,
      display_name: role.display_name,
      description: role.description || "",
      permissions: (role.permissions || []).map((p) =>
        typeof p === "string" ? p : p.name,
      ),
    });
    setShowModal(true);
  };

  const closeModal = () => {
    setShowModal(false);
    setEditingRole(null);
  };

  const handleDisplayNameChange = (value: string) => {
    const updates: Partial<RoleForm> = { display_name: value };
    if (!editingRole) {
      updates.name = generateSlug(value);
    }
    setForm((prev) => ({ ...prev, ...updates }));
  };

  const togglePermission = (permName: string) => {
    setForm((prev) => ({
      ...prev,
      permissions: prev.permissions.includes(permName)
        ? prev.permissions.filter((p) => p !== permName)
        : [...prev.permissions, permName],
    }));
  };

  const toggleModulePermissions = (moduleName: string) => {
    const modulePerms = (permissionGroups[moduleName] || []).map((p) => p.name);
    const allChecked = modulePerms.every((p) => form.permissions.includes(p));

    setForm((prev) => ({
      ...prev,
      permissions: allChecked
        ? prev.permissions.filter((p) => !modulePerms.includes(p))
        : [...new Set([...prev.permissions, ...modulePerms])],
    }));
  };

  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();

    if (!form.display_name.trim()) {
      alert.error("Zobrazovaný název je povinný");
      return;
    }

    if (!editingRole && !form.name.trim()) {
      alert.error("Název role je povinný");
      return;
    }

    const permission_ids = form.permissions
      .map((name) => {
        // Find permission ID by name from groups
        for (const perms of Object.values(permissionGroups)) {
          const found = perms.find((p) => p.name === name);
          if (found) return found.id;
        }
        return null;
      })
      .filter((id): id is number => id !== null);

    try {
      if (editingRole) {
        await updateRoleMutation.mutateAsync({
          id: editingRole.id,
          display_name: form.display_name,
          description: form.description,
          permission_ids,
        });
      } else {
        await createRoleMutation.mutateAsync({
          name: form.name,
          display_name: form.display_name,
          description: form.description,
          permission_ids,
        });
      }
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

  const handleDelete = async () => {
    if (!deleteConfirm.role) return;

    try {
      await deleteRoleMutation.mutateAsync(deleteConfirm.role.id);
    } catch (e) {
      alert.error(e instanceof Error ? e.message : "Chyba připojení");
    }
  };

  if (canManageRoles && rolesLoading) {
    return (
      <div className="admin-loading">
        <div className="admin-spinner" />
      </div>
    );
  }

  const isAdminRole = (role: Role) => role.name === "admin";

  const get2FADescription = (): React.ReactNode => {
    if (require2FALoading) {
      return (
        <div className="admin-loading">
          <div className="admin-spinner" />
        </div>
      );
    }
    if (require2FA)
      return "Všichni uživatelé musí mít aktivní 2FA pro přístup do systému";
    return "2FA je volitelná - uživatelé si ji mohou aktivovat v profilu";
  };

  const get2FAButtonLabel = (): string => {
    if (toggle2FARoleMutation.isPending) return "Ukládání...";
    return require2FA ? "Vypnout" : "Zapnout";
  };

  const renderRoleButtonContent = (): React.ReactNode => {
    const isPending =
      createRoleMutation.isPending || updateRoleMutation.isPending;
    if (isPending) {
      return (
        <>
          <div className="admin-spinner admin-spinner-sm" />
          Ukládání...
        </>
      );
    }
    return editingRole ? "Uložit změny" : "Vytvořit roli";
  };

  return (
    <div>
      <motion.div
        className="admin-page-header"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25 }}
      >
        <div>
          <h1 className="admin-page-title">Nastavení</h1>
          <p className="admin-page-subtitle">
            {activeTab === "system"
              ? "Systémová nastavení"
              : activeTab === "firma"
                ? "Informace o firmě"
                : "Role"}
          </p>
        </div>
      </motion.div>

      {availableTabs.length > 0 && (
        <div style={{ display: "flex", gap: "0.5rem", marginBottom: "1.5rem" }}>
          {availableTabs.includes("roles") && (
            <button
              className={`admin-btn admin-btn-sm ${activeTab === "roles" ? "admin-btn-primary" : "admin-btn-secondary"}`}
              onClick={() => setActiveTab("roles")}
            >
              Role
            </button>
          )}
          {availableTabs.includes("system") && (
            <button
              className={`admin-btn admin-btn-sm ${activeTab === "system" ? "admin-btn-primary" : "admin-btn-secondary"}`}
              onClick={() => setActiveTab("system")}
            >
              Systémová nastavení
            </button>
          )}
          {availableTabs.includes("firma") && (
            <button
              className={`admin-btn admin-btn-sm ${activeTab === "firma" ? "admin-btn-primary" : "admin-btn-secondary"}`}
              onClick={() => setActiveTab("firma")}
            >
              Firma
            </button>
          )}
        </div>
      )}

      {/* Security Settings */}
      {activeTab === "system" && canManageSystem && (
        <motion.div
          className="admin-card"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.06 }}
        >
          <div className="admin-card-header">
            <h2 className="admin-card-title">Zabezpečení</h2>
          </div>
          <div className="admin-card-body">
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                gap: "1rem",
              }}
            >
              <div className="flex-row-gap">
                <div
                  style={{
                    width: 36,
                    height: 36,
                    borderRadius: "50%",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    background: require2FA
                      ? "var(--success-light)"
                      : "rgba(var(--text-secondary-rgb, 107, 114, 128), 0.1)",
                    color: require2FA
                      ? "var(--success)"
                      : "var(--text-secondary)",
                    flexShrink: 0,
                  }}
                >
                  <svg
                    width="18"
                    height="18"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                  >
                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                    <path d="M7 11V7a5 5 0 0 1 10 0v4" />
                  </svg>
                </div>
                <div>
                  <div
                    className="fw-500 text-md"
                    style={{
                      color: "var(--text-primary)",
                    }}
                  >
                    Povinné dvoufaktorové ověření (2FA)
                  </div>
                  <div
                    className="text-xs"
                    style={{
                      color: "var(--text-secondary)",
                    }}
                  >
                    {get2FADescription()}
                  </div>
                </div>
              </div>
              {!require2FALoading && (
                <button
                  onClick={handleToggle2FARequired}
                  disabled={toggle2FARoleMutation.isPending}
                  className={`admin-btn admin-btn-sm ${require2FA ? "admin-btn-secondary" : "admin-btn-primary"}`}
                  style={require2FA ? { color: "var(--danger)" } : {}}
                >
                  {get2FAButtonLabel()}
                </button>
              )}
            </div>
          </div>
        </motion.div>
      )}

      {/* Login Security */}
      {activeTab === "system" && canManageSystem && (
        <motion.div
          className="admin-card"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.08 }}
        >
          <div className="admin-card-header">
            <h2 className="admin-card-title">Přihlašování</h2>
          </div>
          <div className="admin-card-body">
            <div className="admin-form">
              <div className="admin-form-row">
                <FormField label="Max. pokusů o přihlášení">
                  <input
                    type="number"
                    value={sysForm.max_login_attempts}
                    onChange={(e) =>
                      setSysForm((prev) => ({
                        ...prev,
                        max_login_attempts: Number(e.target.value),
                      }))
                    }
                    className="admin-form-input"
                    min={1}
                  />
                </FormField>
                <FormField label="Doba uzamčení účtu (minuty)">
                  <input
                    type="number"
                    value={sysForm.lockout_minutes}
                    onChange={(e) =>
                      setSysForm((prev) => ({
                        ...prev,
                        lockout_minutes: Number(e.target.value),
                      }))
                    }
                    className="admin-form-input"
                    min={1}
                  />
                </FormField>
              </div>
              <div style={{ marginTop: "0.75rem" }}>
                <button
                  onClick={handleSaveSystemSettings}
                  className="admin-btn admin-btn-primary admin-btn-sm"
                  disabled={saveSystemSettingsMutation.isPending}
                >
                  {saveSystemSettingsMutation.isPending
                    ? "Ukládání..."
                    : "Uložit"}
                </button>
              </div>
            </div>
          </div>
        </motion.div>
      )}

      {/* Roles Table */}
      {activeTab === "roles" && (
        <motion.div
          className="admin-card"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.12 }}
        >
          <div
            className="admin-card-header"
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            <h2 className="admin-card-title">Role</h2>
            <button
              onClick={openCreateModal}
              className="admin-btn admin-btn-primary admin-btn-sm"
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <line x1="12" y1="5" x2="12" y2="19" />
                <line x1="5" y1="12" x2="19" y2="12" />
              </svg>
              Přidat roli
            </button>
          </div>
          <div className="admin-card-body">
            <div className="admin-table-responsive">
              <table className="admin-table">
                <thead>
                  <tr>
                    <th>Název</th>
                    <th>Popis</th>
                    <th>Oprávnění</th>
                    <th>Uživatelé</th>
                    <th>Akce</th>
                  </tr>
                </thead>
                <tbody>
                  {roles.map((role: Role) => (
                    <tr key={role.id}>
                      <td>
                        <div
                          className="fw-500"
                          style={{
                            color: "var(--text-primary)",
                          }}
                        >
                          {role.display_name}
                        </div>
                        <div
                          className="text-xs"
                          style={{
                            color: "var(--text-tertiary)",
                          }}
                        >
                          {role.name}
                        </div>
                      </td>
                      <td style={{ color: "var(--text-secondary)" }}>
                        {role.description || "—"}
                      </td>
                      <td>
                        <span className="admin-badge admin-badge-info">
                          {isAdminRole(role)
                            ? "Vše"
                            : (role.permissions?.length ?? 0)}
                        </span>
                      </td>
                      <td>
                        <span className="admin-badge admin-badge-secondary">
                          {role.user_count ?? 0}
                        </span>
                      </td>
                      <td>
                        {!isAdminRole(role) && (
                          <div className="flex-row gap-2">
                            <button
                              onClick={() => openEditModal(role)}
                              className="admin-btn-icon"
                              title="Upravit"
                              aria-label="Upravit"
                            >
                              <svg
                                width="16"
                                height="16"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                              >
                                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
                                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
                              </svg>
                            </button>
                            <button
                              onClick={() =>
                                setDeleteConfirm({ show: true, role })
                              }
                              className="admin-btn-icon danger"
                              title={
                                (role.user_count ?? 0) > 0
                                  ? "Nelze smazat roli s přiřazenými uživateli"
                                  : "Smazat"
                              }
                              aria-label={
                                (role.user_count ?? 0) > 0
                                  ? "Nelze smazat roli s přiřazenými uživateli"
                                  : "Smazat"
                              }
                              disabled={(role.user_count ?? 0) > 0}
                            >
                              <svg
                                width="16"
                                height="16"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                              >
                                <polyline points="3 6 5 6 21 6" />
                                <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
                              </svg>
                            </button>
                          </div>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </motion.div>
      )}

      {/* System Settings Tab */}
      {activeTab === "system" && (
        <>
          {sysSettingsLoading && !sysFormInitialized ? (
            <div className="admin-loading">
              <div className="admin-spinner" />
            </div>
          ) : (
            <>
              {/* Section 1: Docházka */}
              <motion.div
                className="admin-card"
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.25, delay: 0.06 }}
              >
                <div className="admin-card-header">
                  <h2 className="admin-card-title">Docházka</h2>
                </div>
                <div className="admin-card-body">
                  <div className="admin-form">
                    <div className="admin-form-row">
                      <FormField label="Limit pro automatickou přestávku (hodiny)">
                        <input
                          type="number"
                          value={sysForm.break_threshold_hours}
                          onChange={(e) =>
                            setSysForm((prev) => ({
                              ...prev,
                              break_threshold_hours: Number(e.target.value),
                            }))
                          }
                          className="admin-form-input"
                          min={0}
                          step={0.5}
                        />
                      </FormField>
                      <FormField label="Krátká přestávka (minuty)">
                        <input
                          type="number"
                          value={sysForm.break_duration_short}
                          onChange={(e) =>
                            setSysForm((prev) => ({
                              ...prev,
                              break_duration_short: Number(e.target.value),
                            }))
                          }
                          className="admin-form-input"
                          min={0}
                        />
                      </FormField>
                    </div>
                    <div className="admin-form-row">
                      <FormField label="Dlouhá přestávka (minuty)">
                        <input
                          type="number"
                          value={sysForm.break_duration_long}
                          onChange={(e) =>
                            setSysForm((prev) => ({
                              ...prev,
                              break_duration_long: Number(e.target.value),
                            }))
                          }
                          className="admin-form-input"
                          min={0}
                        />
                      </FormField>
                      <FormField label="Zaokrouhlování času (minuty)">
                        <select
                          value={sysForm.clock_rounding_minutes}
                          onChange={(e) =>
                            setSysForm((prev) => ({
                              ...prev,
                              clock_rounding_minutes: Number(e.target.value),
                            }))
                          }
                          className="admin-form-input"
                        >
                          <option value={5}>5</option>
                          <option value={10}>10</option>
                          <option value={15}>15</option>
                          <option value={30}>30</option>
                        </select>
                      </FormField>
                    </div>
                  </div>
                </div>
              </motion.div>

              {/* Section 2: Emailové notifikace */}
              <motion.div
                className="admin-card"
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.25, delay: 0.12 }}
              >
                <div className="admin-card-header">
                  <h2 className="admin-card-title">Emailové notifikace</h2>
                </div>
                <div className="admin-card-body">
                  <div className="admin-form">
                    <div className="admin-form-row">
                      <FormField label="Odesílatel (email)">
                        <input
                          type="email"
                          value={sysForm.smtp_from}
                          onChange={(e) =>
                            setSysForm((prev) => ({
                              ...prev,
                              smtp_from: e.target.value,
                            }))
                          }
                          className="admin-form-input"
                          placeholder="noreply@firma.cz"
                        />
                      </FormField>
                      <FormField label="Odesílatel (jméno)">
                        <input
                          type="text"
                          value={sysForm.smtp_from_name}
                          onChange={(e) =>
                            setSysForm((prev) => ({
                              ...prev,
                              smtp_from_name: e.target.value,
                            }))
                          }
                          className="admin-form-input"
                          placeholder=""
                        />
                      </FormField>
                    </div>
                    <div className="admin-form-row">
                      <FormField label="Email pro upozornění na faktury">
                        <input
                          type="email"
                          value={sysForm.invoice_alert_email}
                          onChange={(e) =>
                            setSysForm((prev) => ({
                              ...prev,
                              invoice_alert_email: e.target.value,
                            }))
                          }
                          className="admin-form-input"
                          placeholder="fakturace@firma.cz"
                        />
                      </FormField>
                      <FormField label="Email pro notifikace dovolené">
                        <input
                          type="email"
                          value={sysForm.leave_notify_email}
                          onChange={(e) =>
                            setSysForm((prev) => ({
                              ...prev,
                              leave_notify_email: e.target.value,
                            }))
                          }
                          className="admin-form-input"
                          placeholder="hr@firma.cz"
                        />
                      </FormField>
                    </div>
                  </div>
                </div>
              </motion.div>

              {/* Section 4: Omezení požadavků */}
              <motion.div
                className="admin-card"
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.25, delay: 0.24 }}
              >
                <div className="admin-card-header">
                  <h2 className="admin-card-title">Omezení požadavků</h2>
                </div>
                <div className="admin-card-body">
                  <div className="admin-form">
                    <FormField label="Max. požadavků za minutu">
                      <input
                        type="number"
                        value={sysForm.max_requests_per_minute}
                        onChange={(e) =>
                          setSysForm((prev) => ({
                            ...prev,
                            max_requests_per_minute: Number(e.target.value),
                          }))
                        }
                        className="admin-form-input"
                        min={1}
                      />
                    </FormField>
                    <small
                      className="text-xs"
                      style={{
                        color: "var(--text-tertiary)",
                      }}
                    >
                      Změna se projeví po restartu serveru
                    </small>
                  </div>
                </div>
              </motion.div>

              {/* Section 5: Informace o aplikaci */}
              <motion.div
                className="admin-card"
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.25, delay: 0.36 }}
              >
                <div className="admin-card-header">
                  <h2 className="admin-card-title">Informace o aplikaci</h2>
                </div>
                <div className="admin-card-body">
                  {systemInfo ? (
                    <table
                      className="w-full"
                      style={{
                        fontSize: "0.85rem",
                        borderCollapse: "collapse",
                      }}
                    >
                      <tbody>
                        {(
                          [
                            [
                              "Verze",
                              (systemInfo as Record<string, unknown>)
                                .app_version,
                            ],
                            [
                              "Node.js",
                              (systemInfo as Record<string, unknown>)
                                .node_version,
                            ],
                            [
                              "Platforma",
                              (systemInfo as Record<string, unknown>).platform,
                            ],
                            [
                              "Uptime",
                              (systemInfo as Record<string, unknown>).uptime,
                            ],
                            [
                              "Prostředí",
                              (systemInfo as Record<string, unknown>)
                                .environment,
                            ],
                            [
                              "Časová zóna",
                              (systemInfo as Record<string, unknown>).timezone,
                            ],
                          ] as [string, string][]
                        ).map(([label, val]) => (
                          <tr key={label}>
                            <td
                              className="whitespace-nowrap"
                              style={{
                                padding: "6px 12px 6px 0",
                                color: "var(--text-secondary)",
                                width: 160,
                              }}
                            >
                              {label}
                            </td>
                            <td className="fw-500" style={{ padding: "6px 0" }}>
                              {val}
                            </td>
                          </tr>
                        ))}
                        <tr>
                          <td
                            colSpan={2}
                            style={{
                              padding: "10px 0 4px",
                              fontWeight: 600,
                              fontSize: "0.8rem",
                              color: "var(--text-tertiary)",
                              textTransform: "uppercase",
                              letterSpacing: "0.05em",
                            }}
                          >
                            Paměť
                          </td>
                        </tr>
                        {(
                          [
                            [
                              "Proces (RSS)",
                              (
                                systemInfo as Record<
                                  string,
                                  Record<string, unknown>
                                >
                              ).memory?.rss as string,
                            ],
                            [
                              "Heap",
                              `${(systemInfo as Record<string, Record<string, unknown>>).memory?.heap_used} / ${(systemInfo as Record<string, Record<string, unknown>>).memory?.heap_total}`,
                            ],
                            [
                              "Systém",
                              `${(systemInfo as Record<string, Record<string, unknown>>).memory?.system_free} volné z ${(systemInfo as Record<string, Record<string, unknown>>).memory?.system_total}`,
                            ],
                          ] as [string, string][]
                        ).map(([label, val]) => (
                          <tr key={label}>
                            <td
                              style={{
                                padding: "4px 12px 4px 0",
                                color: "var(--text-secondary)",
                              }}
                            >
                              {label}
                            </td>
                            <td style={{ padding: "4px 0" }}>{val}</td>
                          </tr>
                        ))}
                        <tr>
                          <td
                            colSpan={2}
                            style={{
                              padding: "10px 0 4px",
                              fontWeight: 600,
                              fontSize: "0.8rem",
                              color: "var(--text-tertiary)",
                              textTransform: "uppercase",
                              letterSpacing: "0.05em",
                            }}
                          >
                            Databáze
                          </td>
                        </tr>
                        <tr>
                          <td
                            style={{
                              padding: "4px 12px 4px 0",
                              color: "var(--text-secondary)",
                            }}
                          >
                            Stav
                          </td>
                          <td style={{ padding: "4px 0" }}>
                            <span
                              className={`admin-badge ${(systemInfo as Record<string, Record<string, unknown>>).database?.status === "ok" ? "admin-badge-success" : "admin-badge-danger"}`}
                            >
                              {(
                                systemInfo as Record<
                                  string,
                                  Record<string, unknown>
                                >
                              ).database?.status === "ok"
                                ? "Připojeno"
                                : "Chyba"}
                            </span>
                          </td>
                        </tr>
                        <tr>
                          <td
                            style={{
                              padding: "4px 12px 4px 0",
                              color: "var(--text-secondary)",
                            }}
                          >
                            Migrace
                          </td>
                          <td style={{ padding: "4px 0" }}>
                            {
                              (
                                systemInfo as Record<
                                  string,
                                  Record<string, unknown>
                                >
                              ).database?.migrations_applied as string
                            }
                          </td>
                        </tr>
                        <tr>
                          <td
                            colSpan={2}
                            style={{
                              padding: "10px 0 4px",
                              fontWeight: 600,
                              fontSize: "0.8rem",
                              color: "var(--text-tertiary)",
                              textTransform: "uppercase",
                              letterSpacing: "0.05em",
                            }}
                          >
                            NAS úložiště
                          </td>
                        </tr>
                        {(
                          [
                            [
                              "Projekty",
                              (
                                systemInfo as Record<
                                  string,
                                  Record<string, Record<string, unknown>>
                                >
                              ).nas?.projects,
                            ],
                            [
                              "Finance",
                              (
                                systemInfo as Record<
                                  string,
                                  Record<string, Record<string, unknown>>
                                >
                              ).nas?.financials,
                            ],
                            [
                              "Nabídky",
                              (
                                systemInfo as Record<
                                  string,
                                  Record<string, Record<string, unknown>>
                                >
                              ).nas?.offers,
                            ],
                          ] as [string, Record<string, any>][]
                        ).map(([label, info]) => (
                          <tr key={label}>
                            <td
                              style={{
                                padding: "4px 12px 4px 0",
                                color: "var(--text-secondary)",
                              }}
                            >
                              {label}
                            </td>
                            <td style={{ padding: "4px 0" }}>
                              <span
                                className={`admin-badge ${info?.configured ? "admin-badge-success" : "admin-badge-secondary"}`}
                              >
                                {info?.configured
                                  ? "Připojeno"
                                  : "Nenakonfigurováno"}
                              </span>
                              {info?.configured && (
                                <span
                                  className="text-xs"
                                  style={{
                                    marginLeft: 8,
                                    color: "var(--text-tertiary)",
                                  }}
                                >
                                  {info.path}
                                </span>
                              )}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  ) : (
                    <div
                      style={{
                        padding: "1rem",
                        display: "flex",
                        flexDirection: "column",
                        gap: "0.5rem",
                      }}
                    >
                      <div
                        style={{
                          height: "0.75rem",
                          background: "#e0e0e0",
                          borderRadius: "4px",
                          width: "60%",
                        }}
                      />
                      <div
                        style={{
                          height: "0.75rem",
                          background: "#e0e0e0",
                          borderRadius: "4px",
                          width: "40%",
                        }}
                      />
                    </div>
                  )}
                </div>
              </motion.div>

              {/* Save button */}
              <motion.div
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.25, delay: 0.42 }}
              >
                <button
                  onClick={handleSaveSystemSettings}
                  disabled={saveSystemSettingsMutation.isPending}
                  className="admin-btn admin-btn-primary w-full"
                >
                  {saveSystemSettingsMutation.isPending ? (
                    <>
                      <div className="admin-spinner admin-spinner-sm" />
                      Ukládání...
                    </>
                  ) : (
                    "Uložit"
                  )}
                </button>
              </motion.div>
            </>
          )}
        </>
      )}

      {/* Firma tab */}
      {activeTab === "firma" && <CompanySettings embedded />}

      {/* Create/Edit Modal */}
      <FormModal
        isOpen={showModal}
        onClose={closeModal}
        onSubmit={handleSubmit}
        title={editingRole ? "Upravit roli" : "Nová role"}
        size="lg"
        loading={createRoleMutation.isPending || updateRoleMutation.isPending}
      >
        <div className="admin-form">
          {editingRole && isAdminRole(editingRole) && (
            <div className="admin-role-locked-notice">
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <circle cx="12" cy="12" r="10" />
                <line x1="12" y1="16" x2="12" y2="12" />
                <line x1="12" y1="8" x2="12.01" y2="8" />
              </svg>
              Administrátor má vždy plný přístup ke všem funkcím
            </div>
          )}

          <FormField label="Zobrazovaný název">
            <input
              type="text"
              value={form.display_name}
              onChange={(e) => handleDisplayNameChange(e.target.value)}
              className="admin-form-input"
              placeholder="např. Manažer"
              disabled={!!(editingRole && isAdminRole(editingRole))}
            />
          </FormField>

          <FormField label="Systémový název (slug)">
            <input
              type="text"
              value={form.name}
              onChange={(e) =>
                setForm((prev) => ({ ...prev, name: e.target.value }))
              }
              className="admin-form-input"
              placeholder="např. manager"
              disabled={!!editingRole}
            />
            {!editingRole && (
              <small
                className="text-xs"
                style={{
                  color: "var(--text-tertiary)",
                }}
              >
                Pouze malá písmena, čísla a pomlčky. Nelze později změnit.
              </small>
            )}
          </FormField>

          <FormField label="Popis">
            <textarea
              value={form.description}
              onChange={(e) =>
                setForm((prev) => ({
                  ...prev,
                  description: e.target.value,
                }))
              }
              className="admin-form-input"
              rows={2}
              placeholder="Volitelný popis role"
              disabled={!!(editingRole && isAdminRole(editingRole))}
            />
          </FormField>

          <div className="admin-form-group">
            <label
              className="admin-form-label"
              style={{ marginBottom: "0.75rem" }}
            >
              Oprávnění
            </label>

            {Object.entries(permissionGroups)
              .sort(([a, aPerms], [b, bPerms]) => {
                if (a === "settings") return 1;
                if (b === "settings") return -1;
                const aMin = Math.min(...aPerms.map((p) => p.id));
                const bMin = Math.min(...bPerms.map((p) => p.id));
                return aMin - bMin;
              })
              .map(([module, perms], index) => {
                const modulePerms = perms.map((p) => p.name);
                const allChecked = modulePerms.every((p) =>
                  form.permissions.includes(p),
                );
                const someChecked = modulePerms.some((p) =>
                  form.permissions.includes(p),
                );
                const disabled = !!(editingRole && isAdminRole(editingRole));

                return (
                  <div key={module}>
                    {index > 0 && (
                      <hr
                        style={{
                          border: "none",
                          borderTop: "1px solid var(--border-color, #e0e0e0)",
                          margin: "0.75rem 0",
                        }}
                      />
                    )}
                    <div className="admin-permission-group">
                      <div className="admin-permission-group-title">
                        <label className="admin-form-checkbox">
                          <input
                            type="checkbox"
                            checked={allChecked}
                            ref={(el) => {
                              if (el)
                                el.indeterminate = someChecked && !allChecked;
                            }}
                            onChange={() => toggleModulePermissions(module)}
                            disabled={disabled}
                          />
                          <span>{MODULE_LABELS[module] || module}</span>
                        </label>
                      </div>
                      <div className="admin-permission-list">
                        {perms.map((perm) => (
                          <div key={perm.id} className="admin-permission-item">
                            <label className="admin-form-checkbox">
                              <input
                                type="checkbox"
                                checked={form.permissions.includes(perm.name)}
                                onChange={() => togglePermission(perm.name)}
                                disabled={disabled}
                              />
                              <span>{perm.display_name}</span>
                            </label>
                            {perm.description && (
                              <div className="admin-permission-desc">
                                {perm.description}
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                );
              })}
          </div>
        </div>
      </FormModal>

      {/* Delete Confirm Modal */}
      <ConfirmModal
        isOpen={deleteConfirm.show}
        onClose={() => setDeleteConfirm({ show: false, role: null })}
        onConfirm={handleDelete}
        title="Smazat roli"
        message={`Opravdu chcete smazat roli "${deleteConfirm.role?.display_name}"? Tato akce je nevratná.`}
        confirmText="Smazat"
        cancelText="Zrušit"
        type="danger"
        loading={deleteRoleMutation.isPending}
      />
    </div>
  );
}
