import { type FormEvent, useState } from "react";
import { Eye, EyeOff } from "lucide-react";
import { useLocation, useNavigate } from "react-router-dom";

import useAuth from "@/hooks/useAuth";
import AuthShell, { fieldClass, primaryButtonClass } from "@/components/auth/AuthShell";

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

/** Normalise Ethiopian local phone (09…/07…) to E.164; pass email through unchanged. */
function normaliseIdentifier(raw: string): string {
  const v = raw.trim();
  const digits = v.replace(/\D/g, "");
  if (digits.length >= 9 && (v.startsWith("0") || v.startsWith("+251"))) {
    const local = digits.startsWith("251") ? digits.slice(3) : digits.replace(/^0/, "");
    return `+251${local}`;
  }
  return v.toLowerCase();
}

export default function LoginPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const { login } = useAuth();
  const [identifier, setIdentifier] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  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 {
      setError("An unexpected error occurred");
    } 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>

        <div className="flex w-full flex-col gap-4">
          <div className="space-y-1.5">
            <label className="text-sm font-medium text-gray-800">
              Email or Phone <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={identifier}
              onChange={(event) => setIdentifier(event.target.value)}
              placeholder="name@company.com or 09XXXXXXXX"
              disabled={loading}
              autoComplete="username"
              className={fieldClass}
            />
          </div>

          <div className="space-y-1.5">
            <div className="flex items-center justify-between">
              <label className="text-sm font-medium text-gray-800">
                Password <span className="text-red-500">*</span>
              </label>
              <a href="#" className="text-xs font-semibold text-primary hover:underline">
                Forgot password?
              </a>
            </div>
            <div className="relative">
              <input
                type={showPassword ? "text" : "password"}
                value={password}
                onChange={(event) => setPassword(event.target.value)}
                placeholder="Enter your password"
                disabled={loading}
                className={`${fieldClass} pr-11`}
              />
              <button
                type="button"
                onClick={() => setShowPassword((current) => !current)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 transition-colors hover:text-gray-600"
                aria-label={showPassword ? "Hide password" : "Show password"}
              >
                {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
              </button>
            </div>
          </div>

          {error ? (
            <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2.5 text-sm text-red-700">
              {error}
            </div>
          ) : null}

          <button type="submit" disabled={loading} className={primaryButtonClass}>
            {loading ? "Signing in..." : "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>
        </div>
      </form>
    </AuthShell>
  );
}
