import { useEffect, useState } from "react";
import { Drawer, Table, Tag, Spin, Timeline, App } from "antd";
import { TaskAssignmentLogDto } from "../taskCoordination.model";
import { getAssignmentLogsUsingGet } from "../taskCoordination.api";
import { AssignmentActionMap } from "../taskCoordination.const";

interface AssignmentLogDrawerProps {
  open: boolean;
  taskId: string | null;
  taskName?: string;
  onClose: () => void;
}

const actionColorMap: Record<string, string> = {
  ASSIGN: "blue",
  REASSIGN: "orange",
  REVOKE: "red",
};

export default function AssignmentLogDrawer({
  open,
  taskId,
  taskName,
  onClose,
}: AssignmentLogDrawerProps) {
  const { message } = App.useApp();
  const [loading, setLoading] = useState(false);
  const [logs, setLogs] = useState<TaskAssignmentLogDto[]>([]);

  useEffect(() => {
    if (!open || !taskId) return;
    setLoading(true);
    getAssignmentLogsUsingGet(taskId)
      .then((res: any) => {
        setLogs(res?.data ?? []);
      })
      .catch(() => {
        message.error("加载分配记录失败");
      })
      .finally(() => {
        setLoading(false);
      });
  }, [open, taskId, message]);

  return (
    <Drawer
      title={`分配记录：${taskName || ""}`}
      open={open}
      onClose={onClose}
      width={520}
    >
      <Spin spinning={loading}>
        {logs.length === 0 && !loading ? (
          <div className="text-center text-gray-400 py-8">暂无分配记录</div>
        ) : (
          <Timeline
            items={logs.map((log) => ({
              color: actionColorMap[log.action] || "gray",
              children: (
                <div className="pb-2">
                  <div className="flex items-center gap-2 mb-1">
                    <Tag
                      color={actionColorMap[log.action] || "default"}
                    >
                      {AssignmentActionMap[log.action] || log.action}
                    </Tag>
                    <span className="text-sm text-gray-500">
                      {log.createdAt}
                    </span>
                  </div>
                  <div className="text-sm">
                    <span className="text-gray-500">操作人：</span>
                    {log.operatorName || "-"}
                    {log.userName && (
                      <>
                        <span className="text-gray-500 ml-3">目标用户：</span>
                        {log.userName}
                      </>
                    )}
                  </div>
                  {log.remark && (
                    <div className="text-sm text-gray-500 mt-1">
                      备注：{log.remark}
                    </div>
                  )}
                </div>
              ),
            }))}
          />
        )}
      </Spin>
    </Drawer>
  );
}
