import { Box, Container, Flex, Title, Text } from "@mantine/core";
import { useSearchParams } from "react-router";
import type { Route } from "./+types/set-password";
import { setPassword } from "@/lib/features/auth/action";
import SetPasswordForm from "./(widgets)/setPasswordForm";
import AuthLogo from "./(widgets)/authLogo";

export function meta() {
  return [{ title: "Set Your Password - Admin Console" }];
}

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

  switch (intent) {
    case "set-password":
      const res = await setPassword({ token, password });
      return res;
    default:
      return {
        success: false,
        message: "Invalid intent",
        data: null,
      };
  }
}

export default function SetPassword() {
  const [searchParams] = useSearchParams();
  const token = searchParams.get("token");

  if (!token) {
    return (
      <Container fluid h={"100vh"}>
        <Flex h={"100%"} w={"100%"} justify={"center"} align="center" direction="column">
          <Box w={400} maw="100%">
            <AuthLogo />
          </Box>
          <Box w={400} maw="100%" p="xl" bg="white" style={{ borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.1)' }}>
            <Title order={3} c="red" style={{ textAlign: 'center' }}>Invalid Link</Title>
            <Text style={{ textAlign: 'center' }} mt="md">The password reset link is invalid or has expired.</Text>
          </Box>
        </Flex>
      </Container>
    );
  }

  return (
    <Container fluid h={"100vh"}>
      <Flex h={"100%"} w={"100%"} justify={"center"} align="center">
        <Box w={400} maw="100%">
          <AuthLogo />
          <SetPasswordForm token={token} />
        </Box>
      </Flex>
    </Container>
  );
}
