import { useEffect, useMemo, useState } from "react";
import { isAxiosError } from "axios";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@edr/ui-common";
import { CopyPlus, Plus, RefreshCw } from "lucide-react";

import { api } from "@/auth/http";
import { useAuth } from "@/auth/useAuth";

interface LocaleText {
  en?: string;
  am?: string;
}

interface OrganizationRecord {
  id: string;
  key: string;
  name?: LocaleText;
}

interface UnitRecord {
  id: string;
  key: string;
  name?: LocaleText;
}

interface PositionTypeRecord {
  id: string;
  key: string;
  name?: LocaleText;
  isSystem?: boolean;
  unitId?: string | null;
  createdAt?: string;
  updatedAt?: string | null;
}

interface PermissionRecord {
  id: string;
  key: string;
  name?: LocaleText;
  applicationId?: string | null;
}

interface ListResponse<T> {
  count?: number;
  items?: T[];
  data?: T[];
}

const PAGE_SIZE = 1000;

const inputClassName =
  "w-full rounded-xl border border-border bg-background px-3 py-2.5 text-sm text-foreground outline-none transition focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100 dark:focus:ring-emerald-950";
const buttonClassName =
  "inline-flex items-center justify-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60";

const emptyCreateForm = {
  copyPermissionFromId: "",
  key: "",
  nameAm: "",
  nameEn: "",
};

type PositionTypeEditFormState = {
  key: string;
  nameAm: string;
  nameEn: string;
};

const emptyEditForm: PositionTypeEditFormState = {
  key: "",
  nameAm: "",
  nameEn: "",
};

const toggleSelection = (
  currentIds: string[],
  targetIds: string[],
  checked: boolean,
) => {
  if (checked) {
    return [...new Set([...currentIds, ...targetIds])];
  }

  return currentIds.filter((id) => !targetIds.includes(id));
};

const getLocaleLabel = (value?: LocaleText | null, fallback = "Unnamed") =>
  value?.en ?? value?.am ?? fallback;

const getItems = <T,>(payload: ListResponse<T> | T[] | undefined | null) => {
  if (!payload) {
    return [] as T[];
  }

  if (Array.isArray(payload)) {
    return payload;
  }

  return payload.items ?? payload.data ?? [];
};

const formatDate = (value?: string | null) => {
  if (!value) {
    return "-";
  }

  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return "-";
  }

  return new Intl.DateTimeFormat("en", {
    year: "numeric",
    month: "short",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  }).format(date);
};

