"use client";

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

type ClientRow = {
  id: string;
  name: string;
  code: string | null;
  parentId: string | null;
  sortOrder: number;
  isActive: boolean;
};

type ClientNode = ClientRow & { children: ClientNode[] };

type EditingClient = {
  id?: string;
  name: string;
  code: string;
  parentId: string;
  sortOrder: number;
};

function ClientTreeNode({
  node,
  onEdit,
  onAddChild,
  depth = 0,
}: {
  node: ClientNode;
  onEdit: (c: ClientRow) => void;
  onAddChild: (parentId: string) => void;
  depth?: number;
}) {
  const [expanded, setExpanded] = useState(depth < 1);
  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="text-sm font-medium text-gray-900 dark:text-gray-100 flex-1">
          {node.name}
          {node.code && <span className="text-gray-400 font-mono ml-1 text-xs">[{node.code}]</span>}
        </span>
        {!node.isActive && <span className="text-xs text-gray-400 italic">inactive</span>}
        <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
          <button
            type="button"
            onClick={() => onAddChild(node.id)}
            className="text-xs text-green-600 hover:text-green-800 font-medium"
          >
            + Child
          </button>
          <button
            type="button"
            onClick={() => onEdit(node)}
            className="text-xs text-brand-600 hover:text-brand-800 font-medium"
          >
            Edit
          </button>
        </div>
      </div>
      {expanded && node.children.map((child) => (
        <ClientTreeNode key={child.id} node={child} onEdit={onEdit} onAddChild={onAddChild} depth={depth + 1} />
      ))}
    </div>
  );
}

export function ClientsAdminClient() {
  const [editing, setEditing] = useState<EditingClient | null>(null);
  const [search, setSearch] = useState("");
  const [error, setError] = useState<string | null>(null);

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

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

  const allClients = (flatList ?? []) as unknown as ClientRow[];

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

  function openEdit(c: ClientRow) {
    setEditing({
      id: c.id,
      name: c.name,
      code: c.code ?? "",
      parentId: c.parentId ?? "",
      sortOrder: c.sortOrder,
    });
    setError(null);
  }

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

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

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

  // Simple client-side filter on tree
  function filterTree(nodes: ClientNode[], q: string): ClientNode[] {
    if (!q) return nodes;
    const lower = q.toLowerCase();
    return nodes.reduce<ClientNode[]>((acc, node) => {
      const filteredChildren = filterTree(node.children, q);
      if (node.name.toLowerCase().includes(lower) || (node.code ?? "").toLowerCase().includes(lower) || filteredChildren.length > 0) {
        acc.push({ ...node, children: filteredChildren });
      }
      return acc;
    }, []);
  }

  const filteredTree = filterTree(treeNodes, search);

  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">Clients</h1>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            Client hierarchy for project assignment and chargeability reporting <InfoTooltip content="Clients are companies or brands that commission projects. The hierarchy supports parent/child relationships (e.g. BMW Group > BMW > MINI). Projects are assigned to clients for revenue tracking and chargeability reporting." />
          </p>
        </div>
        <button
          type="button"
          onClick={() => openCreate()}
          className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 text-sm font-medium"
        >
          + Add Client
        </button>
      </div>

      <div className="mb-4">
        <input
          type="search"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search clients..."
          className="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400 w-64 bg-white dark:bg-gray-900 dark:text-gray-100"
        />
      </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 && filteredTree.length === 0 && (
          <div className="text-center py-8 text-gray-400">
            {search ? "No clients match your search." : "No clients yet."}
          </div>
        )}
        {filteredTree.map((node) => (
          <ClientTreeNode key={node.id} node={node} onEdit={openEdit} onAddChild={(pid) => openCreate(pid)} />
        ))}
      </div>

      {/* Create/Edit Modal */}
      {editing && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white dark:bg-gray-900 rounded-xl shadow-2xl w-full max-w-md mx-4">
            <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 Client" : "Add Client"}
              </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 the client. Shown in project assignment dropdowns and reports." /></label>
                <input
                  type="text"
                  value={editing.name}
                  onChange={(e) => setEditing({ ...editing, name: e.target.value })}
                  placeholder="e.g. BMW Group"
                  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">Code <InfoTooltip content="A short abbreviation for this client (e.g. BMW). Used in compact views and rate card assignments." /></label>
                  <input
                    type="text"
                    value={editing.code}
                    onChange={(e) => setEditing({ ...editing, code: e.target.value })}
                    placeholder="BMW"
                    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 font-mono"
                  />
                </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. 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>

              <div>
                <label className="flex items-center text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Parent Client <InfoTooltip content="Set a parent to create a hierarchy (e.g. MINI under BMW Group). Child clients inherit the parent's reporting context." /></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="">— Top level (no parent) —</option>
                  {allClients
                    .filter((c) => c.id !== editing.id && c.isActive)
                    .map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.name} {c.code ? `[${c.code}]` : ""}
                      </option>
                    ))}
                </select>
              </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>
          </div>
        </div>
      )}
    </div>
  );
}
