import { useEffect, useMemo, useState } from "react";
import {
  App as AntApp,
  Button,
  Card,
  Form,
  Input,
  Modal,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
  Typography,
} from "antd";
import { EditOutlined, PlusOutlined, ReloadOutlined, DeleteOutlined } from "@ant-design/icons";
import {
  OrgUnit,
  Session,
  createOrgUnit,
  deleteOrgUnit,
  listOrgUnits,
  updateOrgUnit,
} from "./api";

type FormValues = {
  parent_id?: number;
  name: string;
  code?: string;
};

export function OrgUnitsPage(props: {
  session: Session;
  busy: boolean;
  setBusy: (v: boolean) => void;
  setError: (v: string) => void;
  setInfo: (v: string) => void;
}) {
  const { session, busy, setBusy, setError, setInfo } = props;
  const { message } = AntApp.useApp();
  const [items, setItems] = useState<OrgUnit[]>([]);
  const [maxDepth, setMaxDepth] = useState(5);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<OrgUnit | null>(null);
  const [form] = Form.useForm<FormValues>();

  async function refresh() {
    setLoading(true);
    try {
      const res = await listOrgUnits(session);
      setItems(res.items || []);
      if (res.max_depth) setMaxDepth(res.max_depth);
    } catch (e: any) {
      const msg = e.message || String(e);
      setError(msg);
      message.error(msg);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    refresh();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [session.accessToken]);

  const parentOptions = useMemo(() => {
    return (items || [])
      .filter((o) => o.depth < maxDepth)
      .map((o) => ({
        value: o.org_unit_id,
        label: `${"— ".repeat(Math.max(0, o.depth - 1))}${o.name}（L${o.depth}）`,
      }));
  }, [items, maxDepth]);

  function openCreate(parentId?: number) {
    setEditing(null);
    form.resetFields();
    form.setFieldsValue({ parent_id: parentId || undefined, name: "", code: "" });
    setOpen(true);
  }

  function openEdit(o: OrgUnit) {
    setEditing(o);
    form.setFieldsValue({ name: o.name, code: o.code || "", parent_id: o.parent_id || undefined });
    setOpen(true);
  }

  async function onSubmit() {
    const values = await form.validateFields();
    setBusy(true);
    try {
      if (!editing) {
        const ou = await createOrgUnit(session, {
          parent_id: values.parent_id || 0,
          name: values.name.trim(),
          code: (values.code || "").trim(),
        });
        message.success(`已创建「${ou.name}」`);
        setInfo(`已创建组织「${ou.name}」（深度 ${ou.depth}/${maxDepth}）`);
      } else {
        await updateOrgUnit(session, editing.org_unit_id, {
          name: values.name.trim(),
          code: (values.code || "").trim(),
        });
        message.success("已保存");
        setInfo(`已保存组织「${values.name.trim()}」`);
      }
      setOpen(false);
      await refresh();
    } catch (e: any) {
      message.error(e.message || String(e));
      setError(e.message || String(e));
    } finally {
      setBusy(false);
    }
  }

  return (
    <Card
      title="组织管理"
      extra={
        <Space>
          <Button icon={<ReloadOutlined />} onClick={refresh} loading={loading}>
            刷新
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => openCreate()}>
            新建顶级组织
          </Button>
        </Space>
      }
    >
      <Typography.Paragraph type="secondary" style={{ marginTop: 0 }}>
        公司（租户）下可建多级组织，最多 {maxDepth} 级。成员通过邀请码绑定组织后，只能访问本组织及下级数据；公司管理员（owner）可看全公司。
      </Typography.Paragraph>

      <Table
        rowKey="org_unit_id"
        loading={loading || busy}
        dataSource={items}
        pagination={{ pageSize: 20 }}
        columns={[
          {
            title: "名称",
            dataIndex: "name",
            render: (v, r) => (
              <span style={{ paddingLeft: (r.depth - 1) * 16 }}>
                {r.depth > 1 ? "└ " : ""}
                {v}
              </span>
            ),
          },
          { title: "编码", dataIndex: "code", width: 140, render: (v) => v || "—" },
          {
            title: "层级",
            dataIndex: "depth",
            width: 90,
            render: (v) => <Tag>L{v}/{maxDepth}</Tag>,
          },
          { title: "路径", dataIndex: "path", ellipsis: true },
          {
            title: "操作",
            width: 260,
            render: (_, r) => (
              <Space wrap>
                <Button
                  size="small"
                  icon={<PlusOutlined />}
                  disabled={r.depth >= maxDepth}
                  onClick={() => openCreate(r.org_unit_id)}
                >
                  下级
                </Button>
                <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(r)}>
                  编辑
                </Button>
                <Popconfirm
                  title={`删除「${r.name}」？需先删下级`}
                  onConfirm={async () => {
                    setBusy(true);
                    try {
                      await deleteOrgUnit(session, r.org_unit_id);
                      message.success("已删除");
                      await refresh();
                    } catch (e: any) {
                      message.error(e.message || String(e));
                      setError(e.message || String(e));
                    } finally {
                      setBusy(false);
                    }
                  }}
                >
                  <Button size="small" danger icon={<DeleteOutlined />}>
                    删除
                  </Button>
                </Popconfirm>
              </Space>
            ),
          },
        ]}
      />

      <Modal
        title={editing ? `编辑组织 #${editing.org_unit_id}` : "新建组织"}
        open={open}
        onCancel={() => setOpen(false)}
        onOk={onSubmit}
        confirmLoading={busy}
        destroyOnClose
        okText="保存"
      >
        <Form form={form} layout="vertical" style={{ marginTop: 12 }}>
          {!editing && (
            <Form.Item label="上级组织" name="parent_id">
              <Select
                allowClear
                placeholder="空=顶级组织"
                options={parentOptions}
              />
            </Form.Item>
          )}
          <Form.Item label="名称" name="name" rules={[{ required: true, message: "请填写名称" }]}>
            <Input placeholder="如：华东事业部 / 项目一组" />
          </Form.Item>
          <Form.Item label="编码（可选，租户内唯一）" name="code">
            <Input placeholder="如 east / proj_a" disabled={!!editing && !!editing.code} />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}
