import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@edr/ui-common";
import {
  Building2,
  ChevronRight,
  FolderTree,
  Network,
  Plus,
  RefreshCw,
  Save,
  Search,
  Trash2,
  UserPlus,
  Users,
} from "lucide-react";

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

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

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

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

interface PositionRecord {
  id: string;
  key: string;
  name: LocaleText;
  parentPositionId?: string | null;
  rank?: number;
}

interface EmployeeUserRecord {
  id: string;
  name?: LocaleText;
  email?: string;
  username?: string;
}

interface EmployeePositionSummary {
  id: string;
  position?: {
    id: string;
    name?: LocaleText;
  };
}

interface EmployeeRecord {
  id: string;
  name?: LocaleText;
  user?: EmployeeUserRecord;
  status?: string;
  employeePositions?: EmployeePositionSummary[];
}

interface PositionTreeNode extends PositionRecord {
  children: PositionTreeNode[];
}

interface PositionFormState {
  id?: string;
  nameEn: string;
  nameAm: string;
  key: string;
  parentPositionId: string;
}

interface EmployeeInviteFormState {
  nameEn: string;
  nameAm: string;
  email: string;
  username: string;
  phoneNumber: string;
}

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

const ORG_KEY = "edr_freight";
const emptyInviteForm: EmployeeInviteFormState = {
  nameEn: "",
  nameAm: "",
  email: "",
  username: "",
  phoneNumber: "",
};
const emptyPositionForm: PositionFormState = {
  nameEn: "",
  nameAm: "",
  key: "",
  parentPositionId: "",
};

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 getLocaleLabel = (value?: LocaleText | null, fallback = "Unnamed") => {
  if (!value) {
    return fallback;
  }

  return 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 toInternalKey = (value: string) =>
  value
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "_")
    .replace(/^_+|_+$/g, "")
    .replace(/_+/g, "_");

const buildTree = (positions: PositionRecord[]) => {
  const nodes = new Map<string, PositionTreeNode>();

  positions.forEach((position) => {
    nodes.set(position.id, { ...position, children: [] });
  });

  const roots: PositionTreeNode[] = [];

  nodes.forEach((node) => {
    if (node.parentPositionId) {
      const parent = nodes.get(node.parentPositionId);

      if (parent) {
        parent.children.push(node);
        return;
      }
    }

    roots.push(node);
  });

  const sortNodes = (items: PositionTreeNode[]) => {
    items.sort((left, right) => {
      const rankDiff = (left.rank ?? 0) - (right.rank ?? 0);
      if (rankDiff !== 0) {
        return rankDiff;
      }

      return getLocaleLabel(left.name, left.key).localeCompare(
        getLocaleLabel(right.name, right.key),
      );
    });

    items.forEach((item) => sortNodes(item.children));
  };

  sortNodes(roots);

  return roots;
};

const Field = ({ label, children }: { label: string; children: ReactNode }) => (
  <label className="flex flex-col gap-2 text-sm">
    <span className="font-medium text-foreground">{label}</span>
    {children}
  </label>
);

const ReadOnlyField = ({ label, value }: { label: string; value: string }) => (
  <div className="flex flex-col gap-2 text-sm">
    <span className="font-medium text-foreground">{label}</span>
    <div className="rounded-xl border border-border bg-muted px-3 py-2.5 text-sm text-card-foreground">
      {value || "-"}
    </div>
  </div>
);

const TreeNode = ({
  node,
  depth = 0,
  selectedPositionId,
  onSelect,
}: {
  node: PositionTreeNode;
  depth?: number;
  selectedPositionId: string | null;
  onSelect: (node: PositionRecord) => void;
}) => {
  const hasChildren = node.children.length > 0;
  const isSelected = selectedPositionId === node.id;

  return (
    <li>
      <button
        type="button"
        onClick={() => onSelect(node)}
        className={`flex w-full items-center gap-2 rounded-xl border px-3 py-2 text-left text-sm shadow-sm transition ${
          isSelected
            ? "border-emerald-300 bg-emerald-50 text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-100"
            : "border-border bg-card text-card-foreground hover:border-emerald-200 hover:bg-emerald-50/80 dark:hover:bg-slate-900"
        }`}
        style={{ marginLeft: depth * 14 }}
      >
        <span className="flex h-7 w-7 items-center justify-center rounded-lg bg-emerald-50 text-emerald-600 dark:bg-emerald-950/40 dark:text-emerald-300">
          {hasChildren ? <FolderTree className="h-4 w-4" /> : <Building2 className="h-4 w-4" />}
        </span>
        <div className="min-w-0 flex-1">
          <div className="truncate font-medium">{getLocaleLabel(node.name, node.key)}</div>
          <div className="truncate text-xs text-muted-foreground">{node.key}</div>
        </div>
        {hasChildren ? <ChevronRight className="h-4 w-4 text-muted-foreground" /> : null}
      </button>

      {hasChildren ? (
        <ul className="mt-2 space-y-2">
          {node.children.map((child) => (
            <TreeNode
              key={child.id}
              node={child}
              depth={depth + 1}
              selectedPositionId={selectedPositionId}
              onSelect={onSelect}
            />
          ))}
        </ul>
      ) : null}
    </li>
  );
};

