import { useCoreFetcher } from "@/lib/features/useCoreFetcher";
import { Button, Flex, Grid, Modal, PasswordInput, Text } from "@mantine/core";
import { useForm } from "@mantine/form";
import { useDisclosure } from "@mantine/hooks";
import { IconEdit } from "@tabler/icons-react";
import { zod4Resolver } from "mantine-form-zod-resolver";
import { toast } from "sonner";
import z from "zod";

const schema = z
  .object({
    password: z
      .string()
      .min(8, { message: "Password must be at least 8 characters long" }),
    confirmPassword: z.string().min(8, {
      message: "Confirm Password must be at least 8 characters long",
    }),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: "Passwords do not match",
    path: ["confirmPassword"],
  });
type SchemaType = z.infer<typeof schema>;

const ResetPasswordPopup: React.FC<{
  memberRecordId: string;
}> = ({ memberRecordId }) => {
  const form = useForm<SchemaType>({
    initialValues: {
      password: "",
      confirmPassword: "",
    },
    validate: zod4Resolver(schema),
  });
  const [opened, { open, close }] = useDisclosure(false);

  const { trigger: resetPasswordTrigger, isLoading: resetPasswordLoading } =
    useCoreFetcher("reset-member-password", "patch", {
      onSuccess: () => {
        toast.success("Password updated successfully");
        form.reset();
      },
      onError: (error) => {
        toast.error(
          (error as Error)?.message ?? "Failed to reset member password",
        );
      },
    });

  const handleSubmit = async () => {
    const result = form.validate();
    if (!result.hasErrors) {
      const parsed = schema.parse(form.values);
      await resetPasswordTrigger({ password: parsed.password, memberRecordId });
      close();
    }
  };
  return (
    <>
      <Modal
        opened={opened}
        onClose={close}
        title={
          <Flex align={"center"} justify={"center"} gap={10}>
            <Text fz={16} fw={600} c={"dark.10"}>
              Update Password
            </Text>
          </Flex>
        }
        radius={12}
        centered
      >
        <Modal.Body>
          <form>
            <Grid columns={6} gutter={"lg"}>
              <Grid.Col span={6}>
                <PasswordInput
                  label="Enter Password"
                  placeholder="Enter Password"
                  key={form.key("password")}
                  {...form.getInputProps("password")}
                />
              </Grid.Col>
              <Grid.Col span={6}>
                <PasswordInput
                  label="Re Enter Password"
                  placeholder="Re Enter Password"
                  key={form.key("confirmPassword")}
                  {...form.getInputProps("confirmPassword")}
                />
              </Grid.Col>
              <Grid.Col span={6}>
                <Button
                  variant="light"
                  w={"100%"}
                  onClick={handleSubmit}
                  loading={resetPasswordLoading}
                >
                  Save
                </Button>
              </Grid.Col>
            </Grid>
          </form>
        </Modal.Body>
      </Modal>

      <Button variant="light" onClick={open}>
        <IconEdit size={12} style={{ marginRight: "10px" }} />
        Reset Member Password
      </Button>
    </>
  );
};

export default ResetPasswordPopup;
