import { checkSuperAdminExists, createInitialSuperAdmin } from "@/lib/features/auth/action";
import {
  Box,
  Button,
  Container,
  Flex,
  PasswordInput,
  Stack,
  TextInput,
  Title,
  Text,
} from "@mantine/core";
import { useForm } from "@mantine/form";
import { notifications } from "@mantine/notifications";
import { useState } from "react";
import { redirect, useFetcher, useNavigate } from "react-router";
import type { Route } from "./+types/logout";

export function meta() {
  return [{ title: "Initial Admin Setup" }];
}

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

export async function action({ request }: Route.ActionArgs) {
  const payload = await request.json();
  const res = await createInitialSuperAdmin(payload);
  return res;
}

export default function Setup() {
  const fetcher = useFetcher();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const form = useForm({
    initialValues: {
      firstName: "",
      lastName: "",
      email: "",
      username: "",
      password: "",
      confirmPassword: "",
    },
    validate: {
      firstName: (value) => (value.length < 2 ? "First name is too short" : null),
      lastName: (value) => (value.length < 2 ? "Last name is too short" : null),
      email: (value) => (/^\S+@\S+$/.test(value) ? null : "Invalid email"),
      username: (value) => (value.length < 3 ? "Username is too short" : null),
      password: (value) => (value.length < 6 ? "Password is too short" : null),
      confirmPassword: (value, values) =>
        value !== values.password ? "Passwords do not match" : null,
    },
  });

  const handleSubmit = async (values: typeof form.values) => {
    setLoading(true);
    fetcher.submit(
      { ...values },
      {
        method: "POST",
        encType: "application/json",
      }
    );
  };

  // Handle fetcher state
  if (fetcher.data && fetcher.state === "idle" && loading) {
    setLoading(false);
    const res = fetcher.data as any;
    if (res.success) {
      notifications.show({
        title: "Success",
        message: "Super Admin created successfully. You can now login.",
        color: "green",
      });
      navigate("/auth/signin");
    } else {
      notifications.show({
        title: "Error",
        message: res.message || "Failed to create Super Admin",
        color: "red",
      });
    }
  }

  return (
    <Container fluid h={"100vh"}>
      <Flex h={"100%"} w={"100%"} justify={"center"} align="center">
        <Box w={450} p="xl" style={{ border: "1px solid #eee", borderRadius: "8px", boxShadow: "0 4px 12px rgba(0,0,0,0.05)" }}>
          <Stack gap="md">
            <Title order={2} ta="center">Setup Super Admin</Title>
            <Text size="sm" color="dimmed" ta="center">
              No super admin exists. Please create the initial super admin account to get started.
            </Text>

            <form onSubmit={form.onSubmit(handleSubmit)}>
              <Stack gap="sm">
                <Flex gap="sm">
                  <TextInput
                    label="First Name"
                    placeholder="John"
                    required
                    style={{ flex: 1 }}
                    {...form.getInputProps("firstName")}
                  />
                  <TextInput
                    label="Last Name"
                    placeholder="Doe"
                    required
                    style={{ flex: 1 }}
                    {...form.getInputProps("lastName")}
                  />
                </Flex>

                <TextInput
                  label="Email"
                  placeholder="admin@example.com"
                  required
                  {...form.getInputProps("email")}
                />

                <TextInput
                  label="Username"
                  placeholder="admin"
                  required
                  {...form.getInputProps("username")}
                />

                <PasswordInput
                  label="Password"
                  placeholder="Your password"
                  required
                  {...form.getInputProps("password")}
                />

                <PasswordInput
                  label="Confirm Password"
                  placeholder="Confirm your password"
                  required
                  {...form.getInputProps("confirmPassword")}
                />

                <Button type="submit" fullWidth mt="md" loading={loading}>
                  Create Super Admin
                </Button>
              </Stack>
            </form>
          </Stack>
        </Box>
      </Flex>
    </Container>
  );
}
