import styled from '@emotion/styled';
import { useMutation } from '@tanstack/react-query';
import { Field, Form, Formik } from 'formik';
import { useEffect, useState } from 'react';
import { AdminWrapper, InteractiveDate } from '../../next-res/components/admin/common';
import { NavbarPage, NavigationBar } from '../../next-res/components/admin/NavBar';

const Table = styled.table`
  width: 100%;
  tbody {
    tr:nth-of-type(odd) {
      background-color: #f9f9f9;
    }
    tr {
      cursor: pointer;
      transition: background-color 0.3s;
    }
    tr:hover {
      background-color: #f1f1f1;
    }
  }
  td,
  th {
    padding: 5px 10px;
  }
`;

const FormikForm = styled(Form)`
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  button {
    height: 40px;
    padding: 10px 15px;
    background-color: #0070f3;
    color: white;
    border: none;
    cursor: pointer;
  }
`;

const FormikField = styled(Field)`
  padding: 10px;
  margin: 10px 0;
  width: 100%;
`;

export async function getServerSideProps(context: any) {
  const serverUri = process.env.SERVER_URI || 'http://localhost:3001';

  // Get the user's session based on the request
  if (context?.req?.user?.role !== 'admin') {
    context.res.statusCode = 404;
    context.res.end();
  }

  return {
    props: {
      serverUri,
    },
  };
}

interface SearchFormValues {
  query: string;
}

const AdminHomePage = ({ serverUri }: { serverUri: string }) => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // Needed to set the cookies
    async function getWhoami() {
      await fetch(`${serverUri}/auth/whoami`, { credentials: 'include' });
    }
    getWhoami();
  }, []);

  const {
    mutate: searchUsersMutation,
    isLoading: seachUsersIsLoading,
    isError: searchUsersIsError,
    isSuccess: searchUsersIsSuccess,
  } = useMutation(async (values: SearchFormValues) => {
    const response = await fetch(`${serverUri}/api/admin/searchUsers`, {
      credentials: 'include',
      method: 'POST',
      body: JSON.stringify(values),
      headers: {
        'Content-Type': 'application/json',
      },
    });
    const data = await response.json();
    setUsers(data);
  }, {});

  return (
    <AdminWrapper>
      <h1
        style={{
          marginBottom: '20px',
        }}
      >
        WavTool Admin Dashboard
      </h1>

      <NavigationBar currentPage={NavbarPage.UserData} />

      <p>
        Welcome to the admin dashboard. Here you can search for users and view their details.
        <br />
        Enjoy having God powers.
      </p>

      <span>Search for user:</span>
      <Formik
        initialValues={{ query: '' }}
        onSubmit={async (values) => {
          await searchUsersMutation(values);
        }}
      >
        {({ isSubmitting }) => (
          <FormikForm>
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                width: '100%',
              }}
            >
              <FormikField type="query" name="query" placeholder="Email, Name, or ID" />
              <button type="submit" disabled={isSubmitting}>
                Search
              </button>
            </div>
          </FormikForm>
        )}
      </Formik>
      {seachUsersIsLoading && <p>Loading...</p>}
      {searchUsersIsError && <p>Error</p>}
      {searchUsersIsSuccess && users.length === 0 && <p>No users found</p>}
      {searchUsersIsSuccess && users.length > 0 && (
        <>
          <small>Only 25 results will be shown</small>
          <Table>
            <thead>
              <tr>
                <th>ID</th>
                <th>
                  Display Name
                  <br />
                  (Share Name)
                </th>
                <th>Email</th>
                <th>Plan</th>
              </tr>
            </thead>
            <tbody>
              {users.map((user: any) => {
                const plan = user.override_plan_name
                  ? user.override_plan_name
                  : user.paddle_plan_name?.split('WavTool ')[1] || user.plan_name;
                const provider = user.override ? 'Override' : user.paddle_plan_name ? 'Paddle' : 'Stripe';
                const expiry = user.override_plan_name
                  ? user.override_expires_at
                  : user.paddle_subscribed_until || user.subscribed_until;
                return (
                  <tr
                    key={user.id}
                    onClick={(e) => {
                      if (e.metaKey || e.ctrlKey) {
                        window.open(`/admin/user/${user.id}`, '_blank');
                      } else {
                        window.location.href = `/admin/user/${user.id}`;
                      }
                    }}
                  >
                    <td>{user.id}</td>
                    <td>
                      <div>{user.display_name}</div>
                      {user.share_name && <div>({user.share_name})</div>}
                    </td>
                    <td>{user.email}</td>
                    <td>
                      {plan ? (
                        <>
                          <b>
                            {plan} {provider && <span>({provider})</span>}
                          </b>
                          <br />
                          <InteractiveDate date={expiry} prefix="expires" />
                        </>
                      ) : (
                        'Free'
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </Table>
        </>
      )}
    </AdminWrapper>
  );
};

export default AdminHomePage;
