import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useAuthStore } from "@modules/auth/store/authStore";
import { useIsSuperuser } from "@modules/auth";
import { Button, Form, Input, Modal, Select, Space, Switch, Table, Tag, Typography, message } from "antd";
import {
  createAdminUser,
  deleteAdminUser,
  getAdminUsers,
  patchAdminUser,
  resetAdminUserPassword,
  type AdminUser
} from "../api/adminApi";

export function AdminUsersTable(): JSX.Element {
  const isSuperuser = useIsSuperuser();
  const currentUser = useAuthStore((state) => state.user);
  const [messageApi, contextHolder] = message.useMessage();
  const [modal, contextModal] = Modal.useModal();
  const [editingUser, setEditingUser] = useState<AdminUser | null>(null);
  const [createOpen, setCreateOpen] = useState(false);
  const [createForm] = Form.useForm<{ email: string; password: string; role: string; status: string; is_superuser: boolean }>();
  const [editForm] = Form.useForm<{ role: string; status: string; is_superuser: boolean }>();

  const { data, isLoading } = useQuery({
    queryKey: ["admin-users"],
    queryFn: () => getAdminUsers()
  });
  const queryClient = useQueryClient();
  const createMutation = useMutation({
    mutationFn: (values: { email: string; password: string; role: string; status: string; is_superuser: boolean }) =>
      createAdminUser(values),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      messageApi.success("User created");
      setCreateOpen(false);
      createForm.resetFields();
    }
  });

  const updateMutation = useMutation({
    mutationFn: (payload: { id: string; role: string; status: string; is_superuser: boolean }) =>
      patchAdminUser(payload.id, payload),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      messageApi.success("User updated");
      setEditingUser(null);
    }
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => deleteAdminUser(id),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["admin-users"] });
      messageApi.success("User deleted");
    }
  });

  const resetMutation = useMutation({
    mutationFn: (id: string) => resetAdminUserPassword(id, "Admin1234"),
    onSuccess: () => {
      messageApi.success("Password reset to Admin1234");
    }
  });

  if (isLoading || !data) {
    return <p className="wesp-admin-block">Loading users...</p>;
  }

  const rows = data.data;

  return (
    <div className="wesp-admin-grid">
      {contextHolder}
      {contextModal}
      <Space align="center">
        <Typography.Title level={4} style={{ margin: 0 }}>
          Users
        </Typography.Title>
      {isSuperuser ? (
        <Button type="primary" onClick={() => setCreateOpen(true)}>
          Create user
        </Button>
      ) : null}
      </Space>
      <Table
        rowKey="id"
        dataSource={rows}
        pagination={false}
        columns={[
          {
            title: "Email",
            dataIndex: "email"
          },
          {
            title: "Role",
            dataIndex: "role",
            render: (role: string) => (
              <Tag className={role === "admin" ? "wesp-tag wesp-tag--warn" : "wesp-tag"}>{role}</Tag>
            )
          },
          {
            title: "Status",
            dataIndex: "status",
            render: (status: string) => (
              <Tag
                className={
                  status === "active"
                    ? "wesp-tag wesp-tag--ok"
                    : status === "blocked"
                      ? "wesp-tag wesp-tag--error"
                      : "wesp-tag"
                }
              >
                {status}
              </Tag>
            )
          },
          {
            title: "Superuser",
            dataIndex: "is_superuser",
            render: (value: boolean) => (value ? "yes" : "no")
          },
          {
            title: "Actions",
            render: (_, user: AdminUser) => {
              const isSelf = currentUser?.id === user.id;
              return (
                <Space wrap>
                  <Button
                    onClick={() => {
                      editForm.setFieldsValue({
                        role: user.role,
                        status: user.status,
                        is_superuser: user.is_superuser
                      });
                      setEditingUser(user);
                    }}
                    disabled={isSelf}
                  >
                    Edit
                  </Button>
                  {isSuperuser ? (
                    <>
                      <Button
                        disabled={isSelf}
                        onClick={() => {
                          void resetMutation.mutate(user.id);
                        }}
                      >
                        Reset pwd
                      </Button>
                      <Button
                        danger
                        disabled={isSelf}
                        onClick={() => {
                          void modal.confirm({
                            title: "Delete user",
                            content: `Delete ${user.email}?`,
                            okText: "Delete",
                            okButtonProps: { danger: true },
                            onOk: () => deleteMutation.mutateAsync(user.id)
                          });
                        }}
                      >
                        Delete
                      </Button>
                    </>
                  ) : null}
                  {isSelf ? <Typography.Text type="secondary">(you)</Typography.Text> : null}
                </Space>
              );
            }
          }
        ]}
      />

      <Modal
        title="Create user"
        open={createOpen}
        onCancel={() => setCreateOpen(false)}
        onOk={() => createForm.submit()}
        okText="Create"
        confirmLoading={createMutation.isPending}
      >
        <Form
          form={createForm}
          layout="vertical"
          initialValues={{ role: "user", status: "active", is_superuser: false, password: "Admin1234" }}
          onFinish={(values) => createMutation.mutate(values)}
        >
          <Form.Item name="email" label="Email" rules={[{ required: true, type: "email" }]}>
            <Input />
          </Form.Item>
          <Form.Item name="password" label="Password" rules={[{ required: true, min: 8 }]}>
            <Input.Password />
          </Form.Item>
          <Form.Item name="role" label="Role" rules={[{ required: true }]}>
            <Select options={[{ value: "user" }, { value: "admin" }]} />
          </Form.Item>
          <Form.Item name="status" label="Status" rules={[{ required: true }]}>
            <Select options={[{ value: "active" }, { value: "pending" }, { value: "blocked" }]} />
          </Form.Item>
          {isSuperuser ? (
            <Form.Item name="is_superuser" label="Superuser" valuePropName="checked">
              <Switch />
            </Form.Item>
          ) : null}
        </Form>
      </Modal>

      <Modal
        title={editingUser ? `Edit ${editingUser.email}` : "Edit user"}
        open={Boolean(editingUser)}
        onCancel={() => setEditingUser(null)}
        onOk={() => editForm.submit()}
        okText="Save"
        confirmLoading={updateMutation.isPending}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={(values) => {
            if (!editingUser) {
              return;
            }
            updateMutation.mutate({ id: editingUser.id, ...values });
          }}
        >
          <Form.Item name="role" label="Role" rules={[{ required: true }]}>
            <Select options={[{ value: "user" }, { value: "admin" }]} />
          </Form.Item>
          <Form.Item name="status" label="Status" rules={[{ required: true }]}>
            <Select options={[{ value: "active" }, { value: "pending" }, { value: "blocked" }]} />
          </Form.Item>
          {isSuperuser ? (
            <Form.Item name="is_superuser" label="Superuser" valuePropName="checked">
              <Switch />
            </Form.Item>
          ) : null}
        </Form>
      </Modal>
    </div>
  );
}
