"use client";

import { useState } from "react";

type Step = "email" | "sent";

export default function LoginPage() {
  const [email, setEmail] = useState("");
  const [step, setStep] = useState<Step>("email");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function submit() {
    setLoading(true);
    setError(null);

    try {
      const res = await fetch("/api/auth/request-link", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });

      if (!res.ok) {
        throw new Error("Failed to send login link");
      }

      setStep("sent");
    } catch (e) {
      setError("Something went wrong. Try again.");
    } finally {
      setLoading(false);
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !loading && email && step === "email") {
      submit();
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-50 to-white flex flex-col">
      {/* Navigation */}
      <nav className="border-b border-slate-200 bg-white/50 backdrop-blur-sm">
        <div className="max-w-6xl mx-auto px-6 h-16 flex items-center">
          <div className="text-xl font-bold bg-gradient-to-r from-blue-600 to-blue-700 bg-clip-text text-transparent">
            S2X
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="flex-1 flex items-center justify-center px-6 py-12">
        <div className="w-full max-w-md">
          {/* Progress Bar */}
          <Progress step={step} />

          {/* Form Card */}
          <div className="mt-12 bg-white border border-slate-200 rounded-xl shadow-sm p-8">
            {step === "email" && (
              <>
                <h1 className="text-2xl font-bold text-slate-900 mb-2">
                  Welcome back
                </h1>
                <p className="text-slate-600 mb-6">
                  Sign in to your Stripe to Xero automation dashboard
                </p>

                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-2">
                      Email address
                    </label>
                    <input
                      type="email"
                      placeholder="you@company.com"
                      className="w-full px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      onKeyPress={handleKeyPress}
                      disabled={loading}
                      autoFocus
                    />
                  </div>

                  <button
                    onClick={submit}
                    disabled={loading || !email}
                    className="w-full px-4 py-3 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-semibold rounded-lg hover:shadow-lg hover:from-blue-700 hover:to-blue-800 transition disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {loading ? (
                      <span className="flex items-center justify-center gap-2">
                        <span className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></span>
                        Sending link…
                      </span>
                    ) : (
                      "Send login link"
                    )}
                  </button>

                  {error && (
                    <div className="p-3 bg-red-50 border border-red-200 rounded-lg">
                      <p className="text-sm text-red-700">{error}</p>
                    </div>
                  )}
                </div>
              </>
            )}

            {step === "sent" && (
              <>
                <div className="text-center">
                  <div className="inline-flex items-center justify-center w-12 h-12 bg-green-100 rounded-full mb-4">
                    <svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                    </svg>
                  </div>

                  <h1 className="text-2xl font-bold text-slate-900 mb-2">
                    Check your email
                  </h1>

                  <p className="text-slate-600 mb-4">
                    We've sent a login link to <strong className="text-slate-900">{email}</strong>
                  </p>

                  <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                    <p className="text-sm text-blue-800">
                      The link expires in 15 minutes. Check your spam folder if you don't see it.
                    </p>
                  </div>

                  <button
                    onClick={() => {
                      setStep("email");
                      setError(null);
                    }}
                    className="text-sm text-blue-600 hover:text-blue-700 font-medium"
                  >
                    ← Try another email
                  </button>
                </div>
              </>
            )}
          </div>

          {/* Footer */}
          <p className="text-center text-sm text-slate-500 mt-8">
            Magic link authentication is secure and passwordless
          </p>
        </div>
      </main>
    </div>
  );
}

function Progress({ step }: { step: Step }) {
  const percent = step === "email" ? 50 : 100;

  return (
    <div className="space-y-2">
      <div className="h-1 bg-slate-200 rounded-full overflow-hidden">
        <div
          className="h-1 bg-gradient-to-r from-blue-600 to-blue-700 rounded-full transition-all duration-500"
          style={{ width: `${percent}%` }}
        />
      </div>
      <p className="text-xs font-medium text-slate-600 uppercase tracking-wide">
        {step === "email" ? "Step 1 of 2 • Enter email" : "Step 2 of 2 • Check inbox"}
      </p>
    </div>
  );
}
