"use client";

import NextLink from "next/link";
import { useRouter, useSearchParams } 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 { resetPassword } from "@/features/auth/service/auth-service";

const passwordSchema = z
  .object({
    newPassword: z
      .string()
      .min(1, { message: "Please enter a new password." })
      .min(8, { message: "Password must be at least 8 characters." }),
    confirmPassword: z
      .string()
      .min(1, { message: "Please confirm your password." }),
  })
  .refine((data) => data.newPassword === data.confirmPassword, {
    message: "Passwords do not match.",
    path: ["confirmPassword"],
  });

type FieldErrors = {
  newPassword?: string;
  confirmPassword?: string;
};

export function ResetPasswordScreen() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const email = searchParams.get("email") ?? "";
  const otp = searchParams.get("otp") ?? "";

  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
  const [errorMessage, setErrorMessage] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

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

    if (!email || !otp) {
      setErrorMessage(
        "Missing email or OTP. Please start from the forgot password page.",
      );
      return;
    }

    const parsed = passwordSchema.safeParse({ newPassword, confirmPassword });

    if (!parsed.success) {
      const flattened = z.flattenError(parsed.error).fieldErrors;
      setFieldErrors({
        newPassword: flattened.newPassword?.[0],
        confirmPassword: flattened.confirmPassword?.[0],
      });
      return;
    }

    try {
      setIsSubmitting(true);

      await resetPassword({
        email,
        otp,
        newPassword: parsed.data.newPassword,
      });

      router.push("/auth/login?reset=success");
    } catch (error) {
      setErrorMessage(
        error instanceof Error ? error.message : "Unable to reset your password.",
      );
    } 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/otp?email=${encodeURIComponent(email)}`}
            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",
              display: "flex",
              flexDirection: "column",
              gap: 4.5,
            }}
          >
            <AuthLogoHeader title="New password" />

            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                gap: 2.25,
              }}
            >
              <AuthField
                autoComplete="new-password"
                error={Boolean(fieldErrors.newPassword)}
                helperText={fieldErrors.newPassword}
                label="New password"
                name="newPassword"
                onChange={(event) => {
                  setNewPassword(event.target.value);
                  setFieldErrors((prev) => ({ ...prev, newPassword: undefined }));
                  setErrorMessage("");
                }}
                placeholder="Enter a new password"
                type="password"
                value={newPassword}
              />

              <AuthField
                autoComplete="new-password"
                error={Boolean(fieldErrors.confirmPassword)}
                helperText={fieldErrors.confirmPassword}
                label="Password confirmation"
                name="confirmPassword"
                onChange={(event) => {
                  setConfirmPassword(event.target.value);
                  setFieldErrors((prev) => ({
                    ...prev,
                    confirmPassword: undefined,
                  }));
                  setErrorMessage("");
                }}
                placeholder="Enter the password again"
                type="password"
                value={confirmPassword}
              />

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

            <AuthPrimaryButton disabled={isSubmitting} type="submit">
              {isSubmitting ? "Saving..." : "Confirm"}
            </AuthPrimaryButton>
          </Box>
        </Box>
      </Paper>
    </Box>
  );
}
