import { useState } from "react";
import { useLocation } from "wouter";
import { trpc } from "@/lib/trpc";
import { useAuth } from "@/_core/hooks/useAuth";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Bot,
  Eye,
  EyeOff,
  Loader2,
  Mail,
  Lock,
  AlertCircle,
  ArrowLeft,
} from "lucide-react";
import { Link } from "wouter";

export default function Login() {
  const [, navigate] = useLocation();
  const { isAuthenticated, loading: authLoading } = useAuth();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");

  const loginMutation = trpc.auth.login.useMutation({
    onSuccess: () => {
      // Redirect to dashboard after login
      const params = new URLSearchParams(window.location.search);
      const base = import.meta.env.BASE_URL ?? "/";
      const raw = params.get("returnTo");
      // Validate returnTo to prevent open redirect attacks (must be a relative path)
      const returnTo = (raw && raw.startsWith("/") && !raw.startsWith("//"))
        ? raw
        : `${base}dashboard`;
      window.location.href = returnTo;
    },
    onError: (err) => {
      setError(err.message || "Invalid email or password");
    },
  });

  // Redirect if already logged in
  if (!authLoading && isAuthenticated) {
    window.location.href = `${import.meta.env.BASE_URL ?? "/"}dashboard`;
    return null;
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    if (!email || !password) {
      setError("Please fill in all fields");
      return;
    }
    loginMutation.mutate({ email, password });
  };

  const isLoading = loginMutation.isPending;

  return (
    <div
      className="min-h-screen flex items-center justify-center px-4 py-12 relative"
      style={{ background: "linear-gradient(135deg, #FFFBEB 0%, #f5f0e8 50%, #e8e0d4 100%)" }}
    >
      {/* Decorative elements */}
      <div className="absolute top-0 left-0 w-full h-1" style={{ background: "#14532D" }} />
      <div
        className="absolute top-20 right-20 w-64 h-64 rounded-full opacity-10"
        style={{ background: "#14532D", filter: "blur(80px)" }}
      />
      <div
        className="absolute bottom-20 left-20 w-48 h-48 rounded-full opacity-10"
        style={{ background: "#C2410C", filter: "blur(60px)" }}
      />

      <div className="w-full max-w-md relative z-10">
        {/* Back to home */}
        <Link
          href="/"
          className="inline-flex items-center gap-1.5 text-sm mb-6 transition-colors hover:opacity-80"
          style={{ color: "#78716C", fontFamily: "'Source Sans 3', sans-serif" }}
        >
          <ArrowLeft className="w-4 h-4" />
          Back to home
        </Link>

        <Card
          className="border-0 shadow-xl"
          style={{ background: "#fff", boxShadow: "0 20px 60px rgba(120, 113, 108, 0.12)" }}
        >
          <CardHeader className="text-center pb-2">
            {/* Logo */}
            <div className="flex justify-center mb-4">
              <div
                className="w-14 h-14 rounded-2xl flex items-center justify-center"
                style={{
                  background: "linear-gradient(135deg, #14532D 0%, #166534 100%)",
                  boxShadow: "0 4px 16px rgba(20, 83, 45, 0.3)",
                }}
              >
                <Bot className="w-7 h-7 text-white" />
              </div>
            </div>
            <CardTitle
              className="text-2xl"
              style={{ fontFamily: "'Playfair Display', serif", color: "#292524" }}
            >
              Welcome Back
            </CardTitle>
            <CardDescription
              className="text-sm mt-1"
              style={{ fontFamily: "'Source Sans 3', sans-serif", color: "#78716C" }}
            >
              Sign in to access the Homelegance Dashboard
            </CardDescription>
          </CardHeader>

          <CardContent className="pt-4">
            <form onSubmit={handleSubmit} className="space-y-4">
              {error && (
                <div
                  className="flex items-center gap-2 p-3 rounded-lg text-sm"
                  style={{
                    background: "#FEF2F2",
                    color: "#DC2626",
                    border: "1px solid #FECACA",
                    fontFamily: "'Source Sans 3', sans-serif",
                  }}
                >
                  <AlertCircle className="w-4 h-4 shrink-0" />
                  {error}
                </div>
              )}

              <div className="space-y-2">
                <Label
                  htmlFor="email"
                  className="text-sm font-medium"
                  style={{ color: "#57534e", fontFamily: "'Source Sans 3', sans-serif" }}
                >
                  Email Address
                </Label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    id="email"
                    type="email"
                    placeholder="you@company.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="pl-10 h-11"
                    style={{
                      borderColor: "#e7e0d5",
                      fontFamily: "'Source Sans 3', sans-serif",
                    }}
                    disabled={isLoading}
                    autoComplete="email"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label
                    htmlFor="password"
                    className="text-sm font-medium"
                    style={{ color: "#57534e", fontFamily: "'Source Sans 3', sans-serif" }}
                  >
                    Password
                  </Label>
                  <Link
                    href="/forgot-password"
                    className="text-xs font-medium transition-colors hover:opacity-80"
                    style={{ color: "#C2410C", fontFamily: "'Source Sans 3', sans-serif" }}
                  >
                    Forgot your password?
                  </Link>
                </div>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="Enter your password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="pl-10 pr-10 h-11"
                    style={{
                      borderColor: "#e7e0d5",
                      fontFamily: "'Source Sans 3', sans-serif",
                    }}
                    disabled={isLoading}
                    autoComplete="current-password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              <Button
                type="submit"
                className="w-full h-11 text-sm font-semibold"
                style={{
                  background: "linear-gradient(135deg, #14532D 0%, #166534 100%)",
                  fontFamily: "'Source Sans 3', sans-serif",
                  boxShadow: "0 2px 8px rgba(20, 83, 45, 0.25)",
                }}
                disabled={isLoading}
              >
                {isLoading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Signing in...
                  </>
                ) : (
                  "Sign In"
                )}
              </Button>
            </form>

          </CardContent>

          <CardFooter className="justify-center pb-6">
            <p
              className="text-sm"
              style={{ color: "#78716C", fontFamily: "'Source Sans 3', sans-serif" }}
            >
              Don't have an account?{" "}
              <Link
                href="/register"
                className="font-semibold transition-colors hover:opacity-80"
                style={{ color: "#14532D" }}
              >
                Create one
              </Link>
            </p>
          </CardFooter>
        </Card>

        {/* Footer */}
        <p
          className="text-center text-xs mt-6"
          style={{ color: "#a8a29e", fontFamily: "'Source Sans 3', sans-serif" }}
        >
          Homelegance Chatbot Administration Portal
        </p>
      </div>
    </div>
  );
}
