import styles from './UsersPage.module.scss';
import { useState } from 'react';
import useSWR from 'swr';
import useUser from '../../lib/hooks/useUser';
import { PaginatedResponse } from '../../lib/types/paginated-response.interface';
import { UserListItem } from '../../lib/types/users.interfaces';
import { Container } from '../common/Container/Container';
import { Header } from '../common/Header/Header';
import avatar from '../../public/avatar.png';
import Image from 'next/image';
import { UPLOADS_URL } from '../../lib/constants';
import { Paginator } from '../common/Paginator/Paginator';

const UserCard = ({ user }: { user: UserListItem }) => (
  <div className={styles.userCard}>
    <div className={styles.pictureWrapper}>
      {user.picture ? (
        <Image
          src={`${UPLOADS_URL}/${user.picture.file}`}
          width={128}
          height={128}
          alt=""
        />
      ) : (
        <Image src={avatar} alt="" width={128} height={128} />
      )}
    </div>
    <div className={styles.userInfo}>
      <h2>
        {user.display_name}{' '}
        <span className={styles.username}>@{user.username}</span>
      </h2>
      <dl>
        <dt>UUID</dt>
        <dd>{user.uuid}</dd>
        <dt>Email</dt>
        <dd>{user.email}</dd>
        <dt>Activated</dt>
        <dd>{user.activated ? 'Yes' : <b>NOT ACTIVATED</b>}</dd>
        <dt>Registered</dt>
        <dd>{new Date(user.created_at).toDateString()}</dd>
      </dl>
    </div>
  </div>
);

const UserList = ({
  pageIndex,
  searchTerm,
  setPage,
}: {
  pageIndex: number;
  searchTerm: string;
  setPage: (page: number) => void;
}) => {
  const { data } = useSWR<PaginatedResponse<UserListItem>>(
    `/api/admin/users?page=${pageIndex}${searchTerm ? `&q=${searchTerm}` : ''}`
  );

  return data ? (
    <>
      <div className={styles.userList}>
        {data.list.map((user) => (
          <UserCard user={user} key={user.uuid} />
        ))}
        <Paginator setPage={setPage} pagination={data.pagination}></Paginator>
      </div>
    </>
  ) : (
    <span>Nothing found</span>
  );
};

export const UsersPage = () => {
  const { user } = useUser({ redirectTo: '/login' });
  const [pageIndex, setPageIndex] = useState(1);
  const [searchTerm, setSearchTerm] = useState('');

  return (
    <>
      <Header user={user}></Header>
      <Container>
        <h1>Users</h1>
        <UserList
          pageIndex={pageIndex}
          searchTerm={searchTerm}
          setPage={setPageIndex}
        />
      </Container>
    </>
  );
};
