"use client";

import { ActionForm } from "@/components/action-form";
import { useActionState, useState } from "react";
import { useFormStatus } from "react-dom";
import { createDepartmentAction, type DepartmentState } from "./actions";
import { Badge } from "@/components/ui";
import { formatVndShort } from "@/lib/format";

export type DepartmentNode = {
  id: string;
  code: string;
  name: string;
  parentId: string | null;
  headUserId: string | null;
  headName: string | null;
  isActive: boolean;
  staffCount: number;
  revenue: number;
};

type Option = { id: string; name: string };

function Submit() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" className="btn-primary" disabled={pending}>
      {pending ? "Đang thêm…" : "Thêm phòng ban"}
    </button>
  );
}

export function DepartmentTree({
  nodes,
  staff,
  onUpdate,
  onToggleActive,
}: {
  nodes: DepartmentNode[];
  staff: Option[];
  onUpdate: (formData: FormData) => Promise<unknown>;
  onToggleActive: (formData: FormData) => Promise<unknown>;
}) {
  const [state, formAction] = useActionState<DepartmentState, FormData>(createDepartmentAction, {});
  const [parentId, setParentId] = useState<string>("");
  const [editing, setEditing] = useState<string | null>(null);

  const childrenOf = (id: string | null) => nodes.filter((node) => node.parentId === id);
  const parent = nodes.find((node) => node.id === parentId);

  const parentOptions = (() => {
    const list: { id: string; label: string }[] = [];
    const walk = (id: string | null, depth: number) => {
      for (const node of childrenOf(id)) {
        list.push({ id: node.id, label: `${"— ".repeat(depth)}${node.name}` });
        walk(node.id, depth + 1);
      }
    };
    walk(null, 0);
    return list;
  })();

  const renderNode = (node: DepartmentNode, depth: number) => {
    const children = childrenOf(node.id);
    return (
      <li key={node.id}>
        <div
          className="flex flex-wrap items-center gap-2 border-b border-[var(--color-line)] py-2"
          style={{ paddingLeft: `${depth * 20}px` }}
        >
          {editing === node.id ? (
            <ActionForm action={onUpdate} success="Đã lưu thay đổi." className="flex flex-wrap items-center gap-1.5">
              <input type="hidden" name="id" value={node.id} />
              <input name="name" defaultValue={node.name} className="input w-52 py-1 text-sm" />
              <select
                name="headUserId"
                defaultValue={node.headUserId ?? ""}
                className="input w-48 py-1 text-sm"
                aria-label="Trưởng phòng"
              >
                <option value="">— Chưa có trưởng phòng —</option>
                {staff.map((person) => (
                  <option key={person.id} value={person.id}>
                    {person.name}
                  </option>
                ))}
              </select>
              <button type="submit" className="btn-primary px-2 py-1 text-xs">
                Lưu
              </button>
              <button
                type="button"
                onClick={() => setEditing(null)}
                className="btn-ghost px-2 py-1 text-xs"
              >
                Bỏ
              </button>
            </ActionForm>
          ) : (
            <>
              <span
                className={`text-sm font-medium ${node.isActive ? "text-ink-700" : "text-ink-300 line-through"}`}
              >
                {node.name}
              </span>
              <span className="tnum text-[11px] text-ink-400">{node.code}</span>
              {node.headName ? (
                <Badge tone="brand">TP: {node.headName}</Badge>
              ) : (
                <span className="text-[11px] text-ink-400">Chưa có trưởng phòng</span>
              )}
              {node.staffCount > 0 && (
                <span className="text-[11px] text-ink-400">{node.staffCount} nhân sự</span>
              )}
              {node.revenue > 0 && (
                <span className="tnum text-[11px] text-brand-600">{formatVndShort(node.revenue)}</span>
              )}
              {!node.isActive && <Badge tone="red">Ngừng dùng</Badge>}

              <span className="ml-auto flex gap-1">
                <button
                  type="button"
                  onClick={() => setEditing(node.id)}
                  className="btn-ghost px-2 py-0.5 text-xs"
                >
                  Sửa
                </button>
                <button
                  type="button"
                  onClick={() => setParentId(node.id)}
                  className="btn-ghost px-2 py-0.5 text-xs"
                >
                  + Cấp con
                </button>
                <ActionForm action={onToggleActive} success="Đã cập nhật trạng thái.">
                  <input type="hidden" name="id" value={node.id} />
                  <button
                    type="submit"
                    className={`btn-ghost px-2 py-0.5 text-xs ${node.isActive ? "text-red-600" : "text-emerald-700"}`}
                  >
                    {node.isActive ? "Ngừng dùng" : "Dùng lại"}
                  </button>
                </ActionForm>
              </span>
            </>
          )}
        </div>
        {children.length > 0 && <ul>{children.map((child) => renderNode(child, depth + 1))}</ul>}
      </li>
    );
  };

  return (
    <div className="flex flex-col gap-5">
      <form action={formAction} className="card flex flex-col gap-4 p-4">
        <h2 className="text-base font-bold text-ink-700">
          {parent ? `Thêm phòng ban trong ${parent.name}` : "Thêm phòng ban cấp cao nhất"}
        </h2>

        <div className="grid gap-4 lg:grid-cols-4">
          <div>
            <label className="label-caps mb-1.5 block">Thuộc phòng ban</label>
            <select
              name="parentId"
              value={parentId}
              onChange={(event) => setParentId(event.target.value)}
              className="input"
            >
              <option value="">— Cấp cao nhất —</option>
              {parentOptions.map((option) => (
                <option key={option.id} value={option.id}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="label-caps mb-1.5 block">Tên phòng ban *</label>
            <input name="name" required className="input" placeholder="Team Miền Bắc" />
          </div>
          <div>
            <label className="label-caps mb-1.5 block">Mã *</label>
            <input name="code" required className="input" placeholder="KD-MB" />
          </div>
          <div>
            <label className="label-caps mb-1.5 block">Trưởng phòng</label>
            <select name="headUserId" defaultValue="" className="input">
              <option value="">— Chưa có —</option>
              {staff.map((person) => (
                <option key={person.id} value={person.id}>
                  {person.name}
                </option>
              ))}
            </select>
          </div>
        </div>

        {state.error && (
          <p role="alert" className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
            {state.error}
          </p>
        )}
        {state.ok && <p className="rounded-lg bg-ink-100 px-3 py-2 text-sm text-brand-600">{state.ok}</p>}

        <div>
          <Submit />
        </div>
      </form>

      <div className="card p-4">
        <h2 className="mb-2 text-base font-bold text-ink-700">Cơ cấu tổ chức</h2>
        {nodes.length === 0 ? (
          <p className="py-8 text-center text-sm text-ink-400">Chưa có phòng ban nào.</p>
        ) : (
          <ul>{childrenOf(null).map((node) => renderNode(node, 0))}</ul>
        )}
      </div>
    </div>
  );
}
