import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { ArrowRight, Mail, Phone, Loader2 } from "lucide-react";
import useAuth from "@/hooks/useAuth";
import AuthLayout from "@/components/auth/AuthLayout";
import {
  Button,
  Input,
  Field,
  FieldLabel,
  FieldError,
  FieldGroup,
} from "@edr/ui-common";
import PhoneInput from "@/components/auth/PhoneInput";

type LoginMethod = "email" | "phone";

export default function LoginPage() {
  const navigate = useNavigate();
  const { login } = useAuth();
  const [method, setMethod] = useState<LoginMethod>("email");
  const [identifier, setIdentifier] = useState("");
  const [countryCode, setCountryCode] = useState("+251");
  const [phoneNumber, setPhoneNumber] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const loginId = method === "email"
        ? identifier
        : `${countryCode}${phoneNumber.startsWith("0") ? phoneNumber.slice(1) : phoneNumber}`;
      const result = await login({ email: loginId, password });
      if (result.success) {
        navigate("/");
      } else {
        setError(result.error.message);
      }
    } catch {
      setError("An unexpected error occurred");
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthLayout
      left={{
        badge: "Welcome Back",
        title: "Sign in to your freight operations account",
        description:
          "Access your dashboard to manage shipments, monitor railway operations, track consignments, and streamline logistics workflows.",
        features: [
          "Real-time shipment tracking",
          "Secure logistics management",
          "Enterprise-grade operations",
          "Multi-corridor freight monitoring",
        ],
        stats: {
          label: "Active Corridors",
          value: "24+",
          footer: "Operational",
          progress: "w-[95%]",
        },
      }}
    >
      <div className="mb-6">
        <div className="mb-4 flex size-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
          <Mail className="size-6" />
        </div>
        <h2 className="text-2xl font-black tracking-tight">Welcome back</h2>
        <p className="mt-2 text-base text-muted-foreground">
          Enter your credentials to access your portal
        </p>
      </div>

      <form onSubmit={handleSubmit} className="flex flex-col gap-4">
        <div className="flex gap-2 rounded-lg bg-muted p-1">
          <Button
            type="button"
            variant={"ghost"}
            size="sm"
            onClick={() => setMethod("email")}
            className={`flex-1 hover:bg-background/40! ${method === "email" ? "bg-background shadow border" : ""}`}
          >
            <Mail data-icon="inline-start" />
            Email
          </Button>
          <Button
            type="button"
            variant={"ghost"}
            size="sm"
            onClick={() => setMethod("phone")}
            className={`flex-1 hover:bg-background/40! ${method === "phone" ? "bg-background shadow border" : ""}`}
          >
            <Phone data-icon="inline-start" />
            Phone
          </Button>
        </div>

        <FieldGroup>
          {method === "email" ? (
            <Field>
              <FieldLabel>Email Address</FieldLabel>
              <Input
                type="email"
                placeholder="name@company.com"
                value={identifier}
                onChange={(e) => setIdentifier(e.target.value)}
                required
                disabled={loading}
              />
            </Field>
          ) : (
            <PhoneInput
              disabled={loading}
              countryCode={{
                value: countryCode,
                onChange: (e: React.ChangeEvent<HTMLInputElement>) => setCountryCode(e.target.value),
              }}
              phone={{
                value: phoneNumber,
                onChange: (e: React.ChangeEvent<HTMLInputElement>) => setPhoneNumber(e.target.value),
              }}
            />
          )}

          <Field>
            <div className="flex items-center justify-between">
              <FieldLabel>Password</FieldLabel>
              <Button
                type="button"
                variant="link"
                size="xs"
                className="h-auto p-0"
              >
                Forgot password?
              </Button>
            </div>
            <Input
              type="password"
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              disabled={loading}
            />
          </Field>
        </FieldGroup>

        {error && (
          <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-2.5 text-sm text-red-700">
            {error}
          </div>
        )}

        <Button type="submit" disabled={loading} size="lg" className="w-full">
          {loading ? (
            <>
              <Loader2 className="animate-spin" data-icon="inline-start" />
              Signing in...
            </>
          ) : (
            <>
              Sign In
              <ArrowRight data-icon="inline-end" />
            </>
          )}
        </Button>

        <p className="text-center text-sm text-muted-foreground">
          Don't have an account?{" "}
          <Button
            type="button"
            variant="link"
            size="sm"
            onClick={() => navigate("/signup")}
            className="h-auto p-0 font-semibold"
          >
            Create an account
          </Button>
        </p>
      </form>
    </AuthLayout>
  );
}
