import { useState } from "react";
import { useParams } from "wouter";
import { trpc } from "@/lib/trpc";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Loader2,
  Lock,
  Eye,
  EyeOff,
  AlertCircle,
  ArrowLeft,
  CheckCircle2,
  ShieldAlert,
} from "lucide-react";
import { Link } from "wouter";

export default function ResetPassword() {
  const params = useParams<{ token: string }>();
  const token = params.token || "";

  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);

  // Validate the token
  const validateQuery = trpc.auth.validateResetToken.useQuery(
    { token },
    { enabled: !!token, retry: false }
  );

  const resetMutation = trpc.auth.resetPassword.useMutation({
    onSuccess: () => {
      setSuccess(true);
    },
    onError: (err) => {
      setError(err.message || "Failed to reset password");
    },
  });

  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 (!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;
    }

    resetMutation.mutate({ token, newPassword: password });
  };

  const isLoading = resetMutation.isPending;
  const isValidating = validateQuery.isLoading;
  const isValid = validateQuery.data?.valid;
  const validationReason = validateQuery.data && !validateQuery.data.valid
    ? validateQuery.data.reason
    : null;

  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%)" }}
    >
      <div className="absolute top-0 left-0 w-full h-1" style={{ background: "#14532D" }} />

      <div className="w-full max-w-md relative z-10">
        <Link
          href="/login"
          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 sign in
        </Link>

        <Card
          className="border-0 shadow-xl"
          style={{ background: "#fff", boxShadow: "0 20px 60px rgba(120, 113, 108, 0.12)" }}
        >
          {/* Loading state */}
          {isValidating && (
            <>
              <CardHeader className="text-center pb-2">
                <div className="flex justify-center mb-4">
                  <Loader2 className="w-10 h-10 animate-spin" style={{ color: "#14532D" }} />
                </div>
                <CardTitle
                  className="text-xl"
                  style={{ fontFamily: "'Playfair Display', serif", color: "#292524" }}
                >
                  Validating Reset Link...
                </CardTitle>
              </CardHeader>
            </>
          )}

          {/* Invalid token */}
          {!isValidating && !isValid && !success && (
            <>
              <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, #DC2626 0%, #EF4444 100%)",
                      boxShadow: "0 4px 16px rgba(220, 38, 38, 0.3)",
                    }}
                  >
                    <ShieldAlert className="w-7 h-7 text-white" />
                  </div>
                </div>
                <CardTitle
                  className="text-2xl"
                  style={{ fontFamily: "'Playfair Display', serif", color: "#292524" }}
                >
                  Invalid Reset Link
                </CardTitle>
                <CardDescription
                  className="text-sm mt-1"
                  style={{ fontFamily: "'Source Sans 3', sans-serif", color: "#78716C" }}
                >
                  {validationReason || "This password reset link is not valid"}
                </CardDescription>
              </CardHeader>
              <CardContent className="pt-4 text-center">
                <Link href="/forgot-password">
                  <Button
                    className="text-sm font-semibold"
                    style={{
                      background: "linear-gradient(135deg, #C2410C 0%, #ea580c 100%)",
                      fontFamily: "'Source Sans 3', sans-serif",
                    }}
                  >
                    Request a New Reset Link
                  </Button>
                </Link>
              </CardContent>
            </>
          )}

          {/* Success state */}
          {success && (
            <>
              <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, #16a34a 0%, #15803d 100%)",
                      boxShadow: "0 4px 16px rgba(22, 163, 74, 0.3)",
                    }}
                  >
                    <CheckCircle2 className="w-7 h-7 text-white" />
                  </div>
                </div>
                <CardTitle
                  className="text-2xl"
                  style={{ fontFamily: "'Playfair Display', serif", color: "#292524" }}
                >
                  Password Reset!
                </CardTitle>
                <CardDescription
                  className="text-sm mt-1"
                  style={{ fontFamily: "'Source Sans 3', sans-serif", color: "#78716C" }}
                >
                  Your password has been successfully updated
                </CardDescription>
              </CardHeader>
              <CardContent className="pt-4 text-center">
                <Link href="/login">
                  <Button
                    className="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)",
                    }}
                  >
                    Sign In with New Password
                  </Button>
                </Link>
              </CardContent>
            </>
          )}

          {/* Reset form */}
          {!isValidating && isValid && !success && (
            <>
              <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)",
                    }}
                  >
                    <Lock className="w-7 h-7 text-white" />
                  </div>
                </div>
                <CardTitle
                  className="text-2xl"
                  style={{ fontFamily: "'Playfair Display', serif", color: "#292524" }}
                >
                  Set New Password
                </CardTitle>
                <CardDescription
                  className="text-sm mt-1"
                  style={{ fontFamily: "'Source Sans 3', sans-serif", color: "#78716C" }}
                >
                  {validateQuery.data?.valid && "email" in validateQuery.data
                    ? `Enter a new password for ${validateQuery.data.email}`
                    : "Choose a strong password for your account"}
                </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="password"
                      className="text-sm font-medium"
                      style={{ color: "#57534e", fontFamily: "'Source Sans 3', sans-serif" }}
                    >
                      New 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="Enter new 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.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 New 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 new 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" />
                        Resetting password...
                      </>
                    ) : (
                      "Reset Password"
                    )}
                  </Button>
                </form>
              </CardContent>
            </>
          )}
        </Card>
      </div>
    </div>
  );
}
