import { type FormEvent, useState } from "react";
import { Alert, Button, PasswordInput, Stack, TextInput } from "@mantine/core";
import { AlertCircle } from "lucide-react";
import { Link, useLocation, useNavigate } from "react-router-dom";

import useAuth from "@/hooks/useAuth";
import AuthShell from "@/components/auth/AuthShell";
import { normaliseIdentifier } from "@/utils/identifier";
import { extractApiError } from "@/utils/result";

const EDR_LOGO = "/assets/edr-logo.png";

export default function LoginPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const { login } = useAuth();
  const [identifier, setIdentifier] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const result = await login({ email: normaliseIdentifier(identifier), password });
      if (result.success) {
        const from = (location.state as { from?: { pathname: string } } | null)?.from
          ?.pathname;
        navigate(from ?? "/portal", { replace: true });
      } else {
        setError(result.error.message);
      }
    } catch (err) {
      setError(extractApiError(err).message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthShell>
      <form className="flex w-full flex-col" onSubmit={handleSubmit}>
        <div className="mb-4 flex justify-center sm:mb-6">
          <img src={EDR_LOGO} alt="EDR Freight" className="h-9 w-auto sm:h-11" />
        </div>

        <div className="mb-4 space-y-1.5 text-center sm:mb-5">
          <h1 className="text-xl font-bold tracking-tight text-gray-900 sm:text-2xl">
            Welcome back
          </h1>
          <p className="text-sm leading-relaxed text-gray-500">
            Enter your credentials to access your freight portal.
          </p>
        </div>

        <Stack gap="md">
          <TextInput
            label="Email or Phone"
            placeholder="name@company.com or 09XXXXXXXX"
            autoComplete="username"
            required
            disabled={loading}
            value={identifier}
            onChange={(event) => setIdentifier(event.target.value)}
          />

          <div>
            <div className="mb-1.5 flex items-center justify-between">
              <span className="text-sm font-medium text-gray-800">Password</span>
              <Link
                to="/forgot-password"
                className="text-xs font-semibold text-primary hover:underline"
              >
                Forgot password?
              </Link>
            </div>
            <PasswordInput
              placeholder="Enter your password"
              required
              disabled={loading}
              value={password}
              onChange={(event) => setPassword(event.target.value)}
            />
          </div>

          {error ? (
            <Alert color="red" variant="light" icon={<AlertCircle size={18} />}>
              {error}
            </Alert>
          ) : null}

          <Button type="submit" color="edr-green" fullWidth loading={loading}>
            Sign In
          </Button>

          <p className="text-center text-sm text-gray-500">
            Don&apos;t have an account?{" "}
            <button
              type="button"
              onClick={() => navigate("/signup")}
              className="font-semibold text-primary hover:underline"
            >
              Create an account
            </button>
          </p>
        </Stack>
      </form>
    </AuthShell>
  );
}
