"use client";

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

import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import InputAdornment from "@mui/material/InputAdornment";
import Link from "@mui/material/Link";
import Typography from "@mui/material/Typography";

import { AuthField } from "@/features/auth/components/auth-field";
import { EyeIcon } 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 { login } from "@/features/auth/service/auth-service";

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

type FieldErrors = {
  email?: string;
  password?: string;
};

export function LoginFormCard() {
  const router = useRouter();

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errorMessage, setErrorMessage] = useState("");
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);

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

    setErrorMessage("");
    setFieldErrors({});

    const parsed = loginSchema.safeParse({
      email,
      password,
    });

    if (!parsed.success) {
      const emailError = parsed.error.issues.find(
        (issue) => issue.path[0] === "email",
      );

      const passwordError = parsed.error.issues.find(
        (issue) => issue.path[0] === "password",
      );

      setFieldErrors({
        email: emailError?.message,
        password: passwordError?.message,
      });

      return;
    }

    try {
      setIsSubmitting(true);

      localStorage.removeItem("token");
      localStorage.removeItem("accessToken");
      localStorage.removeItem("access_token");

      const data = await login({
        email: parsed.data.email,
        password: parsed.data.password,
      });

      router.push(data.redirectTo || "/account-setting");
      router.refresh();
    } catch (error) {
      setErrorMessage(
        error instanceof Error ? error.message : "Email or password is incorrect.",
      );
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <Box
      component="form"
      onSubmit={handleSubmit}
      sx={{
        width: "100%",
        maxWidth: 511,
        mx: { xs: "auto", lg: 0 },
        px: { xs: 3, sm: 5, lg: 0 },
        py: { xs: 5, sm: 6, lg: "clamp(24px, 4vh, 48px)" },
        ml: { lg: "clamp(32px, 8vw, 101px)" },
        mr: { lg: "clamp(24px, 4vw, 48px)" },
        height: { lg: "100%" },
        minHeight: 0,
        display: { lg: "flex" },
        flexDirection: { lg: "column" },
        justifyContent: { lg: "center" },
        overflow: { lg: "hidden" },
        boxSizing: "border-box",
      }}
    >
      <Box sx={{ width: "100%" }}>
        <AuthLogoHeader title="Sign in to your account" />
      </Box>

      <Box
        sx={{
          mt: { xs: 5, lg: "clamp(20px, 4vh, 66px)" },
          display: "flex",
          flexDirection: "column",
          gap: { xs: 4, lg: "clamp(24px, 3vh, 44px)" },
        }}
      >
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            alignItems: "flex-end",
            gap: 2,
          }}
        >
          <Box
            sx={{
              width: "100%",
              display: "flex",
              flexDirection: "column",
              gap: "22px",
            }}
          >
            <AuthField
              autoComplete="email"
              error={Boolean(fieldErrors.email)}
              helperText={fieldErrors.email}
              label="Email"
              name="email"
              placeholder="privatesectorusergmail.com"
              onChange={(event) => {
                setEmail(event.target.value);
                setErrorMessage("");
                setFieldErrors((current) => ({
                  ...current,
                  email: undefined,
                }));
              }}
              type="email"
              value={email}
            />

            <AuthField
              autoComplete="current-password"
              error={Boolean(fieldErrors.password)}
              helperText={fieldErrors.password}
              label="Password"
              name="password"
              placeholder="Your password"
              onChange={(event) => {
                setPassword(event.target.value);
                setErrorMessage("");
                setFieldErrors((current) => ({
                  ...current,
                  password: undefined,
                }));
              }}
              type={showPassword ? "text" : "password"}
              value={password}
              endAdornment={
                <InputAdornment position="end">
                  <IconButton
                    aria-label={showPassword ? "Hide password" : "Show password"}
                    edge="end"
                    onClick={() => setShowPassword((value) => !value)}
                    sx={{ mr: 0.5 }}
                  >
                    <EyeIcon />
                  </IconButton>
                </InputAdornment>
              }
            />
          </Box>

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

          <Link
            href="/auth/forgot-password"
            underline="none"
            sx={{
              fontSize: 12,
              fontWeight: 700,
              lineHeight: 1,
              color: "#000000",
              textDecoration: "underline",
              textDecorationSkipInk: "none",
            }}
          >
            Forgot password?
          </Link>
        </Box>

        <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
          <AuthPrimaryButton disabled={isSubmitting} type="submit">
            {isSubmitting ? "SIGNING IN..." : "SIGN IN"}
          </AuthPrimaryButton>
        </Box>
      </Box>
    </Box>
  );
}