const PositionTypesPage = () => {
  const { user } = useAuth();
  const [organizations, setOrganizations] = useState<OrganizationRecord[]>([]);
  const [units, setUnits] = useState<UnitRecord[]>([]);
  const [positionTypes, setPositionTypes] = useState<PositionTypeRecord[]>([]);
  const [selectedOrgId, setSelectedOrgId] = useState("");
  const [selectedUnitId, setSelectedUnitId] = useState("");
  const [loadingOrganizations, setLoadingOrganizations] = useState(true);
  const [loadingUnits, setLoadingUnits] = useState(false);
  const [loadingPositionTypes, setLoadingPositionTypes] = useState(false);
  const [loadingPermissionsCatalog, setLoadingPermissionsCatalog] =
    useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [selectedPositionType, setSelectedPositionType] =
    useState<PositionTypeRecord | null>(null);
  const [allPermissions, setAllPermissions] = useState<PermissionRecord[]>([]);
  const [permissionsLoading, setPermissionsLoading] = useState(false);
  const [permissionsError, setPermissionsError] = useState<string | null>(null);
  const [permissionSearch, setPermissionSearch] = useState("");
  const [selectedPermissionIds, setSelectedPermissionIds] = useState<string[]>(
    [],
  );
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [createForm, setCreateForm] = useState(emptyCreateForm);
  const [createPermissionSearch, setCreatePermissionSearch] = useState("");
  const [createPermissionIds, setCreatePermissionIds] = useState<string[]>([]);
  const [createError, setCreateError] = useState<string | null>(null);
  const [editForm, setEditForm] =
    useState<PositionTypeEditFormState>(emptyEditForm);

  const isSuperAdmin = Boolean(
    user?.roles?.some((role) => role.key === "super_admin"),
  );
  const allowedOrgIds = useMemo(
    () =>
      new Set(
        (user?.employee ?? [])
          .map((employee) => employee.organizationId)
          .filter((organizationId): organizationId is string =>
            Boolean(organizationId),
          ),
      ),
    [user?.employee],
  );

  const visibleOrganizations = useMemo(() => {
    if (isSuperAdmin) {
      return organizations;
    }

    return organizations.filter((organization) =>
      allowedOrgIds.has(organization.id),
    );
  }, [allowedOrgIds, isSuperAdmin, organizations]);

  const selectedOrganization =
    visibleOrganizations.find(
      (organization) => organization.id === selectedOrgId,
    ) ?? null;
  const selectedUnit = units.find((unit) => unit.id === selectedUnitId) ?? null;
  const availableCopySources = useMemo(
    () =>
      positionTypes.filter(
        (positionType) => positionType.id !== selectedPositionType?.id,
      ),
    [positionTypes, selectedPositionType?.id],
  );
  const filteredPermissions = useMemo(() => {
    const query = permissionSearch.trim().toLowerCase();

    return allPermissions.filter((permission) => {
      if (!query) {
        return true;
      }

      const label = getLocaleLabel(
        permission.name,
        permission.key,
      ).toLowerCase();
      return (
        label.includes(query) || permission.key.toLowerCase().includes(query)
      );
    });
  }, [allPermissions, permissionSearch]);
  const filteredCreatePermissions = useMemo(() => {
    const query = createPermissionSearch.trim().toLowerCase();

    return allPermissions.filter((permission) => {
      if (!query) {
        return true;
      }

      const label = getLocaleLabel(
        permission.name,
        permission.key,
      ).toLowerCase();
      return (
        label.includes(query) || permission.key.toLowerCase().includes(query)
      );
    });
  }, [allPermissions, createPermissionSearch]);
  const allFilteredPermissionIds = filteredPermissions.map(
    (permission) => permission.id,
  );
  const allFilteredCreatePermissionIds = filteredCreatePermissions.map(
    (permission) => permission.id,
  );
  const areAllFilteredPermissionsSelected =
    allFilteredPermissionIds.length > 0 &&
    allFilteredPermissionIds.every((id) => selectedPermissionIds.includes(id));
  const areAllFilteredCreatePermissionsSelected =
    allFilteredCreatePermissionIds.length > 0 &&
    allFilteredCreatePermissionIds.every((id) =>
      createPermissionIds.includes(id),
    );

  const loadPositionTypes = async (unitId: string) => {
    const response = await api.get<ListResponse<PositionTypeRecord>>(
      `/position-types/list-with-commons/${unitId}`,
      {
        params: {
          skip: 0,
          take: PAGE_SIZE,
          orderBy: "createdAt:Desc",
        },
      },
    );

    return getItems(response.data);
  };

  const loadPermissionsForPositionType = async (positionTypeId: string) => {
    const response = await api.get<ListResponse<PermissionRecord>>(
      `/position-type-permissions/given-first/${positionTypeId}`,
    );

    return getItems(response.data);
  };

  useEffect(() => {
    let isMounted = true;

    const loadOrganizations = async () => {
      setLoadingOrganizations(true);
      setErrorMessage(null);

      try {
        const response =
          await api.get<ListResponse<OrganizationRecord>>("/organizations");

        if (!isMounted) {
          return;
        }

        setOrganizations(getItems(response.data));
      } catch (error) {
        if (!isMounted) {
          return;
        }

        setErrorMessage(
          isAxiosError(error)
            ? (error.response?.data?.message ?? "Unable to load organizations.")
            : "Unable to load organizations.",
        );
      } finally {
        if (isMounted) {
          setLoadingOrganizations(false);
        }
      }
    };

    void loadOrganizations();

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    let isMounted = true;

    const loadPermissionsCatalog = async () => {
      setLoadingPermissionsCatalog(true);

      try {
        const response = await api.get<ListResponse<PermissionRecord>>(
          "/permissions",
          {
            params: {
              skip: 0,
              take: 2000,
            },
          },
        );

        if (!isMounted) {
          return;
        }

        setAllPermissions(getItems(response.data));
      } catch {
        if (!isMounted) {
          return;
        }

        setAllPermissions([]);
      } finally {
        if (isMounted) {
          setLoadingPermissionsCatalog(false);
        }
      }
    };

    void loadPermissionsCatalog();

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    if (!visibleOrganizations.length) {
      setSelectedOrgId("");
      setSelectedUnitId("");
      setUnits([]);
      setPositionTypes([]);
      return;
    }

    if (
      selectedOrgId &&
      visibleOrganizations.some(
        (organization) => organization.id === selectedOrgId,
      )
    ) {
      return;
    }

    setSelectedOrgId(visibleOrganizations[0]?.id ?? "");
  }, [selectedOrgId, visibleOrganizations]);

  useEffect(() => {
    if (!selectedOrgId) {
      setUnits([]);
      setSelectedUnitId("");
      setPositionTypes([]);
      return;
    }

    let isMounted = true;

    const loadUnits = async () => {
      setLoadingUnits(true);
      setErrorMessage(null);
      setSelectedUnitId("");
      setPositionTypes([]);

      try {
        const response = await api.get<ListResponse<UnitRecord>>(
          `/units/list/${selectedOrgId}`,
        );
        const items = getItems(response.data);

        if (!isMounted) {
          return;
        }

        setUnits(items);
        setSelectedUnitId(items[0]?.id ?? "");
      } catch (error) {
        if (!isMounted) {
          return;
        }

        setUnits([]);
        setErrorMessage(
          isAxiosError(error)
            ? (error.response?.data?.message ?? "Unable to load units.")
            : "Unable to load units.",
        );
      } finally {
        if (isMounted) {
          setLoadingUnits(false);
        }
      }
    };

    void loadUnits();

    return () => {
      isMounted = false;
    };
  }, [selectedOrgId]);

  useEffect(() => {
    if (!selectedUnitId) {
      setPositionTypes([]);
      return;
    }

    let isMounted = true;

    const loadItems = async () => {
      setLoadingPositionTypes(true);
      setErrorMessage(null);

      try {
        const items = await loadPositionTypes(selectedUnitId);

        if (!isMounted) {
          return;
        }

        setPositionTypes(items);
      } catch (error) {
        if (!isMounted) {
          return;
        }

        setPositionTypes([]);
        setErrorMessage(
          isAxiosError(error)
            ? (error.response?.data?.message ??
              "Unable to load position types.")
            : "Unable to load position types.",
        );
      } finally {
        if (isMounted) {
          setLoadingPositionTypes(false);
        }
      }
    };

    void loadItems();

    return () => {
      isMounted = false;
    };
  }, [selectedUnitId]);

  useEffect(() => {
    if (!selectedPositionType) {
      setSelectedPermissionIds([]);
      setEditForm(emptyEditForm);
      setPermissionsError(null);
      setPermissionsLoading(false);
      setPermissionSearch("");
      return;
    }

    setEditForm({
      key: selectedPositionType.key,
      nameAm: selectedPositionType.name?.am ?? "",
      nameEn: selectedPositionType.name?.en ?? "",
    });

    let isMounted = true;

    const loadPermissions = async () => {
      setPermissionsLoading(true);
      setPermissionsError(null);

      try {
        const items = await loadPermissionsForPositionType(
          selectedPositionType.id,
        );

        if (!isMounted) {
          return;
        }

        setSelectedPermissionIds(items.map((permission) => permission.id));
      } catch (error) {
        if (!isMounted) {
          return;
        }

        setPermissionsError(
          isAxiosError(error)
            ? (error.response?.data?.message ??
              "Unable to load position type permissions.")
            : "Unable to load position type permissions.",
        );
      } finally {
        if (isMounted) {
          setPermissionsLoading(false);
        }
      }
    };

    void loadPermissions();

    return () => {
      isMounted = false;
    };
  }, [selectedPositionType]);

  const handleRefresh = async () => {
    if (!selectedUnitId) {
      return;
    }

    setLoadingPositionTypes(true);
    setErrorMessage(null);

    try {
      const items = await loadPositionTypes(selectedUnitId);
      setPositionTypes(items);

      if (selectedPositionType) {
        const nextSelected =
          items.find((item) => item.id === selectedPositionType.id) ??
          selectedPositionType;
        setSelectedPositionType(nextSelected);
      }
    } catch (error) {
      setErrorMessage(
        isAxiosError(error)
          ? (error.response?.data?.message ??
            "Unable to refresh position types.")
          : "Unable to refresh position types.",
      );
    } finally {
      setLoadingPositionTypes(false);
    }
  };

  const openCreateDialog = () => {
    setCreateForm(emptyCreateForm);
    setCreatePermissionIds([]);
    setCreatePermissionSearch("");
    setCreateError(null);
    setIsCreateOpen(true);
  };

  const handleSelectCopySource = async (positionTypeId: string) => {
    setCreateForm((current) => ({
      ...current,
      copyPermissionFromId: positionTypeId,
    }));

    if (!positionTypeId) {
      setCreatePermissionIds([]);
      return;
    }

    try {
      const copiedPermissions =
        await loadPermissionsForPositionType(positionTypeId);
      setCreatePermissionIds(
        copiedPermissions.map((permission) => permission.id),
      );
    } catch (error) {
      setCreateError(
        isAxiosError(error)
          ? (error.response?.data?.message ?? "Unable to copy permissions.")
          : "Unable to copy permissions.",
      );
    }
  };

  const handleCreatePositionType = async (
    event: React.FormEvent<HTMLFormElement>,
  ) => {
    event.preventDefault();

    if (!selectedUnitId) {
      setCreateError("Select a unit before creating a position type.");
      return;
    }

    setSubmitting(true);
    setCreateError(null);

    try {
      const response = await api.post<PositionTypeRecord>("/position-types", {
        key: createForm.key.trim(),
        name: {
          am: createForm.nameAm.trim(),
          en: createForm.nameEn.trim(),
        },
        unitId: selectedUnitId,
      });

      const createdPositionType = response.data;

      await api.post("/position-type-permissions/assign-seconds-for-first", {
        firstId: createdPositionType.id,
        secondIds: createPermissionIds,
      });

      setIsCreateOpen(false);
      setCreateForm(emptyCreateForm);
      setCreatePermissionIds([]);
      await handleRefresh();
    } catch (error) {
      setCreateError(
        isAxiosError(error)
          ? (error.response?.data?.message ?? "Unable to create position type.")
          : "Unable to create position type.",
      );
    } finally {
      setSubmitting(false);
    }
  };

  const handleSavePositionTypeChanges = async () => {
    if (!selectedPositionType) {
      return;
    }

    setSubmitting(true);
    setPermissionsError(null);

    try {
      if (!selectedPositionType.isSystem) {
        await api.put(`/position-types/${selectedPositionType.id}`, {
          key: editForm.key.trim(),
          name: {
            am: editForm.nameAm.trim(),
            en: editForm.nameEn.trim(),
          },
          unitId: selectedPositionType.unitId,
        });
      }

      await api.post("/position-type-permissions/assign-seconds-for-first", {
        firstId: selectedPositionType.id,
        secondIds: selectedPermissionIds,
      });

      const [refreshedPermissions, refreshedPositionTypes] = await Promise.all([
        loadPermissionsForPositionType(selectedPositionType.id),
        selectedUnitId
          ? loadPositionTypes(selectedUnitId)
          : Promise.resolve(positionTypes),
      ]);

      setSelectedPermissionIds(
        refreshedPermissions.map((permission) => permission.id),
      );
      setPositionTypes(refreshedPositionTypes);

      const refreshedSelected = refreshedPositionTypes.find(
        (item) => item.id === selectedPositionType.id,
      );
      if (refreshedSelected) {
        setSelectedPositionType(refreshedSelected);
      }
    } catch (error) {
      setPermissionsError(
        isAxiosError(error)
          ? (error.response?.data?.message ?? "Unable to update position type.")
          : "Unable to update position type.",
      );
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section className="p-6">
      <div className="space-y-6 rounded-2xl border border-border bg-card p-8 shadow-sm">
        <div className="space-y-3">
          <p className="text-sm font-medium uppercase tracking-[0.2em] text-muted-foreground">
            User Management
          </p>
          <div className="flex items-start justify-between gap-4">
            <div>
              <h1 className="text-3xl font-semibold text-foreground">
                Position Type
              </h1>
              <p className="mt-3 max-w-2xl text-sm text-muted-foreground">
                Browse position types for a selected organization unit, add new
                ones, and manage their permissions.
              </p>
            </div>
            <div className="flex items-center gap-2">
              <div className="rounded-full border border-border bg-muted px-3 py-1 text-sm font-medium text-muted-foreground">
                {positionTypes.length} position types
              </div>
              <button
                type="button"
                onClick={() => void handleRefresh()}
                disabled={!selectedUnitId || loadingPositionTypes}
                className={`${buttonClassName} border border-border bg-background text-foreground hover:bg-accent hover:text-accent-foreground`}
              >
                <RefreshCw className="h-4 w-4" />
                Refresh
              </button>
              <button
                type="button"
                onClick={openCreateDialog}
                disabled={!selectedUnitId || submitting}
                className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
              >
                <Plus className="h-4 w-4" />
                New position type
              </button>
            </div>
          </div>
        </div>

        <div className="grid gap-3 rounded-2xl border border-border bg-background/60 p-4 md:grid-cols-2 xl:grid-cols-[minmax(0,280px)_minmax(0,280px)_1fr] xl:items-end">
          <div className="space-y-2">
            <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
              Organization
            </p>
            <Select
              value={selectedOrgId || undefined}
              onValueChange={setSelectedOrgId}
              disabled={loadingOrganizations || !visibleOrganizations.length}
            >
              <SelectTrigger className="w-full rounded-xl bg-background">
                <SelectValue
                  placeholder={
                    loadingOrganizations
                      ? "Loading organizations..."
                      : "Select organization"
                  }
                />
              </SelectTrigger>
              <SelectContent>
                {visibleOrganizations.map((organization) => (
                  <SelectItem key={organization.id} value={organization.id}>
                    {getLocaleLabel(organization.name, organization.key)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
              Unit
            </p>
            <Select
              value={selectedUnitId || undefined}
              onValueChange={setSelectedUnitId}
              disabled={!selectedOrgId || loadingUnits || !units.length}
            >
              <SelectTrigger className="w-full rounded-xl bg-background">
                <SelectValue
                  placeholder={
                    loadingUnits ? "Loading units..." : "Select unit"
                  }
                />
              </SelectTrigger>
              <SelectContent>
                {units.map((unit) => (
                  <SelectItem key={unit.id} value={unit.id}>
                    {getLocaleLabel(unit.name, unit.key)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <p className="text-sm text-muted-foreground">
            {selectedOrganization && selectedUnit
              ? `Showing position types for ${getLocaleLabel(selectedUnit.name, selectedUnit.key)} in ${getLocaleLabel(selectedOrganization.name, selectedOrganization.key)}.`
              : "Select an organization and unit to load position types."}
          </p>
        </div>

        {errorMessage ? (
          <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-8 text-center text-sm text-red-700 dark:border-red-950 dark:bg-red-950/30 dark:text-red-300">
            {errorMessage}
          </div>
        ) : loadingOrganizations || loadingUnits || loadingPositionTypes ? (
          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
            Loading position types...
          </div>
        ) : !visibleOrganizations.length ? (
          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
            No organization scope is available for this account.
          </div>
        ) : !selectedOrgId ? (
          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
            Select an organization to continue.
          </div>
        ) : !units.length ? (
          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
            No units are available for the selected organization.
          </div>
        ) : !selectedUnitId ? (
          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
            Select a unit to load position types.
          </div>
        ) : positionTypes.length ? (
          <div className="overflow-x-auto rounded-2xl border border-border">
            <table className="min-w-[980px] w-full border-collapse text-left text-sm">
              <thead className="bg-muted/60 text-muted-foreground">
                <tr>
                  <th className="px-4 py-3 font-medium">Name</th>
                  <th className="px-4 py-3 font-medium">Key</th>
                  <th className="px-4 py-3 font-medium">Scope</th>
                  <th className="px-4 py-3 font-medium">Unit ID</th>
                  <th className="px-4 py-3 font-medium">Created At</th>
                  <th className="px-4 py-3 font-medium">Updated At</th>
                </tr>
              </thead>
              <tbody>
                {positionTypes.map((positionType) => (
                  <tr
                    key={positionType.id}
                    onClick={() => setSelectedPositionType(positionType)}
                    className="cursor-pointer border-t border-border bg-background transition hover:bg-accent/20"
                  >
                    <td className="px-4 py-3 font-medium text-foreground">
                      {getLocaleLabel(positionType.name, positionType.key)}
                    </td>
                    <td className="px-4 py-3 font-mono text-muted-foreground">
                      {positionType.key}
                    </td>
                    <td className="px-4 py-3 text-muted-foreground">
                      {positionType.isSystem ? "System" : "Unit"}
                    </td>
                    <td className="px-4 py-3 font-mono text-muted-foreground">
                      {positionType.unitId ?? "-"}
                    </td>
                    <td className="px-4 py-3 text-muted-foreground">
                      {formatDate(positionType.createdAt)}
                    </td>
                    <td className="px-4 py-3 text-muted-foreground">
                      {formatDate(positionType.updatedAt)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
            No position types were found for the selected unit.
          </div>
        )}
      </div>

      <Dialog
        open={Boolean(selectedPositionType)}
        onOpenChange={(open) => !open && setSelectedPositionType(null)}
      >
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              {selectedPositionType
                ? getLocaleLabel(
                  selectedPositionType.name,
                  selectedPositionType.key,
                )
                : "Position type details"}
            </DialogTitle>
            <DialogDescription>
              {selectedPositionType
                ? `Review and update the permission set assigned to ${getLocaleLabel(selectedPositionType.name, selectedPositionType.key)}.`
                : undefined}
            </DialogDescription>
          </DialogHeader>

          {selectedPositionType ? (
            <div className="space-y-6">
              <div className="grid gap-4 rounded-2xl border border-border bg-muted/40 p-4 sm:grid-cols-2">
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Position type
                  </p>
                  <p className="mt-2 text-sm font-semibold text-foreground">
                    {getLocaleLabel(
                      selectedPositionType.name,
                      selectedPositionType.key,
                    )}
                  </p>
                </div>
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Key
                  </p>
                  <p className="mt-2 font-mono text-sm text-foreground">
                    {selectedPositionType.key}
                  </p>
                </div>
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Scope
                  </p>
                  <p className="mt-2 text-sm text-foreground">
                    {selectedPositionType.isSystem ? "System" : "Unit"}
                  </p>
                </div>
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Unit ID
                  </p>
                  <p className="mt-2 font-mono text-sm text-foreground">
                    {selectedPositionType.unitId ?? "-"}
                  </p>
                </div>
              </div>

              <div className="space-y-3">
                <div className="grid gap-4 rounded-2xl border border-border bg-muted/40 p-4 sm:grid-cols-2">
                  <label className="flex flex-col gap-2 text-sm">
                    <span className="font-medium text-foreground">
                      English name
                    </span>
                    <input
                      className={inputClassName}
                      value={editForm.nameEn}
                      onChange={(event) =>
                        setEditForm((current) => ({
                          ...current,
                          nameEn: event.target.value,
                        }))
                      }
                      disabled={selectedPositionType.isSystem}
                    />
                  </label>
                  <label className="flex flex-col gap-2 text-sm">
                    <span className="font-medium text-foreground">
                      Amharic name
                    </span>
                    <input
                      className={inputClassName}
                      value={editForm.nameAm}
                      onChange={(event) =>
                        setEditForm((current) => ({
                          ...current,
                          nameAm: event.target.value,
                        }))
                      }
                      disabled={selectedPositionType.isSystem}
                    />
                  </label>
                  <label className="flex flex-col gap-2 text-sm sm:col-span-2">
                    <span className="font-medium text-foreground">Key</span>
                    <input
                      className={inputClassName}
                      value={editForm.key}
                      onChange={(event) =>
                        setEditForm((current) => ({
                          ...current,
                          key: event.target.value,
                        }))
                      }
                      disabled={selectedPositionType.isSystem}
                    />
                  </label>
                  {selectedPositionType.isSystem ? (
                    <p className="text-xs text-muted-foreground sm:col-span-2">
                      System position types keep their name and key, but you can
                      still manage permissions here.
                    </p>
                  ) : null}
                </div>

                <div className="flex items-center justify-between gap-3">
                  <h2 className="text-sm font-semibold text-foreground">
                    Permissions
                  </h2>
                  <div className="rounded-full border border-border bg-muted px-3 py-1 text-xs font-medium text-muted-foreground">
                    {selectedPermissionIds.length} permissions selected
                  </div>
                </div>

                {permissionsLoading ? (
                  <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                    Loading position type permissions...
                  </div>
                ) : permissionsError ? (
                  <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-8 text-center text-sm text-red-700 dark:border-red-950 dark:bg-red-950/30 dark:text-red-300">
                    {permissionsError}
                  </div>
                ) : (
                  <div className="space-y-4">
                    <input
                      className={inputClassName}
                      value={permissionSearch}
                      onChange={(event) =>
                        setPermissionSearch(event.target.value)
                      }
                      placeholder="Search permissions by name or key"
                    />

                    <label className="flex items-center gap-2 rounded-xl border border-border bg-background px-3 py-2 text-sm">
                      <input
                        type="checkbox"
                        checked={areAllFilteredPermissionsSelected}
                        onChange={(event) => {
                          setSelectedPermissionIds((current) =>
                            toggleSelection(
                              current,
                              allFilteredPermissionIds,
                              event.target.checked,
                            ),
                          );
                        }}
                      />
                      <span className="font-medium text-foreground">
                        Select all
                      </span>
                    </label>

                    {loadingPermissionsCatalog ? (
                      <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                        Loading permissions catalog...
                      </div>
                    ) : filteredPermissions.length ? (
                      <div className="grid max-h-[420px] gap-2 overflow-y-auto pr-1 md:grid-cols-2 xl:grid-cols-3">
                        {filteredPermissions.map((permission) => (
                          <label
                            key={permission.id}
                            className="flex items-start gap-2 rounded-xl border border-border bg-background px-3 py-2 text-xs"
                          >
                            <input
                              type="checkbox"
                              checked={selectedPermissionIds.includes(
                                permission.id,
                              )}
                              onChange={(event) => {
                                setSelectedPermissionIds((current) =>
                                  event.target.checked
                                    ? [...current, permission.id]
                                    : current.filter(
                                      (item) => item !== permission.id,
                                    ),
                                );
                              }}
                            />
                            <div className="min-w-0 leading-4">
                              <div className="truncate font-medium text-foreground">
                                {getLocaleLabel(
                                  permission.name,
                                  permission.key,
                                )}
                              </div>
                              <div className="truncate text-xs text-muted-foreground">
                                {permission.key}
                              </div>
                            </div>
                          </label>
                        ))}
                      </div>
                    ) : (
                      <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                        No permissions match the current search.
                      </div>
                    )}

                    <div className="flex justify-end gap-2">
                      <button
                        type="button"
                        onClick={() => setSelectedPositionType(null)}
                        className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                      >
                        Close
                      </button>
                      <button
                        type="button"
                        disabled={submitting || loadingPermissionsCatalog}
                        onClick={() => void handleSavePositionTypeChanges()}
                        className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
                      >
                        Save changes
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          ) : null}
        </DialogContent>
      </Dialog>

      <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
        <DialogContent className="sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>Create position type</DialogTitle>
            <DialogDescription>
              Add a new position type for the selected unit and optionally copy
              permissions from an existing one.
            </DialogDescription>
          </DialogHeader>

          <form
            className="space-y-4"
            onSubmit={(event) => void handleCreatePositionType(event)}
          >
            <div className="grid gap-4 md:grid-cols-2">
              <label className="flex flex-col gap-2 text-sm">
                <span className="font-medium text-foreground">
                  English name
                </span>
                <input
                  className={inputClassName}
                  value={createForm.nameEn}
                  onChange={(event) =>
                    setCreateForm((current) => ({
                      ...current,
                      nameEn: event.target.value,
                    }))
                  }
                />
              </label>

              <label className="flex flex-col gap-2 text-sm">
                <span className="font-medium text-foreground">
                  Amharic name
                </span>
                <input
                  className={inputClassName}
                  value={createForm.nameAm}
                  onChange={(event) =>
                    setCreateForm((current) => ({
                      ...current,
                      nameAm: event.target.value,
                    }))
                  }
                />
              </label>

              <label className="flex flex-col gap-2 text-sm">
                <span className="font-medium text-foreground">Key</span>
                <input
                  className={inputClassName}
                  value={createForm.key}
                  onChange={(event) =>
                    setCreateForm((current) => ({
                      ...current,
                      key: event.target.value,
                    }))
                  }
                />
              </label>

              <label className="flex flex-col gap-2 text-sm">
                <span className="font-medium text-foreground">
                  Copy permissions from
                </span>
                <Select
                  value={createForm.copyPermissionFromId || undefined}
                  onValueChange={(value) => void handleSelectCopySource(value)}
                >
                  <SelectTrigger className="w-full rounded-xl bg-background">
                    <SelectValue placeholder="Optional" />
                  </SelectTrigger>
                  <SelectContent>
                    {availableCopySources.map((positionType) => (
                      <SelectItem key={positionType.id} value={positionType.id}>
                        {getLocaleLabel(positionType.name, positionType.key)}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </label>
            </div>

            <div className="space-y-3 rounded-2xl border border-border bg-background/60 p-4">
              <div className="flex items-center justify-between gap-3">
                <h2 className="text-sm font-semibold text-foreground">
                  Permissions
                </h2>
                <div className="rounded-full border border-border bg-muted px-3 py-1 text-xs font-medium text-muted-foreground">
                  {createPermissionIds.length} selected
                </div>
              </div>

              <input
                className={inputClassName}
                value={createPermissionSearch}
                onChange={(event) =>
                  setCreatePermissionSearch(event.target.value)
                }
                placeholder="Search permissions by name or key"
              />

              <label className="flex items-center gap-2 rounded-xl border border-border bg-background px-3 py-2 text-sm">
                <input
                  type="checkbox"
                  checked={areAllFilteredCreatePermissionsSelected}
                  onChange={(event) => {
                    setCreatePermissionIds((current) =>
                      toggleSelection(
                        current,
                        allFilteredCreatePermissionIds,
                        event.target.checked,
                      ),
                    );
                  }}
                />
                <span className="font-medium text-foreground">Select all</span>
              </label>

              {loadingPermissionsCatalog ? (
                <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                  Loading permissions catalog...
                </div>
              ) : filteredCreatePermissions.length ? (
                <div className="grid max-h-[320px] gap-2 overflow-y-auto pr-1 md:grid-cols-2 xl:grid-cols-3">
                  {filteredCreatePermissions.map((permission) => (
                    <label
                      key={permission.id}
                      className="flex items-start gap-2 rounded-xl border border-border bg-background px-3 py-2 text-xs"
                    >
                      <input
                        type="checkbox"
                        checked={createPermissionIds.includes(permission.id)}
                        onChange={(event) => {
                          setCreatePermissionIds((current) =>
                            event.target.checked
                              ? [...current, permission.id]
                              : current.filter(
                                (item) => item !== permission.id,
                              ),
                          );
                        }}
                      />
                      <div className="min-w-0 leading-4">
                        <div className="truncate font-medium text-foreground">
                          {getLocaleLabel(permission.name, permission.key)}
                        </div>
                        <div className="truncate text-xs text-muted-foreground">
                          {permission.key}
                        </div>
                      </div>
                    </label>
                  ))}
                </div>
              ) : (
                <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                  No permissions match the current search.
                </div>
              )}
            </div>

            {createForm.copyPermissionFromId ? (
              <div className="rounded-2xl border border-sky-200 bg-sky-50 px-4 py-3 text-sm text-sky-700 dark:border-sky-950 dark:bg-sky-950/30 dark:text-sky-300">
                <div className="flex items-center gap-2">
                  <CopyPlus className="h-4 w-4" />
                  The new position type will inherit permissions from the
                  selected source.
                </div>
              </div>
            ) : null}

            {createError ? (
              <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-950 dark:bg-red-950/30 dark:text-red-300">
                {createError}
              </div>
            ) : null}

            <div className="flex justify-end gap-2">
              <button
                type="button"
                onClick={() => setIsCreateOpen(false)}
                className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={submitting || !selectedUnitId}
                className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
              >
                Create position type
              </button>
            </div>
          </form>
        </DialogContent>
      </Dialog>
    </section>
  );
};

export default PositionTypesPage;
