import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { AccountStatus, AllUser, AllUserResponse } from "@/types/user";
import Header from "@/components/Header";
import ContentDrawer from "@/components/ContentDrawer";
import UserCreate from "@/components/UserCreate";
import { Avatar, Table } from "antd";
import { TableProps } from "antd/lib";
import { UserService } from "@/services/userService";
import UserEdit from "@/components/UserEdit";
import { useSearchParams } from "react-router-dom";

export default function AccountsPage() {
  const { t } = useTranslation();
  const [openCreate, setOpenCreate] = useState(false);
  const [searchParams, setSearchParams] = useSearchParams();

  const [activeAccount, setActiveAccount] = useState<
    { login: string; id: number; name: string; email: string } | undefined
  >(undefined);

  const showCreateDrawer = () => setOpenCreate(true);
  const closeCreateDrawer = () => {
    setActiveAccount(undefined);
    setOpenCreate(false);
  };
  const [openEdit, setOpenEdit] = useState(false);

  const showEditDrawer = () => setOpenEdit(true);
  const closeEditDrawer = () => {
    setActiveAccount(undefined);
    setOpenEdit(false);
  };

  const [accounts, setAccounts] = useState<AllUserResponse>({
    amountCount: 0,
    amountPages: 0,
    users: [],
    currentPage: 1,
    limit: 10,
  });

  async function getUsers() {
    const page = Number(searchParams.get("page") || "1");
    const limit = Number(searchParams.get("limit") || "10");
    setSearchParams({
      page: page.toString(),
      limit: limit.toString(),
    });
    const data = await UserService.getUsers(page, limit);
    console.log("searchParams", searchParams);
    setAccounts(data);
  }

  useEffect(() => {
    getUsers();
  }, []);

  const statusColor = {
    ACTIVE: "#27AE60",
    DISABLED: "#606060",
    BLOCKED: "#FF0000",
    DELETED: "#B30000",
  };

  const columns: TableProps<AllUser>["columns"] = [
    {
      title: "#",
      dataIndex: "id",
      key: "id",
    },
    {
      title: t("nameLogin"),
      dataIndex: "nameLogin",
      key: "nameLogin",
      render: (text, record) => (
        <div
          onClick={() => {
            setActiveAccount({
              login: record.login,
              id: record.id,
              name: record.name,
              email: record.email || "",
            });
            showEditDrawer();
          }}
          style={{
            display: "flex",
            alignItems: "center",
            gap: "16px",
            cursor: "pointer",
          }}
        >
          <div
            style={{
              height: "32px",
              width: "32px",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Avatar
              size={32}
              src={`https://gamma.heado.ru/go/ava?name=${record.login}`}
            />
          </div>
          <div style={{ display: "flex", flexDirection: "column" }}>
            <div>{record.name}</div>
            <div style={{ color: "#606060" }}>{record.login}</div>
          </div>
        </div>
      ),
    },
    {
      title: "E-mail",
      dataIndex: "email",
      key: "email",
    },
    {
      title: t("tenant"),
      dataIndex: "bindTenantId",
      key: "tenant",
    },
    {
      title: t("role"),
      dataIndex: "role",
      key: "role",
      render: (text) => <div>{t(text)}</div>,
    },
    {
      title: t("createdAt"),
      dataIndex: "createdAt",
      key: "createdAt",
      render: (text) => (
        <div>
          {new Date(text).toLocaleString("ru", {
            year: "2-digit",
            month: "2-digit",
            day: "2-digit",
          })}
        </div>
      ),
    },
    {
      title: t("status"),
      dataIndex: "status",
      key: "status",
      render: (text) => (
        <div style={{ color: statusColor[text as AccountStatus] }}>
          {t(text)}
        </div>
      ),
    },
  ];

  const onTableChange: TableProps<AllUser>["onChange"] = (pagination) => {
    console.log(pagination);
    UserService.getUsers(
      pagination.current as number,
      pagination.pageSize
    ).then((data) => {
      setAccounts(data);
      setSearchParams({
        page: data.currentPage.toString(),
        limit: data.limit.toString(),
      });
    });
  };

  return (
    <>
      <Header
        title={t("accounts")}
        additionalContent={
          <img
            src="./icons/header/add_2.svg"
            alt="add"
            style={{
              height: "18px",
              width: "18px",
              cursor: "pointer",
            }}
            onClick={showCreateDrawer}
          />
        }
      />
      <Table
        size="small"
        onChange={onTableChange}
        columns={columns}
        dataSource={accounts.users}
        pagination={{
          pageSize: accounts.limit,
          current: accounts.currentPage,
          total: accounts.amountCount,
        }}
        rowKey={"id"}
      />

      <ContentDrawer
        open={openCreate}
        closeDrawer={closeCreateDrawer}
        type="create"
      >
        <UserCreate getUsers={getUsers} closeDrawer={closeCreateDrawer} />
      </ContentDrawer>
      <ContentDrawer
        login={activeAccount?.login}
        name={activeAccount?.name}
        email={activeAccount?.email}
        open={openEdit}
        closeDrawer={closeEditDrawer}
        type="edit"
      >
        <UserEdit userId={activeAccount?.id} closeDrawer={closeEditDrawer} />
      </ContentDrawer>
    </>
  );
}
