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,
  User,
  AlertCircle,
  ArrowLeft,
  CheckCircle2,
} from "lucide-react";
import { Link } from "wouter";

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

  const registerMutation = trpc.auth.register.useMutation({
    onSuccess: () => {
      window.location.href = `${import.meta.env.BASE_URL ?? "/"}dashboard`;
    },
    onError: (err) => {
      setError(err.message || "Registration failed");
    },
  });

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

  const passwordChecks = [
    { label: "At least 8 characters", met: password.length >= 8 },
    { label: "Contains a number", met: /\d/.test(password) },
    { label: "Contains uppercase letter", met: /[A-Z]/.test(password) },
  ];

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    if (!name || !email || !password || !confirmPassword) {
      setError("Please fill in all fields");
      return;
    }
    if (password !== confirmPassword) {
      setError("Passwords do not match");
      return;
    }
    if (password.length < 8) {
      setError("Password must be at least 8 characters");
      return;
    }

    registerMutation.mutate({ email, password, name });
  };

  const isLoading = registerMutation.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 left-20 w-64 h-64 rounded-full opacity-10"
        style={{ background: "#C2410C", filter: "blur(80px)" }}
      />
      <div
        className="absolute bottom-20 right-20 w-48 h-48 rounded-full opacity-10"
        style={{ background: "#14532D", 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">
            <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" }}
            >
              Create Account
            </CardTitle>
            <CardDescription
              className="text-sm mt-1"
              style={{ fontFamily: "'Source Sans 3', sans-serif", color: "#78716C" }}
            >
              Join the Homelegance team to manage the chatbot
            </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="name"
                  className="text-sm font-medium"
                  style={{ color: "#57534e", fontFamily: "'Source Sans 3', sans-serif" }}
                >
                  Full Name
                </Label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    id="name"
                    type="text"
                    placeholder="John Smith"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    className="pl-10 h-11"
                    style={{ borderColor: "#e7e0d5", fontFamily: "'Source Sans 3', sans-serif" }}
                    disabled={isLoading}
                    autoComplete="name"
                  />
                </div>
              </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">
                <Label
                  htmlFor="password"
                  className="text-sm font-medium"
                  style={{ color: "#57534e", fontFamily: "'Source Sans 3', sans-serif" }}
                >
                  Password
                </Label>
                <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="Create a strong 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="new-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>

                {/* Password strength indicators */}
                {password.length > 0 && (
                  <div className="space-y-1 mt-2">
                    {passwordChecks.map((check) => (
                      <div
                        key={check.label}
                        className="flex items-center gap-2 text-xs"
                        style={{
                          color: check.met ? "#16a34a" : "#a8a29e",
                          fontFamily: "'Source Sans 3', sans-serif",
                        }}
                      >
                        <CheckCircle2
                          className="w-3.5 h-3.5"
                          style={{ opacity: check.met ? 1 : 0.4 }}
                        />
                        {check.label}
                      </div>
                    ))}
                  </div>
                )}
              </div>

              <div className="space-y-2">
                <Label
                  htmlFor="confirmPassword"
                  className="text-sm font-medium"
                  style={{ color: "#57534e", fontFamily: "'Source Sans 3', sans-serif" }}
                >
                  Confirm Password
                </Label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    id="confirmPassword"
                    type="password"
                    placeholder="Confirm your password"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    className="pl-10 h-11"
                    style={{ borderColor: "#e7e0d5", fontFamily: "'Source Sans 3', sans-serif" }}
                    disabled={isLoading}
                    autoComplete="new-password"
                  />
                </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" />
                    Creating account...
                  </>
                ) : (
                  "Create Account"
                )}
              </Button>
            </form>
          </CardContent>

          <CardFooter className="justify-center pb-6">
            <p
              className="text-sm"
              style={{ color: "#78716C", fontFamily: "'Source Sans 3', sans-serif" }}
            >
              Already have an account?{" "}
              <Link
                href="/login"
                className="font-semibold transition-colors hover:opacity-80"
                style={{ color: "#14532D" }}
              >
                Sign in
              </Link>
            </p>
          </CardFooter>
        </Card>
      </div>
    </div>
  );
}