const OrgStructurePage = () => {
  const navigate = useNavigate();
  const { unitId, section } = useParams();
  const activeSection = section === "employees" ? "employees" : "positions";

  const [organization, setOrganization] = useState<OrganizationRecord | null>(null);
  const [units, setUnits] = useState<UnitRecord[]>([]);
  const [positions, setPositions] = useState<PositionRecord[]>([]);
  const [orgEmployees, setOrgEmployees] = useState<EmployeeRecord[]>([]);
  const [positionMembers, setPositionMembers] = useState<EmployeeRecord[]>([]);
  const [selectedPositionId, setSelectedPositionId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [membersLoading, setMembersLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [actionError, setActionError] = useState<string | null>(null);
  const [actionSuccess, setActionSuccess] = useState<string | null>(null);
  const [unitSearch, setUnitSearch] = useState("");
  const [isCreateUnitOpen, setIsCreateUnitOpen] = useState(false);
  const [isCreatePositionOpen, setIsCreatePositionOpen] = useState(false);
  const [isInviteEmployeeOpen, setIsInviteEmployeeOpen] = useState(false);
  const [isUnitEditing, setIsUnitEditing] = useState(false);
  const [isPositionEditing, setIsPositionEditing] = useState(false);
  const [unitNameEn, setUnitNameEn] = useState("");
  const [unitNameAm, setUnitNameAm] = useState("");
  const [unitFormKey, setUnitFormKey] = useState("");
  const [createPositionMode, setCreatePositionMode] = useState<"create-root" | "create-child">(
    "create-root",
  );
  const [positionForm, setPositionForm] = useState<PositionFormState>(emptyPositionForm);
  const [inviteForm, setInviteForm] = useState<EmployeeInviteFormState>(emptyInviteForm);
  const [submitting, setSubmitting] = useState(false);

  const selectedUnit = useMemo(
    () => units.find((item) => item.id === unitId) ?? null,
    [unitId, units],
  );
  const tree = useMemo(() => buildTree(positions), [positions]);
  const selectedPosition = useMemo(
    () => positions.find((item) => item.id === selectedPositionId) ?? null,
    [positions, selectedPositionId],
  );
  const filteredUnits = useMemo(() => {
    const query = unitSearch.trim().toLowerCase();
    if (!query) {
      return units;
    }

    return units.filter((item) => {
      const label = getLocaleLabel(item.name, item.key).toLowerCase();
      return label.includes(query) || item.key.toLowerCase().includes(query);
    });
  }, [unitSearch, units]);
  const parentOptions = useMemo(
    () => positions.filter((item) => item.id !== selectedPositionId),
    [positions, selectedPositionId],
  );
  const selectedPositionParent = useMemo(
    () => positions.find((item) => item.id === selectedPosition?.parentPositionId) ?? null,
    [positions, selectedPosition],
  );

  const resetMessages = () => {
    setActionError(null);
    setActionSuccess(null);
  };

  const resetUnitForm = useCallback(() => {
    setUnitNameEn("");
    setUnitNameAm("");
    setUnitFormKey("");
  }, []);

  const syncUnitFormFromSelectedUnit = useCallback((unit: UnitRecord | null) => {
    setUnitNameEn(unit?.name.en ?? "");
    setUnitNameAm(unit?.name.am ?? "");
    setUnitFormKey(unit?.key ?? "");
  }, []);

  const syncPositionFormForCreate = useCallback(
    (mode: "create-root" | "create-child") => {
      setCreatePositionMode(mode);
      setPositionForm({
        ...emptyPositionForm,
        parentPositionId: mode === "create-child" && selectedPosition ? selectedPosition.id : "",
      });
    },
    [selectedPosition],
  );

  const syncPositionFormFromSelectedPosition = useCallback((position: PositionRecord | null) => {
    if (!position) {
      setPositionForm(emptyPositionForm);
      return;
    }

    setPositionForm({
      id: position.id,
      nameEn: position.name.en ?? "",
      nameAm: position.name.am ?? "",
      key: position.key,
      parentPositionId: position.parentPositionId ?? "",
    });
  }, []);

  const loadData = useCallback(async () => {
    setLoading(true);
    setError(null);

    try {
      const organizationsResponse = await api.get<ListResponse<OrganizationRecord>>("/organizations");
      const organizations = getItems(organizationsResponse.data);
      const currentOrganization = organizations.find((item) => item.key === ORG_KEY);

      if (!currentOrganization) {
        throw new Error("EDR Freight organization has not been seeded yet.");
      }

      const [unitsResponse, employeesResponse] = await Promise.all([
        api.get<ListResponse<UnitRecord>>(`/units/list/${currentOrganization.id}`),
        api.get<ListResponse<EmployeeRecord>>(`/employees/${currentOrganization.id}/by-organization`),
      ]);

      const currentUnits = getItems(unitsResponse.data);
      let unitPositions: PositionRecord[] = [];

      if (unitId) {
        const targetUnit = currentUnits.find((item) => item.id === unitId);
        if (targetUnit) {
          const positionsResponse = await api.get<ListResponse<PositionRecord>>(
            `/positions/list/${targetUnit.id}`,
          );
          unitPositions = getItems(positionsResponse.data);
        }
      }

      setOrganization(currentOrganization);
      setUnits(currentUnits);
      setPositions(unitPositions);
      setOrgEmployees(getItems(employeesResponse.data));
    } catch (loadError) {
      setError(
        loadError instanceof Error
          ? loadError.message
          : "Failed to load organization structure.",
      );
      setOrganization(null);
      setUnits([]);
      setPositions([]);
      setOrgEmployees([]);
    } finally {
      setLoading(false);
    }
  }, [unitId]);

  const loadPositionMembers = useCallback(async (positionId: string | null) => {
    if (!positionId) {
      setPositionMembers([]);
      return;
    }

    setMembersLoading(true);

    try {
      const response = await api.get<ListResponse<EmployeeRecord>>(
        `/positions/current/${positionId}/employees`,
      );
      setPositionMembers(getItems(response.data));
    } catch {
      setPositionMembers([]);
    } finally {
      setMembersLoading(false);
    }
  }, []);

  useEffect(() => {
    void loadData();
  }, [loadData]);

  useEffect(() => {
    if (!selectedUnit) {
      resetUnitForm();
      setSelectedPositionId(null);
      setIsUnitEditing(false);
      setIsPositionEditing(false);
      setIsCreateUnitOpen(false);
      setIsCreatePositionOpen(false);
      setIsInviteEmployeeOpen(false);
      return;
    }

    syncUnitFormFromSelectedUnit(selectedUnit);
    setIsUnitEditing(false);
    setIsPositionEditing(false);
    setIsCreatePositionOpen(false);
    setIsInviteEmployeeOpen(false);
  }, [resetUnitForm, selectedUnit, syncUnitFormFromSelectedUnit]);

  useEffect(() => {
    if (!positions.length) {
      setSelectedPositionId(null);
      setPositionMembers([]);
      setIsPositionEditing(false);
      return;
    }

    if (selectedPositionId && positions.some((item) => item.id === selectedPositionId)) {
      return;
    }

    setSelectedPositionId(positions[0].id);
  }, [positions, selectedPositionId]);

  useEffect(() => {
    if (!selectedPosition) {
      setIsPositionEditing(false);
      setIsInviteEmployeeOpen(false);
      setPositionForm(emptyPositionForm);
      setPositionMembers([]);
      return;
    }

    setIsPositionEditing(false);
    syncPositionFormFromSelectedPosition(selectedPosition);
    void loadPositionMembers(selectedPosition.id);
  }, [loadPositionMembers, selectedPosition, syncPositionFormFromSelectedPosition]);

  const goToUnit = (nextUnitId: string, nextSection = activeSection) => {
    navigate(`/dashboard/org-structure/units/${nextUnitId}/${nextSection}`);
  };

  const handleRefresh = async () => {
    resetMessages();
    await loadData();
  };

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

    if (!organization) {
      return;
    }

    setSubmitting(true);
    resetMessages();

    try {
      await api.post("/units", {
        name: { am: unitNameAm.trim(), en: unitNameEn.trim() },
        key: unitFormKey.trim(),
        organizationId: organization.id,
      });

      resetUnitForm();
      setActionSuccess("Unit created.");
      setIsCreateUnitOpen(false);
      await loadData();
    } catch (saveError) {
      setActionError(saveError instanceof Error ? saveError.message : "Failed to create unit.");
    } finally {
      setSubmitting(false);
    }
  };

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

    if (!organization || !selectedUnit) {
      return;
    }

    setSubmitting(true);
    resetMessages();

    try {
      await api.put(`/units/${selectedUnit.id}`, {
        name: { am: unitNameAm.trim(), en: unitNameEn.trim() },
        key: unitFormKey.trim(),
        organizationId: organization.id,
      });

      setActionSuccess("Unit updated.");
      setIsUnitEditing(false);
      await loadData();
    } catch (saveError) {
      setActionError(saveError instanceof Error ? saveError.message : "Failed to update unit.");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDeleteUnit = async () => {
    if (!selectedUnit || !window.confirm(`Delete unit '${getLocaleLabel(selectedUnit.name, selectedUnit.key)}'?`)) {
      return;
    }

    setSubmitting(true);
    resetMessages();

    try {
      await api.delete(`/units/${selectedUnit.id}`);
      setActionSuccess("Unit deleted.");
      setSelectedPositionId(null);
      navigate("/dashboard/org-structure");
      await loadData();
    } catch (deleteError) {
      setActionError(deleteError instanceof Error ? deleteError.message : "Failed to delete unit.");
    } finally {
      setSubmitting(false);
    }
  };

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

    if (!organization || !selectedUnit) {
      setActionError("Select a unit before managing positions.");
      return;
    }

    setSubmitting(true);
    resetMessages();

    try {
      const payload = {
        id: positionForm.id,
        name: { am: positionForm.nameAm.trim(), en: positionForm.nameEn.trim() },
        key: positionForm.key.trim(),
        unitId: selectedUnit.id,
        organizationId: organization.id,
        parentPositionId: positionForm.parentPositionId || null,
        rank: 0,
      };

      if (isPositionEditing && positionForm.id) {
        const existing = positions.find((item) => item.id === positionForm.id);
        await api.put(`/positions/${positionForm.id}`, payload);

        if ((existing?.parentPositionId ?? "") !== (positionForm.parentPositionId || "")) {
          await api.patch("/positions/change-parent", {
            positionId: positionForm.id,
            newParentId: positionForm.parentPositionId || null,
          });
        }

        setActionSuccess("Position updated.");
        setIsPositionEditing(false);
      } else {
        await api.post("/positions", payload);
        setActionSuccess("Position created.");
        syncPositionFormForCreate(createPositionMode);
        setIsCreatePositionOpen(false);
      }

      await loadData();
    } catch (saveError) {
      setActionError(
        saveError instanceof Error ? saveError.message : "Failed to save position.",
      );
    } finally {
      setSubmitting(false);
    }
  };

  const handleDeletePosition = async () => {
    if (!selectedPosition) {
      return;
    }

    if (!window.confirm(`Delete position '${getLocaleLabel(selectedPosition.name, selectedPosition.key)}'?`)) {
      return;
    }

    setSubmitting(true);
    resetMessages();

    try {
      await api.delete(`/positions/${selectedPosition.id}`);
      setActionSuccess("Position deleted.");
      await loadData();
    } catch (deleteError) {
      setActionError(
        deleteError instanceof Error ? deleteError.message : "Failed to delete position.",
      );
    } finally {
      setSubmitting(false);
    }
  };

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

    if (!selectedPosition) {
      setActionError("Select a position before inviting an employee.");
      return;
    }

    setSubmitting(true);
    resetMessages();

    try {
      await api.post("/employee-positions/invite", {
        positionId: selectedPosition.id,
        username: inviteForm.username.trim(),
        phoneNumber: inviteForm.phoneNumber.trim(),
        email: inviteForm.email.trim(),
        name: { am: inviteForm.nameAm.trim(), en: inviteForm.nameEn.trim() },
      });

      setInviteForm(emptyInviteForm);
      setActionSuccess("Employee invited and assigned to the selected position.");
      setIsInviteEmployeeOpen(false);
      await Promise.all([loadData(), loadPositionMembers(selectedPosition.id)]);
    } catch (inviteError) {
      setActionError(
        inviteError instanceof Error ? inviteError.message : "Failed to invite employee.",
      );
    } finally {
      setSubmitting(false);
    }
  };

  const positionMemberNames = positionMembers.map((item) => ({
    id: item.id,
    name: getLocaleLabel(item.name ?? item.user?.name, item.user?.email ?? item.id),
    email: item.user?.email,
  }));

  return (
    <section className="space-y-6 bg-background p-6 text-foreground">
      <div className="rounded-3xl border border-border bg-linear-to-br from-emerald-100 via-card to-background p-6 shadow-sm dark:from-emerald-950/30 dark:via-card dark:to-background">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div className="flex items-start gap-4">
            <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-100 text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300">
              <Network className="h-6 w-6" />
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium uppercase tracking-[0.2em] text-emerald-700 dark:text-emerald-300">
                Org structure
              </p>
              <h1 className="text-2xl font-semibold text-foreground">Organization management</h1>
              <p className="max-w-3xl text-sm text-muted-foreground">
                Manage units, department positions, and employee onboarding for EDR Freight from a
                single workspace.
              </p>
            </div>
          </div>

          <button
            type="button"
            onClick={() => void handleRefresh()}
            className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
          >
            <RefreshCw className="h-4 w-4" />
            Refresh
          </button>
        </div>
      </div>

      {actionSuccess ? (
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-200">
          {actionSuccess}
        </div>
      ) : null}

      {actionError ? (
        <div className="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700 dark:border-rose-900/60 dark:bg-rose-950/40 dark:text-rose-200">
          {actionError}
        </div>
      ) : null}

      {loading ? (
        <div className="rounded-3xl border border-border bg-card p-6 text-sm text-muted-foreground shadow-sm">
          Loading organization structure...
        </div>
      ) : null}

      {!loading && error ? (
        <div className="rounded-3xl border border-rose-200 bg-rose-50 p-6 text-sm text-rose-700 shadow-sm dark:border-rose-900/60 dark:bg-rose-950/40 dark:text-rose-200">
          {error}
        </div>
      ) : null}

      {!loading && !error ? (
        <div className="grid gap-6 xl:grid-cols-[340px_minmax(0,1fr)]">
          <aside className="rounded-3xl border border-border bg-card p-5 shadow-sm">
            <div className="mb-5 flex items-center justify-between gap-3">
              <div>
                <h2 className="text-lg font-semibold text-card-foreground">Units</h2>
                <p className="text-sm text-muted-foreground">
                  {organization ? getLocaleLabel(organization.name, organization.key) : ORG_KEY}
                </p>
              </div>
              <button
                type="button"
                onClick={() => {
                  resetUnitForm();
                  resetMessages();
                  setIsCreateUnitOpen(true);
                }}
                className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
              >
                <Plus className="h-4 w-4" />
                Add
              </button>
            </div>

            <div className="relative mb-4">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <input
                className={`${inputClassName} pl-9`}
                value={unitSearch}
                onChange={(event) => setUnitSearch(event.target.value)}
                placeholder="Search units"
              />
            </div>

            {filteredUnits.length ? (
              <ul className="space-y-2">
                {filteredUnits.map((item) => {
                  const isActive = selectedUnit?.id === item.id;

                  return (
                    <li key={item.id}>
                      <button
                        type="button"
                        onClick={() => goToUnit(item.id)}
                        className={`flex w-full items-center justify-between rounded-2xl border px-4 py-3 text-left transition ${
                          isActive
                            ? "border-emerald-300 bg-emerald-50 text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-100"
                            : "border-border bg-card text-card-foreground hover:border-emerald-200 hover:bg-emerald-50/80 dark:hover:bg-slate-900"
                        }`}
                      >
                        <div className="min-w-0">
                          <div className="truncate font-medium">{getLocaleLabel(item.name, item.key)}</div>
                          <div className="truncate text-xs text-muted-foreground">{item.key}</div>
                        </div>
                        <ChevronRight className="h-4 w-4 text-muted-foreground" />
                      </button>
                    </li>
                  );
                })}
              </ul>
            ) : (
              <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                No units found.
              </div>
            )}
          </aside>

          <div className="space-y-6">
            {selectedUnit ? (
              <>
                <section className="rounded-3xl border border-border bg-card p-6 shadow-sm">
                  <div className="mb-5 flex flex-wrap items-center justify-between gap-3">
                    <div>
                      <h2 className="text-xl font-semibold text-card-foreground">
                        {getLocaleLabel(selectedUnit.name, selectedUnit.key)}
                      </h2>
                      <p className="text-sm text-muted-foreground">{selectedUnit.key}</p>
                    </div>
                    <div className="flex gap-2">
                      <button
                        type="button"
                        disabled={submitting}
                        onClick={() => {
                          resetMessages();
                          syncUnitFormFromSelectedUnit(selectedUnit);
                          setIsUnitEditing(true);
                        }}
                        className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                      >
                        Edit
                      </button>
                      <button
                        type="button"
                        disabled={submitting}
                        onClick={() => void handleDeleteUnit()}
                        className={`${buttonClassName} border border-rose-300 bg-card text-rose-700 hover:bg-rose-50 dark:border-rose-900 dark:text-rose-300 dark:hover:bg-rose-950/30`}
                      >
                        <Trash2 className="h-4 w-4" />
                        Delete unit
                      </button>
                    </div>
                  </div>

                  {isUnitEditing ? (
                    <form className="grid gap-4 md:grid-cols-2" onSubmit={handleUpdateUnit}>
                      <Field label="Unit name (EN)">
                        <input
                          className={inputClassName}
                          value={unitNameEn}
                          onChange={(event) => setUnitNameEn(event.target.value)}
                          required
                        />
                      </Field>
                      <Field label="Unit name (AM)">
                        <input
                          className={inputClassName}
                          value={unitNameAm}
                          onChange={(event) => setUnitNameAm(event.target.value)}
                          required
                        />
                      </Field>
                      <Field label="Unit key">
                        <div className="flex gap-2">
                          <input
                            className={inputClassName}
                            value={unitFormKey}
                            onChange={(event) => setUnitFormKey(event.target.value)}
                            required
                          />
                          <button
                            type="button"
                            onClick={() => setUnitFormKey(toInternalKey(unitNameEn))}
                            className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                          >
                            Key
                          </button>
                        </div>
                      </Field>
                      <div className="md:col-span-2 flex flex-wrap gap-3">
                        <button
                          type="submit"
                          disabled={submitting || !unitNameEn.trim() || !unitNameAm.trim() || !unitFormKey.trim()}
                          className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
                        >
                          <Save className="h-4 w-4" />
                          Save unit
                        </button>
                        <button
                          type="button"
                          disabled={submitting}
                          onClick={() => {
                            syncUnitFormFromSelectedUnit(selectedUnit);
                            setIsUnitEditing(false);
                          }}
                          className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                        >
                          Cancel
                        </button>
                      </div>
                    </form>
                  ) : (
                    <div className="grid gap-4 md:grid-cols-2">
                      <ReadOnlyField
                        label="Unit name (EN)"
                        value={selectedUnit.name.en ?? getLocaleLabel(selectedUnit.name, selectedUnit.key)}
                      />
                      <ReadOnlyField label="Unit name (AM)" value={selectedUnit.name.am ?? ""} />
                      <ReadOnlyField label="Unit key" value={selectedUnit.key} />
                    </div>
                  )}
                </section>

                <section className="rounded-3xl border border-border bg-card p-6 shadow-sm">
                  <div className="mb-5 flex flex-wrap items-center justify-between gap-3 border-b border-border pb-4">
                    <div className="flex gap-2">
                      <button
                        type="button"
                        onClick={() => goToUnit(selectedUnit.id, "positions")}
                        className={`${buttonClassName} ${
                          activeSection === "positions"
                            ? "bg-emerald-600 text-white hover:bg-emerald-700"
                            : "border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground"
                        }`}
                      >
                        <Building2 className="h-4 w-4" />
                        Positions
                      </button>
                      <button
                        type="button"
                        onClick={() => goToUnit(selectedUnit.id, "employees")}
                        className={`${buttonClassName} ${
                          activeSection === "employees"
                            ? "bg-emerald-600 text-white hover:bg-emerald-700"
                            : "border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground"
                        }`}
                      >
                        <Users className="h-4 w-4" />
                        Employees
                      </button>
                    </div>
                  </div>

                  {activeSection === "positions" ? (
                    <div className="grid gap-6 xl:grid-cols-[minmax(0,1.1fr)_360px]">
                      <div>
                        <div className="mb-4 flex flex-wrap gap-2">
                          <button
                            type="button"
                            disabled={submitting}
                            onClick={() => {
                              resetMessages();
                              syncPositionFormForCreate("create-root");
                              setIsCreatePositionOpen(true);
                            }}
                            className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                          >
                            <Plus className="h-4 w-4" />
                            Add root
                          </button>
                          <button
                            type="button"
                            disabled={submitting || !selectedPosition}
                            onClick={() => {
                              resetMessages();
                              syncPositionFormForCreate("create-child");
                              setIsCreatePositionOpen(true);
                            }}
                            className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                          >
                            <Plus className="h-4 w-4" />
                            Add child
                          </button>
                        </div>

                        {tree.length ? (
                          <ul className="space-y-3">
                            {tree.map((node) => (
                              <TreeNode
                                key={node.id}
                                node={node}
                                selectedPositionId={selectedPositionId}
                                onSelect={(position) => {
                                  resetMessages();
                                  setSelectedPositionId(position.id);
                                }}
                              />
                            ))}
                          </ul>
                        ) : (
                          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                            No positions yet. Create the first root position for this unit.
                          </div>
                        )}
                      </div>

                      <div className="space-y-4">
                        <div className="rounded-2xl border border-border bg-muted p-4">
                          <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
                            <div>
                              <div className="text-sm font-medium text-foreground">Position details</div>
                              <div className="text-sm text-muted-foreground">
                                {selectedPosition
                                  ? "View a selected position and edit it only when needed."
                                  : "Select a position from the tree to inspect its details."}
                              </div>
                            </div>
                            {selectedPosition ? (
                              <div className="flex flex-wrap gap-2">
                                <button
                                  type="button"
                                  disabled={submitting}
                                  onClick={() => {
                                    resetMessages();
                                    syncPositionFormFromSelectedPosition(selectedPosition);
                                    setIsPositionEditing(true);
                                  }}
                                  className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                                >
                                  Edit
                                </button>
                                <button
                                  type="button"
                                  disabled={submitting}
                                  onClick={() => void handleDeletePosition()}
                                  className={`${buttonClassName} border border-rose-300 bg-card text-rose-700 hover:bg-rose-50 dark:border-rose-900 dark:text-rose-300 dark:hover:bg-rose-950/30`}
                                >
                                  <Trash2 className="h-4 w-4" />
                                  Delete selected
                                </button>
                              </div>
                            ) : null}
                          </div>

                          {selectedPosition ? (
                            isPositionEditing ? (
                              <form className="space-y-4" onSubmit={handleSavePosition}>
                                <Field label="Position name (EN)">
                                  <input
                                    className={inputClassName}
                                    value={positionForm.nameEn}
                                    onChange={(event) =>
                                      setPositionForm((current) => ({ ...current, nameEn: event.target.value }))
                                    }
                                    placeholder="Dispatch"
                                    required
                                  />
                                </Field>
                                <Field label="Position name (AM)">
                                  <input
                                    className={inputClassName}
                                    value={positionForm.nameAm}
                                    onChange={(event) =>
                                      setPositionForm((current) => ({ ...current, nameAm: event.target.value }))
                                    }
                                    placeholder="ዲስፓች"
                                    required
                                  />
                                </Field>
                                <Field label="Position key">
                                  <div className="flex gap-2">
                                    <input
                                      className={inputClassName}
                                      value={positionForm.key}
                                      onChange={(event) =>
                                        setPositionForm((current) => ({ ...current, key: event.target.value }))
                                      }
                                      placeholder="dispatch"
                                      required
                                    />
                                    <button
                                      type="button"
                                      onClick={() =>
                                        setPositionForm((current) => ({
                                          ...current,
                                          key: toInternalKey(current.nameEn),
                                        }))
                                      }
                                      className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                                    >
                                      Key
                                    </button>
                                  </div>
                                </Field>
                                <Field label="Parent position">
                                  <select
                                    className={inputClassName}
                                    value={positionForm.parentPositionId}
                                    onChange={(event) =>
                                      setPositionForm((current) => ({
                                        ...current,
                                        parentPositionId: event.target.value,
                                      }))
                                    }
                                  >
                                    <option value="">No parent (root position)</option>
                                    {parentOptions.map((item) => (
                                      <option key={item.id} value={item.id}>
                                        {getLocaleLabel(item.name, item.key)}
                                      </option>
                                    ))}
                                  </select>
                                </Field>
                                <div className="flex flex-wrap gap-3">
                                  <button
                                    type="submit"
                                    disabled={
                                      submitting ||
                                      !positionForm.nameEn.trim() ||
                                      !positionForm.nameAm.trim() ||
                                      !positionForm.key.trim()
                                    }
                                    className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
                                  >
                                    <Save className="h-4 w-4" />
                                    Save position
                                  </button>
                                  <button
                                    type="button"
                                    disabled={submitting}
                                    onClick={() => {
                                      syncPositionFormFromSelectedPosition(selectedPosition);
                                      setIsPositionEditing(false);
                                    }}
                                    className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                                  >
                                    Cancel
                                  </button>
                                </div>
                              </form>
                            ) : (
                              <div className="grid gap-4">
                                <ReadOnlyField
                                  label="Position name (EN)"
                                  value={selectedPosition.name.en ?? getLocaleLabel(selectedPosition.name, selectedPosition.key)}
                                />
                                <ReadOnlyField label="Position name (AM)" value={selectedPosition.name.am ?? ""} />
                                <ReadOnlyField label="Position key" value={selectedPosition.key} />
                                <ReadOnlyField
                                  label="Parent position"
                                  value={selectedPositionParent
                                    ? getLocaleLabel(
                                        selectedPositionParent.name,
                                        selectedPositionParent.key,
                                      )
                                    : "No parent (root position)"}
                                />
                              </div>
                            )
                          ) : (
                            <div className="rounded-2xl border border-dashed border-border bg-card px-4 py-8 text-center text-sm text-muted-foreground">
                              Select a position from the tree to view its details.
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  ) : (
                    <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
                      <div className="space-y-6">
                        <section className="rounded-2xl border border-border bg-muted p-4">
                          <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
                            <div className="flex items-center gap-2">
                              <UserPlus className="h-5 w-5 text-emerald-600 dark:text-emerald-300" />
                              <h3 className="text-base font-semibold text-card-foreground">
                                Invite employee
                              </h3>
                            </div>
                            <button
                              type="button"
                              disabled={submitting || !selectedPosition}
                              onClick={() => {
                                resetMessages();
                                setInviteForm(emptyInviteForm);
                                setIsInviteEmployeeOpen(true);
                              }}
                              className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
                            >
                              <UserPlus className="h-4 w-4" />
                              Invite employee
                            </button>
                          </div>
                          {selectedPosition ? (
                            <div className="space-y-3 text-sm text-muted-foreground">
                              <p>
                                New users are created during onboarding and assigned directly to the selected position.
                              </p>
                              <ReadOnlyField
                                label="Target position"
                                value={getLocaleLabel(selectedPosition.name, selectedPosition.key)}
                              />
                            </div>
                          ) : (
                            <p className="text-sm text-muted-foreground">
                              Select a position from the tree first, then onboard employees into it.
                            </p>
                          )}
                        </section>

                        <section>
                          <h3 className="mb-3 text-base font-semibold text-card-foreground">
                            Organization employees
                          </h3>
                          {orgEmployees.length ? (
                            <ul className="space-y-3">
                              {orgEmployees.map((employee) => (
                                <li
                                  key={employee.id}
                                  className="rounded-2xl border border-border bg-muted px-4 py-3"
                                >
                                  <div className="font-medium text-card-foreground">
                                    {getLocaleLabel(employee.name ?? employee.user?.name, employee.id)}
                                  </div>
                                  <div className="text-sm text-muted-foreground">
                                    {employee.user?.email ?? employee.user?.username ?? "No login details"}
                                  </div>
                                  {employee.employeePositions?.length ? (
                                    <div className="mt-2 text-xs text-muted-foreground">
                                      {employee.employeePositions
                                        .map((item) => getLocaleLabel(item.position?.name, item.id))
                                        .join(", ")}
                                    </div>
                                  ) : null}
                                </li>
                              ))}
                            </ul>
                          ) : (
                            <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                              No employees have been onboarded yet.
                            </div>
                          )}
                        </section>
                      </div>

                      <aside className="space-y-6">
                        <section className="rounded-2xl border border-border bg-muted p-4">
                          <h3 className="text-base font-semibold text-card-foreground">
                            Position picker
                          </h3>
                          <p className="mt-1 text-sm text-muted-foreground">
                            Employees are invited into a position inside the selected unit.
                          </p>
                          {tree.length ? (
                            <ul className="mt-4 space-y-3">
                              {tree.map((node) => (
                                <TreeNode
                                  key={node.id}
                                  node={node}
                                  selectedPositionId={selectedPositionId}
                                  onSelect={(position) => setSelectedPositionId(position.id)}
                                />
                              ))}
                            </ul>
                          ) : (
                            <p className="mt-4 text-sm text-muted-foreground">
                              Add positions first before onboarding employees.
                            </p>
                          )}
                        </section>

                        <section className="rounded-2xl border border-border bg-muted p-4">
                          <h3 className="text-base font-semibold text-card-foreground">
                            Position members
                          </h3>
                          {membersLoading ? (
                            <p className="mt-4 text-sm text-muted-foreground">Loading members...</p>
                          ) : positionMemberNames.length ? (
                            <ul className="mt-4 space-y-3">
                              {positionMemberNames.map((member) => (
                                <li
                                  key={member.id}
                                  className="rounded-2xl border border-border bg-card px-4 py-3"
                                >
                                  <div className="font-medium text-card-foreground">{member.name}</div>
                                  <div className="text-sm text-muted-foreground">
                                    {member.email ?? "No email recorded"}
                                  </div>
                                </li>
                              ))}
                            </ul>
                          ) : (
                            <p className="mt-4 text-sm text-muted-foreground">
                              No active members for the selected position yet.
                            </p>
                          )}
                        </section>
                      </aside>
                    </div>
                  )}
                </section>
              </>
            ) : (
              <section className="rounded-3xl border border-dashed border-border bg-muted p-10 text-center shadow-sm">
                <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-emerald-100 text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300">
                  <Network className="h-6 w-6" />
                </div>
                <h2 className="mt-5 text-xl font-semibold text-card-foreground">
                  Choose a unit to manage
                </h2>
                <p className="mx-auto mt-2 max-w-xl text-sm text-muted-foreground">
                  Use the unit list on the left to manage positions and employees strictly inside one selected unit.
                </p>
              </section>
            )}
          </div>
        </div>
      ) : null}

      <Dialog
        open={isCreateUnitOpen}
        onOpenChange={(open) => {
          setIsCreateUnitOpen(open);
          if (!open) {
            resetUnitForm();
          }
        }}
      >
        <DialogContent className="max-h-[90vh] overflow-y-auto rounded-3xl sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle className="text-2xl font-bold">Create unit</DialogTitle>
            <DialogDescription>
              Add a new unit under the EDR Freight organization.
            </DialogDescription>
          </DialogHeader>
          <form className="space-y-4" onSubmit={handleCreateUnit}>
            <Field label="Unit name (EN)">
              <input
                className={inputClassName}
                value={unitNameEn}
                onChange={(event) => setUnitNameEn(event.target.value)}
                placeholder="Operations"
                required
              />
            </Field>
            <Field label="Unit name (AM)">
              <input
                className={inputClassName}
                value={unitNameAm}
                onChange={(event) => setUnitNameAm(event.target.value)}
                placeholder="ኦፕሬሽንስ"
                required
              />
            </Field>
            <Field label="Unit key">
              <div className="flex gap-2">
                <input
                  className={inputClassName}
                  value={unitFormKey}
                  onChange={(event) => setUnitFormKey(event.target.value)}
                  placeholder="operations"
                  required
                />
                <button
                  type="button"
                  onClick={() => setUnitFormKey(toInternalKey(unitNameEn))}
                  className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                >
                  Key
                </button>
              </div>
            </Field>
            <div className="flex flex-wrap gap-3">
              <button
                type="submit"
                disabled={submitting || !unitNameEn.trim() || !unitNameAm.trim() || !unitFormKey.trim()}
                className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
              >
                <Save className="h-4 w-4" />
                Create unit
              </button>
              <button
                type="button"
                onClick={() => {
                  resetUnitForm();
                  setIsCreateUnitOpen(false);
                }}
                className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
              >
                Cancel
              </button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog
        open={isCreatePositionOpen}
        onOpenChange={(open) => {
          setIsCreatePositionOpen(open);
          if (!open) {
            syncPositionFormForCreate(createPositionMode);
          }
        }}
      >
        <DialogContent className="max-h-[90vh] overflow-y-auto rounded-3xl sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle className="text-2xl font-bold">
              {createPositionMode === "create-child" ? "Create child position" : "Create root position"}
            </DialogTitle>
            <DialogDescription>
              {createPositionMode === "create-child"
                ? "Add a child position under the currently selected position."
                : "Add a top-level position for the selected unit."}
            </DialogDescription>
          </DialogHeader>
          <form className="space-y-4" onSubmit={handleSavePosition}>
            <Field label="Position name (EN)">
              <input
                className={inputClassName}
                value={positionForm.nameEn}
                onChange={(event) =>
                  setPositionForm((current) => ({ ...current, nameEn: event.target.value }))
                }
                placeholder="Dispatch"
                required
              />
            </Field>
            <Field label="Position name (AM)">
              <input
                className={inputClassName}
                value={positionForm.nameAm}
                onChange={(event) =>
                  setPositionForm((current) => ({ ...current, nameAm: event.target.value }))
                }
                placeholder="ዲስፓች"
                required
              />
            </Field>
            <Field label="Position key">
              <div className="flex gap-2">
                <input
                  className={inputClassName}
                  value={positionForm.key}
                  onChange={(event) =>
                    setPositionForm((current) => ({ ...current, key: event.target.value }))
                  }
                  placeholder="dispatch"
                  required
                />
                <button
                  type="button"
                  onClick={() =>
                    setPositionForm((current) => ({
                      ...current,
                      key: toInternalKey(current.nameEn),
                    }))
                  }
                  className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                >
                  Key
                </button>
              </div>
            </Field>
            <Field label="Parent position">
              <select
                className={inputClassName}
                value={positionForm.parentPositionId}
                onChange={(event) =>
                  setPositionForm((current) => ({
                    ...current,
                    parentPositionId: event.target.value,
                  }))
                }
              >
                <option value="">No parent (root position)</option>
                {parentOptions.map((item) => (
                  <option key={item.id} value={item.id}>
                    {getLocaleLabel(item.name, item.key)}
                  </option>
                ))}
              </select>
            </Field>
            <div className="flex flex-wrap gap-3">
              <button
                type="submit"
                disabled={
                  submitting ||
                  !positionForm.nameEn.trim() ||
                  !positionForm.nameAm.trim() ||
                  !positionForm.key.trim()
                }
                className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
              >
                <Save className="h-4 w-4" />
                Create position
              </button>
              <button
                type="button"
                disabled={submitting}
                onClick={() => {
                  syncPositionFormForCreate(createPositionMode);
                  setIsCreatePositionOpen(false);
                }}
                className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
              >
                Cancel
              </button>
            </div>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog
        open={isInviteEmployeeOpen}
        onOpenChange={(open) => {
          setIsInviteEmployeeOpen(open);
          if (!open) {
            setInviteForm(emptyInviteForm);
          }
        }}
      >
        <DialogContent className="max-h-[90vh] overflow-y-auto rounded-3xl sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle className="text-2xl font-bold">Invite employee</DialogTitle>
            <DialogDescription>
              Create a new employee account and assign it directly to the selected position.
            </DialogDescription>
          </DialogHeader>
          <form className="space-y-4" onSubmit={handleInviteEmployee}>
            <Field label="Target position">
              <div className="rounded-xl border border-border bg-muted px-3 py-2.5 text-sm text-card-foreground">
                {selectedPosition ? getLocaleLabel(selectedPosition.name, selectedPosition.key) : "No position selected"}
              </div>
            </Field>
            <Field label="Full name (EN)">
              <input
                className={inputClassName}
                value={inviteForm.nameEn}
                onChange={(event) =>
                  setInviteForm((current) => ({ ...current, nameEn: event.target.value }))
                }
                required
              />
            </Field>
            <Field label="Full name (AM)">
              <input
                className={inputClassName}
                value={inviteForm.nameAm}
                onChange={(event) =>
                  setInviteForm((current) => ({ ...current, nameAm: event.target.value }))
                }
                required
              />
            </Field>
            <Field label="Email">
              <input
                type="email"
                className={inputClassName}
                value={inviteForm.email}
                onChange={(event) =>
                  setInviteForm((current) => ({ ...current, email: event.target.value }))
                }
                required
              />
            </Field>
            <Field label="Username">
              <input
                className={inputClassName}
                value={inviteForm.username}
                onChange={(event) =>
                  setInviteForm((current) => ({ ...current, username: event.target.value }))
                }
                required
              />
            </Field>
            <Field label="Phone number">
              <input
                className={inputClassName}
                value={inviteForm.phoneNumber}
                onChange={(event) =>
                  setInviteForm((current) => ({ ...current, phoneNumber: event.target.value }))
                }
                required
              />
            </Field>
            <div className="flex flex-wrap gap-3">
              <button
                type="submit"
                disabled={submitting || !selectedPosition}
                className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
              >
                <UserPlus className="h-4 w-4" />
                Invite and assign
              </button>
              <button
                type="button"
                disabled={submitting}
                onClick={() => {
                  setInviteForm(emptyInviteForm);
                  setIsInviteEmployeeOpen(false);
                }}
                className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
              >
                Cancel
              </button>
            </div>
          </form>
        </DialogContent>
      </Dialog>
    </section>
  );
};

export default OrgStructurePage;
