import {
  Button,
  PasswordInput,
  Stack,
  Title,
  Text,
} from "@mantine/core";
import { useForm } from "@mantine/form";
import { toast } from "sonner";
import { useCoreFetcher } from "@/lib/features/useCoreFetcher";

export default function SetPasswordForm({ token }: { token: string }) {
  const { trigger: setPasswordTrigger, isLoading } = useCoreFetcher(
    "set-password",
    "post",
    {
      onSuccess: () => {
        toast.success("Password set successfully. You can now sign in.");
        setTimeout(() => {
            window.location.href = "/auth/signin";
        }, 2000);
      },
      onError: (error) =>
        toast.error(
          (error as any)?.message ?? "Failed to set password. Please try again.",
        ),
    },
  );

  const form = useForm({
    mode: "controlled",
    initialValues: { password: "", confirmPassword: "" },
    validate: {
      password: (value) =>
        value.length < 6 ? "Password must be at least 6 characters long" : null,
      confirmPassword: (value, values) =>
        value !== values.password ? "Passwords do not match" : null,
    },
  });

  const handleSubmit = (data: typeof form.values) => {
    setPasswordTrigger({ token, password: data.password });
  };

  return (
    <Stack gap="md" bg="white" p="xl" style={{ borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.1)' }}>
      <Title order={2} style={{ textAlign: 'center' }}>Set Your Password</Title>
      <Text size="sm" c="dimmed" style={{ textAlign: 'center' }}>
        Please enter a new password for your account.
      </Text>
      <form onSubmit={form.onSubmit(handleSubmit)}>
        <PasswordInput
          label="New Password"
          placeholder="Enter new password"
          key={form.key("password")}
          {...form.getInputProps("password")}
        />
        <PasswordInput
          mt="sm"
          label="Confirm Password"
          placeholder="Confirm new password"
          key={form.key("confirmPassword")}
          {...form.getInputProps("confirmPassword")}
        />
        <Button
          type="submit"
          mt="xl"
          size="md"
          fullWidth
          loading={isLoading}
        >
          Set Password
        </Button>
      </form>
    </Stack>
  );
}
