import {
  Button,
  TextInput,
  Stack,
  Title,
  Text,
  Anchor,
} from "@mantine/core";
import { useForm } from "@mantine/form";
import { Link } from "react-router";
import { useCoreFetcher } from "@/lib/features/useCoreFetcher";

export default function ForgotPasswordForm() {
  const { trigger: forgotPasswordTrigger, isLoading, data } = useCoreFetcher(
    "forgot-password",
    "post"
  );

  const form = useForm({
    mode: "controlled",
    initialValues: { email: "" },
    validate: {
      email: (value) => (/^\S+@\S+$/.test(value) ? null : "Invalid email"),
    },
  });

  const handleSubmit = (data: typeof form.values) => {
    forgotPasswordTrigger({ email: data.email });
  };

  if (data && (data as any).success) {
    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' }}>Check Your Email</Title>
        <Text size="sm" c="dimmed" style={{ textAlign: 'center' }}>
          If the email exists in our system, you will receive a password reset link shortly.
        </Text>
        <Anchor component={Link} to="/auth/signin" size="sm" style={{ textAlign: 'center' }}>
          Back to Sign In
        </Anchor>
      </Stack>
    );
  }

  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' }}>Forgot Password?</Title>
      <Text size="sm" c="dimmed" style={{ textAlign: 'center' }}>
        Enter your registered email below to receive a password reset link.
      </Text>
      <form onSubmit={form.onSubmit(handleSubmit)}>
        <TextInput
          label="Registered Email"
          placeholder="Enter email address"
          key={form.key("email")}
          {...form.getInputProps("email")}
        />
        <Button
          type="submit"
          mt="xl"
          size="md"
          fullWidth
          loading={isLoading}
        >
          Send Reset Link
        </Button>
      </form>
      <Anchor component={Link} to="/auth/signin" size="sm" style={{ textAlign: 'center' }} mt="sm">
          Back to Sign In
      </Anchor>
    </Stack>
  );
}
