"use client";

import NextLink from "next/link";
import { useRouter } from "next/navigation";
import { useState, type SyntheticEvent } from "react";
import { z } from "zod";

import Box from "@mui/material/Box";
import Link from "@mui/material/Link";
import Paper from "@mui/material/Paper";
import Typography from "@mui/material/Typography";

import { AuthField } from "@/features/auth/components/auth-field";
import { ArrowLeftIcon } from "@/features/auth/components/auth-icons";
import { AuthLogoHeader } from "@/features/auth/components/auth-logo-header";
import { AuthPrimaryButton } from "@/features/auth/components/auth-primary-button";
import { forgotPassword } from "@/features/auth/service/auth-service";

const emailSchema = z
  .string()
  .trim()
  .min(1, { message: "Please enter your email." })
  .pipe(z.email({ message: "Please enter a valid email address." }));

export function ForgotPasswordScreen() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [emailError, setEmailError] = useState("");
  const [errorMessage, setErrorMessage] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSubmit(event: SyntheticEvent<HTMLFormElement>) {
    event.preventDefault();
    setEmailError("");
    setErrorMessage("");

    const parsed = emailSchema.safeParse(email);

    if (!parsed.success) {
      setEmailError(parsed.error.issues[0]?.message ?? "Invalid email.");
      return;
    }

    try {
      setIsSubmitting(true);
      await forgotPassword({ email: parsed.data });
      router.push(`/auth/otp?email=${encodeURIComponent(parsed.data)}`);
    } catch (error) {
      setErrorMessage(
        error instanceof Error ? error.message : "Unable to send the reset code.",
      );
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <Box
      sx={{
        minHeight: "100dvh",
        display: "flex",
        alignItems: { xs: "flex-start", md: "center" },
        justifyContent: "center",
        px: { xs: 2, sm: 3 },
        py: { xs: 2, sm: 3 },
      }}
    >
      <Paper
        elevation={0}
        sx={{
          width: "100%",
          maxWidth: 560,
          borderRadius: { xs: "20px", md: "12px" },
          border: "1px solid #edf8fd",
          backgroundColor: "#ffffff",
        }}
      >
        <Box
          component="form"
          onSubmit={handleSubmit}
          sx={{
            px: { xs: 3, sm: 5 },
            pt: { xs: 3, sm: 3.5 },
            pb: { xs: 5, sm: 6 },
            minHeight: { md: 730 },
          }}
        >
          <Link
            component={NextLink}
            href="/auth/login"
            underline="none"
            sx={{
              display: "inline-flex",
              alignItems: "center",
              gap: 1,
              fontSize: 14,
              fontWeight: 500,
              color: "#717680",
            }}
          >
            <ArrowLeftIcon />
            Back
          </Link>

          <Box sx={{ mt: { xs: 8, sm: 10 }, maxWidth: 401, mx: "auto" }}>
            <AuthLogoHeader title="Forgot password?">
              <Link
                component={NextLink}
                href="/auth/login"
                underline="none"
                sx={{
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 0.75,
                  fontSize: 14,
                  fontWeight: 500,
                  color: "#1570EF",
                }}
              >
                <ArrowLeftIcon color="#1570EF" />
                back to sign in
              </Link>
            </AuthLogoHeader>

            <Box
              sx={{
                mt: { xs: 5, sm: 6 },
                display: "flex",
                flexDirection: "column",
                gap: 4.5,
              }}
            >
              <Box
                sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}
              >
                <AuthField
                  autoComplete="email"
                  error={Boolean(emailError)}
                  helperText={emailError}
                  label="Email"
                  name="email"
                  onChange={(event) => {
                    setEmail(event.target.value);
                    setEmailError("");
                    setErrorMessage("");
                  }}
                  placeholder="your@gmail.com"
                  required
                  type="email"
                  value={email}
                />

                {errorMessage ? (
                  <Typography
                    sx={{
                      color: "#F04438",
                      fontSize: 12,
                      fontWeight: 600,
                      lineHeight: 1.4,
                    }}
                  >
                    {errorMessage}
                  </Typography>
                ) : null}
              </Box>

              <AuthPrimaryButton disabled={isSubmitting} type="submit">
                {isSubmitting ? "Sending..." : "Send e-mail"}
              </AuthPrimaryButton>
            </Box>
          </Box>
        </Box>
      </Paper>
    </Box>
  );
}
