"use client";

import { useState } from "react";
import { AnimatedModal } from "~/components/ui/AnimatedModal.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
import { trpc } from "~/lib/trpc/client.js";

type OrgUnitRow = {
  id: string;
  name: string;
  shortName: string | null;
  level: number;
  parentId: string | null;
  sortOrder: number;
  isActive: boolean;
};

type OrgUnitNode = OrgUnitRow & { children: OrgUnitNode[] };

type EditingUnit = {
  id?: string;
  name: string;
  shortName: string;
  level: number;
  parentId: string;
  sortOrder: number;
};

const LEVEL_LABELS: Record<number, string> = { 5: "L5 — Division", 6: "L6 — Department", 7: "L7 — Team" };
const LEVEL_COLORS: Record<number, string> = {
  5: "bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-400",
  6: "bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-400",
  7: "bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400",
};

function TreeNode({
  node,
  onEdit,
  depth = 0,
}: {
  node: OrgUnitNode;
  onEdit: (u: OrgUnitRow) => void;
  depth?: number;
}) {
  const [expanded, setExpanded] = useState(true);
  const hasChildren = node.children.length > 0;

  return (
    <div>
      <div
        className="flex items-center gap-2 py-2 px-3 hover:bg-gray-50 dark:hover:bg-gray-800/30 rounded-lg group"
        style={{ paddingLeft: `${depth * 24 + 12}px` }}
      >
        {hasChildren ? (
          <button
            type="button"
            onClick={() => setExpanded(!expanded)}
            className="w-5 h-5 flex items-center justify-center text-gray-400 hover:text-gray-600 text-xs"
          >
            {expanded ? "▼" : "▶"}
          </button>
        ) : (
          <span className="w-5" />
        )}
        <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${LEVEL_COLORS[node.level] ?? "bg-gray-100 text-gray-600"}`}>
          L{node.level}
        </span>
        <span className="text-sm font-medium text-gray-900 dark:text-gray-100 flex-1">
          {node.name}
          {node.shortName && <span className="text-gray-400 ml-1">({node.shortName})</span>}
        </span>
        {!node.isActive && (
          <span className="text-xs text-gray-400 italic">inactive</span>
        )}
        <button
          type="button"
          onClick={() => onEdit(node)}
          className="text-xs text-brand-600 hover:text-brand-800 font-medium opacity-0 group-hover:opacity-100 transition-opacity"
        >
          Edit
        </button>
      </div>
      {expanded && node.children.map((child) => (
        <TreeNode key={child.id} node={child} onEdit={onEdit} depth={depth + 1} />
      ))}
    </div>
  );
}

export function OrgUnitsClient() {
  const [editing, setEditing] = useState<EditingUnit | null>(null);
  const [error, setError] = useState<string | null>(null);

  const utils = trpc.useUtils();
  const { data: tree, isLoading } = trpc.orgUnit.getTree.useQuery();
  const { data: flatList } = trpc.orgUnit.list.useQuery();

  const createMut = trpc.orgUnit.create.useMutation({
    onSuccess: () => { void utils.orgUnit.getTree.invalidate(); void utils.orgUnit.list.invalidate(); setEditing(null); },
    onError: (e) => setError(e.message),
  });
  const updateMut = trpc.orgUnit.update.useMutation({
    onSuccess: () => { void utils.orgUnit.getTree.invalidate(); void utils.orgUnit.list.invalidate(); setEditing(null); },
    onError: (e) => setError(e.message),
  });

  const allUnits = (flatList ?? []) as unknown as OrgUnitRow[];

  function openCreate(level: number, parentId?: string) {
    setEditing({
      name: "",
      shortName: "",
      level,
      parentId: parentId ?? "",
      sortOrder: 0,
    });
    setError(null);
  }

  function openEdit(u: OrgUnitRow) {
    setEditing({
      id: u.id,
      name: u.name,
      shortName: u.shortName ?? "",
      level: u.level,
      parentId: u.parentId ?? "",
      sortOrder: u.sortOrder,
    });
    setError(null);
  }

  function handleSave() {
    if (!editing) return;
    setError(null);

    if (editing.id) {
      updateMut.mutate({
        id: editing.id,
        data: {
          name: editing.name,
          shortName: editing.shortName || undefined,
          sortOrder: editing.sortOrder,
          parentId: editing.parentId || undefined,
        },
      });
    } else {
      createMut.mutate({
        name: editing.name,
        shortName: editing.shortName || undefined,
        level: editing.level,
        parentId: editing.parentId || undefined,
        sortOrder: editing.sortOrder,
      });
    }
  }

  // Possible parents for the editing unit (must be lower level number)
  const possibleParents = editing
    ? allUnits.filter((u) => u.level < editing.level && u.isActive)
    : [];

  const isPending = createMut.isPending || updateMut.isPending;
  const treeNodes = (tree ?? []) as unknown as OrgUnitNode[];

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-50">Org Units</h1>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            3-level hierarchy: L5 (Division) → L6 (Department) → L7 (Team) <InfoTooltip content="Org units define the organizational structure. Resources are assigned to L7 teams, which roll up to L6 departments and L5 divisions. Used for capacity planning, reporting, and access control." />
          </p>
        </div>
        <div className="flex gap-2">
          <button type="button" onClick={() => openCreate(5)} className="px-3 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 text-sm font-medium">+ L5</button>
          <button type="button" onClick={() => openCreate(6)} className="px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium">+ L6</button>
          <button type="button" onClick={() => openCreate(7)} className="px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm font-medium">+ L7</button>
        </div>
      </div>

      {error && (
        <div className="mb-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 px-4 py-3 text-sm text-red-700 dark:text-red-400 flex items-center justify-between">
          {error}
          <button type="button" onClick={() => setError(null)} className="text-red-400 hover:text-red-600 text-lg leading-none">&times;</button>
        </div>
      )}

      <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 p-2">
        {isLoading && <div className="text-center py-8 text-gray-400">Loading...</div>}
        {!isLoading && treeNodes.length === 0 && (
          <div className="text-center py-8 text-gray-400">No org units yet. Start by adding an L5 division.</div>
        )}
        {treeNodes.map((node) => (
          <TreeNode key={node.id} node={node} onEdit={openEdit} />
        ))}
      </div>

      {/* Create/Edit Modal */}
      <AnimatedModal open={editing !== null} onClose={() => setEditing(null)} maxWidth="max-w-md">
        {editing && (<>
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                {editing.id ? "Edit Org Unit" : `Add ${LEVEL_LABELS[editing.level] ?? `L${editing.level}`}`}
              </h2>
              <button type="button" onClick={() => setEditing(null)} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-2xl leading-none">&times;</button>
            </div>

            <div className="px-6 py-5 space-y-4">
              <div>
                <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Name <InfoTooltip content="The full name of this organizational unit." /></label>
                <input
                  type="text"
                  value={editing.name}
                  onChange={(e) => setEditing({ ...editing, name: e.target.value })}
                  placeholder="e.g. Content Production"
                  className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Short Name <InfoTooltip content="An abbreviation for compact views and exports (e.g. 'CP' for Content Production)." /></label>
                  <input
                    type="text"
                    value={editing.shortName}
                    onChange={(e) => setEditing({ ...editing, shortName: e.target.value })}
                    placeholder="CP"
                    className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                  />
                </div>
                <div>
                  <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Sort Order <InfoTooltip content="Controls the display order among siblings. Lower numbers appear first." /></label>
                  <input
                    type="number"
                    value={editing.sortOrder}
                    onChange={(e) => setEditing({ ...editing, sortOrder: parseInt(e.target.value) || 0 })}
                    className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                  />
                </div>
              </div>

              {editing.level > 5 && (
                <div>
                  <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Parent Unit <InfoTooltip content="The parent org unit in the hierarchy. L6 departments must belong to an L5 division; L7 teams must belong to an L6 department." /></label>
                  <select
                    value={editing.parentId}
                    onChange={(e) => setEditing({ ...editing, parentId: e.target.value })}
                    className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm w-full bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
                  >
                    <option value="">— No parent —</option>
                    {possibleParents.map((p) => (
                      <option key={p.id} value={p.id}>
                        L{p.level} — {p.name}
                      </option>
                    ))}
                  </select>
                </div>
              )}

              <div>
                <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${LEVEL_COLORS[editing.level] ?? "bg-gray-100 text-gray-600"}`}>
                  {LEVEL_LABELS[editing.level] ?? `Level ${editing.level}`}
                </span>
              </div>
            </div>

            <div className="flex items-center justify-end px-6 py-4 border-t border-gray-200 dark:border-gray-700 gap-3">
              <button type="button" onClick={() => setEditing(null)} className="px-4 py-2 text-sm text-gray-600 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200">Cancel</button>
              <button
                type="button"
                onClick={handleSave}
                disabled={isPending || !editing.name}
                className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium disabled:opacity-50"
              >
                {isPending ? "Saving..." : editing.id ? "Update" : "Create"}
              </button>
            </div>
        </>)}
      </AnimatedModal>
    </div>
  );
}
