import { isLoggedInCookie } from "@/utils/createCookie";
import { Alert, Box, Container, Flex } from "@mantine/core";
import { IconInfoCircle } from "@tabler/icons-react";
import { redirect, useSearchParams } from "react-router";
import SigninForm from "./(widgets)/form";
import AuthLogo from "./(widgets)/authLogo";
import type { Route } from "./+types/signin";
import { adminSignin, checkSuperAdminExists } from "@/lib/features/auth/action";

export function meta() {
  return [{ title: "Admin Sign-in" }];
}

export async function loader() {
  const res = await checkSuperAdminExists();
  if (res.success && res.data && !(res.data as { exists: boolean }).exists) {
    return redirect("/auth/setup");
  }
  return null;
}

export async function action({ request }: Route.ActionArgs) {
  const { intent, ...payload } = (await request.json()) as {
    intent: string;
  } & { email: string; password: string };

  switch (intent) {
    case "signin":
      const res = await adminSignin(payload);
      if (!res.success) return res;

      const setCookieHeaders = (res.data as Response).headers.getSetCookie();
      if (setCookieHeaders?.length > 0) {
        const newHeaders = new Headers();
        setCookieHeaders.forEach((cookie) => {
          newHeaders.append("Set-Cookie", cookie);
        });

        const localCookie = await isLoggedInCookie.serialize("true");
        newHeaders.append("Set-Cookie", localCookie);

        return redirect("/admin/dashboard", {
          headers: newHeaders,
        });
      } else {
        return new Response(
          JSON.stringify({
            success: false,
            message: "Something went wrong. Please try again.",
            data: null,
          }),
          {
            headers: { "Content-Type": "application/json" },
          },
        );
      }
    default:
      return new Response(
        JSON.stringify({
          success: false,
          message: "Invalid intent",
          data: null,
        }),
        {
          headers: { "Content-Type": "application/json" },
        },
      );
  }
}

export default function SignIn() {
  const [searchParams] = useSearchParams();
  // Set by /sso when a one-time link from an email couldn't be redeemed. Without
  // this the reader is dropped on a login form with no idea why their link didn't
  // work, and no reason to believe signing in gets them anywhere better.
  const ssoFailure = searchParams.get("sso");

  return (
    <Container fluid h={"100vh"}>
      <Flex h={"100%"} w={"100%"} justify={"center"} align="center">
        <Box w={400} maw="100%">
          <AuthLogo />
          {ssoFailure && (
            <Alert
              variant="light"
              color="orange"
              icon={<IconInfoCircle size={16} />}
              mb="md"
            >
              That sign-in link has already been used or has expired — each one
              works once. Sign in below to carry on.
            </Alert>
          )}
          <SigninForm />
        </Box>
      </Flex>
    </Container>
  );
}
