"use client";

import { ActionForm } from "@/components/action-form";
import { useActionState, useState } from "react";
import { useFormStatus } from "react-dom";
import { createTerritoryAction, type TerritoryState } from "./actions";
import { Badge } from "@/components/ui";

export type TerritoryNode = {
  id: string;
  code: string;
  name: string;
  level: "REGION" | "PROVINCE" | "DISTRICT" | "WARD";
  parentId: string | null;
  isActive: boolean;
  customerCount: number;
};

const LEVEL_LABEL: Record<string, string> = {
  REGION: "Miền",
  PROVINCE: "Tỉnh / TP",
  DISTRICT: "Quận / Huyện",
  WARD: "Phường / Xã",
};

const CHILD_LABEL: Record<string, string | null> = {
  REGION: "tỉnh/thành",
  PROVINCE: "quận/huyện",
  DISTRICT: "phường/xã",
  WARD: null,
};

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

export function TerritoryTree({
  nodes,
  onRename,
  onToggleActive,
}: {
  nodes: TerritoryNode[];
  onRename: (formData: FormData) => Promise<unknown>;
  onToggleActive: (formData: FormData) => Promise<unknown>;
}) {
  const [state, formAction] = useActionState<TerritoryState, FormData>(createTerritoryAction, {});
  const [parentId, setParentId] = useState<string>("");
  const [renaming, setRenaming] = useState<string | null>(null);

  const childrenOf = (id: string | null) => nodes.filter((node) => node.parentId === id);
  const parent = nodes.find((node) => node.id === parentId);
  const nextLevel = parent ? CHILD_LABEL[parent.level] : "miền";

  /** Danh sách chọn khu vực cha, thụt lề theo cấp để nhìn ra cây. */
  const parentOptions = (() => {
    const list: { id: string; label: string; disabled: boolean }[] = [];
    const walk = (id: string | null, depth: number) => {
      for (const node of childrenOf(id)) {
        list.push({
          id: node.id,
          label: `${"— ".repeat(depth)}${node.name}`,
          disabled: node.level === "WARD",
        });
        walk(node.id, depth + 1);
      }
    };
    walk(null, 0);
    return list;
  })();

  const renderNode = (node: TerritoryNode, 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` }}
        >
          {renaming === node.id ? (
            <ActionForm action={onRename} success="Đã đổi tên." className="flex items-center gap-1.5">
              <input type="hidden" name="id" value={node.id} />
              <input
                name="name"
                defaultValue={node.name}
                autoFocus
                className="input w-56 py-1 text-sm"
              />
              <button type="submit" className="btn-primary px-2 py-1 text-xs">
                Lưu
              </button>
              <button
                type="button"
                onClick={() => setRenaming(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>
              <Badge tone={node.level === "REGION" ? "brand" : node.level === "PROVINCE" ? "neutral" : "gold"}>
                {LEVEL_LABEL[node.level]}
              </Badge>
              {node.customerCount > 0 && (
                <span className="text-[11px] text-ink-400">{node.customerCount} khách hàng</span>
              )}
              {!node.isActive && <Badge tone="red">Ngừng dùng</Badge>}

              <span className="ml-auto flex gap-1">
                <button
                  type="button"
                  onClick={() => setRenaming(node.id)}
                  className="btn-ghost px-2 py-0.5 text-xs"
                >
                  Đổi tên
                </button>
                {node.level !== "WARD" && (
                  <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 ${nextLevel} trong ${parent.name}` : "Thêm miền mới"}
        </h2>

        <div className="grid gap-4 lg:grid-cols-4">
          <div className="lg:col-span-2">
            <label className="label-caps mb-1.5 block">Thuộc khu vực</label>
            <select
              name="parentId"
              value={parentId}
              onChange={(event) => setParentId(event.target.value)}
              className="input"
            >
              <option value="">— Không thuộc đâu cả (tạo miền mới) —</option>
              {parentOptions.map((option) => (
                <option key={option.id} value={option.id} disabled={option.disabled}>
                  {option.label}
                  {option.disabled ? " (đã là cấp thấp nhất)" : ""}
                </option>
              ))}
            </select>
            <p className="mt-1 text-[11px] text-ink-400">
              Cấp của khu vực mới tự suy ra từ khu vực cha, không chọn tay — để không có phường nào
              nằm thẳng dưới miền.
            </p>
          </div>
          <div>
            <label className="label-caps mb-1.5 block">Tên khu vực *</label>
            <input name="name" required className="input" placeholder="Quận Ba Đình" />
          </div>
          <div>
            <label className="label-caps mb-1.5 block">Mã *</label>
            <input name="code" required className="input" placeholder="MB-01-BD" />
          </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ây khu vực</h2>
        {nodes.length === 0 ? (
          <p className="py-8 text-center text-sm text-ink-400">Chưa có khu vực nào.</p>
        ) : (
          <ul>{childrenOf(null).map((node) => renderNode(node, 0))}</ul>
        )}
      </div>
    </div>
  );
}
