import { useState } from "react";
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 {
  Bot,
  Loader2,
  Mail,
  AlertCircle,
  ArrowLeft,
  CheckCircle2,
  Copy,
  ExternalLink,
} from "lucide-react";
import { Link } from "wouter";

export default function ForgotPassword() {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");
  const [sent, setSent] = useState(false);
  const [resetToken, setResetToken] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  const forgotMutation = trpc.auth.forgotPassword.useMutation({
    onSuccess: (data) => {
      setSent(true);
      // In demo mode, the token is returned for testing
      if (data.resetToken) {
        setResetToken(data.resetToken);
      }
    },
    onError: (err) => {
      setError(err.message || "Something went wrong");
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    if (!email) {
      setError("Please enter your email address");
      return;
    }
    forgotMutation.mutate({ email });
  };

  const copyResetLink = () => {
    if (resetToken) {
      const link = `${window.location.origin}/reset-password/${resetToken}`;
      navigator.clipboard.writeText(link);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const isLoading = forgotMutation.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%)" }}
    >
      <div className="absolute top-0 left-0 w-full h-1" style={{ background: "#14532D" }} />
      <div
        className="absolute top-32 right-32 w-48 h-48 rounded-full opacity-10"
        style={{ background: "#C2410C", filter: "blur(60px)" }}
      />

      <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)" }}
        >
          <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: sent
                    ? "linear-gradient(135deg, #16a34a 0%, #15803d 100%)"
                    : "linear-gradient(135deg, #C2410C 0%, #ea580c 100%)",
                  boxShadow: sent
                    ? "0 4px 16px rgba(22, 163, 74, 0.3)"
                    : "0 4px 16px rgba(194, 65, 12, 0.3)",
                }}
              >
                {sent ? (
                  <CheckCircle2 className="w-7 h-7 text-white" />
                ) : (
                  <Mail className="w-7 h-7 text-white" />
                )}
              </div>
            </div>
            <CardTitle
              className="text-2xl"
              style={{ fontFamily: "'Playfair Display', serif", color: "#292524" }}
            >
              {sent ? "Check Your Email" : "Forgot Password?"}
            </CardTitle>
            <CardDescription
              className="text-sm mt-1"
              style={{ fontFamily: "'Source Sans 3', sans-serif", color: "#78716C" }}
            >
              {sent
                ? "We've sent password reset instructions to your email"
                : "Enter your email and we'll send you a reset link"}
            </CardDescription>
          </CardHeader>

          <CardContent className="pt-4">
            {sent ? (
              <div className="space-y-4">
                <div
                  className="p-4 rounded-lg text-sm leading-relaxed"
                  style={{
                    background: "#F0FDF4",
                    color: "#166534",
                    border: "1px solid #BBF7D0",
                    fontFamily: "'Source Sans 3', sans-serif",
                  }}
                >
                  <p className="font-medium mb-1">Reset instructions sent!</p>
                  <p className="text-xs" style={{ color: "#15803d" }}>
                    If an account exists for <strong>{email}</strong>, you'll receive an email with a link to reset your password. The link expires in 1 hour.
                  </p>
                </div>

                {/* Demo mode: show the reset link directly */}
                {resetToken && (
                  <div
                    className="p-4 rounded-lg text-sm"
                    style={{
                      background: "#FFFBEB",
                      border: "1px solid #FDE68A",
                      fontFamily: "'Source Sans 3', sans-serif",
                    }}
                  >
                    <p className="font-medium mb-2" style={{ color: "#92400E" }}>
                      Demo Mode — Reset Link
                    </p>
                    <p className="text-xs mb-3" style={{ color: "#a16207" }}>
                      In production, this link would be sent via email. For testing, you can use it directly:
                    </p>
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        variant="outline"
                        className="text-xs flex-1"
                        style={{ borderColor: "#FDE68A", color: "#92400E" }}
                        onClick={copyResetLink}
                      >
                        <Copy className="w-3 h-3 mr-1" />
                        {copied ? "Copied!" : "Copy Link"}
                      </Button>
                      <Link href={`/reset-password/${resetToken}`}>
                        <Button
                          size="sm"
                          className="text-xs"
                          style={{ background: "#C2410C" }}
                        >
                          <ExternalLink className="w-3 h-3 mr-1" />
                          Open Reset Page
                        </Button>
                      </Link>
                    </div>
                  </div>
                )}

                <div className="text-center pt-2">
                  <p
                    className="text-xs mb-3"
                    style={{ color: "#a8a29e", fontFamily: "'Source Sans 3', sans-serif" }}
                  >
                    Didn't receive the email? Check your spam folder or
                  </p>
                  <Button
                    variant="outline"
                    size="sm"
                    className="text-xs"
                    style={{ borderColor: "#e7e0d5", color: "#57534e" }}
                    onClick={() => {
                      setSent(false);
                      setResetToken(null);
                    }}
                  >
                    Try again
                  </Button>
                </div>
              </div>
            ) : (
              <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>

                <Button
                  type="submit"
                  className="w-full h-11 text-sm font-semibold"
                  style={{
                    background: "linear-gradient(135deg, #C2410C 0%, #ea580c 100%)",
                    fontFamily: "'Source Sans 3', sans-serif",
                    boxShadow: "0 2px 8px rgba(194, 65, 12, 0.25)",
                  }}
                  disabled={isLoading}
                >
                  {isLoading ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Sending...
                    </>
                  ) : (
                    "Send Reset Link"
                  )}
                </Button>
              </form>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
