"use client";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";
import { useAuth } from "@/context/AuthContext";

type Tab = "otp" | "password" | "social" | "booking";

export function LoginPageClient() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const nextPath = searchParams.get("next") || "/profile";

  const { requestOtp, verifyOtp, loginPassword, loginGoogle, loginBookingRef } = useAuth();

  const [tab, setTab] = useState<Tab>("otp");
  const [email, setEmail] = useState("");
  const [otp, setOtp] = useState("");
  const [otpStep, setOtpStep] = useState<1 | 2>(1);
  const [password, setPassword] = useState("");
  const [bookingRef, setBookingRef] = useState("");
  const [message, setMessage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleSendOtp(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setMessage(null);
    const r = await requestOtp(email);
    setLoading(false);
    setMessage(r.message);
    if (r.ok) setOtpStep(2);
  }

  async function handleVerifyOtp(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setMessage(null);
    const r = await verifyOtp(email, otp);
    setLoading(false);
    setMessage(r.message);
    if (r.ok) router.push(nextPath);
  }

  async function handlePassword(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setMessage(null);
    const r = await loginPassword(email, password);
    setLoading(false);
    setMessage(r.message);
    if (r.ok) router.push(nextPath);
  }

  async function handleGoogle() {
    setMessage(null);
    await loginGoogle();
  }

  async function handleBookingRef(e: React.FormEvent) {
    e.preventDefault();
    setMessage(null);
    setLoading(true);
    const r = await loginBookingRef(bookingRef);
    setLoading(false);
    setMessage(r.message);
    if (r.ok) router.push(nextPath);
  }

  const tabs: { id: Tab; label: string }[] = [
    { id: "otp", label: "Email & OTP" },
    { id: "password", label: "Password" },
    { id: "social", label: "Social" },
    { id: "booking", label: "Booking ID" },
  ];

  return (
    <div className="bg-[var(--color-bg)] py-16 md:py-24">
      <div className="mx-auto max-w-lg px-4 md:px-8">
        <nav className="text-xs font-medium text-[var(--color-muted)]">
          <Link href="/" className="hover:text-[var(--color-accent)]">
            Home
          </Link>
          <span className="mx-2 opacity-50">/</span>
          <span className="text-[var(--color-text)]">Sign in</span>
        </nav>
        <h1 className="mt-4 font-heading text-3xl font-semibold text-[var(--color-text)] md:text-4xl">
          Guest access
        </h1>
        <p className="mt-3 text-sm leading-relaxed text-[var(--color-muted)]">
          Sign in with email (OTP or password), social accounts, or your reservation reference to
          order room service, laundry, and manage your stay profile.
        </p>

        <div className="mt-8 flex flex-wrap gap-2 rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] p-1.5 shadow-sm">
          {tabs.map((t) => (
            <button
              key={t.id}
              type="button"
              onClick={() => {
                setTab(t.id);
                setMessage(null);
              }}
              className={`flex-1 rounded-xl px-3 py-2.5 text-center text-xs font-semibold transition sm:text-sm ${
                tab === t.id
                  ? "bg-[var(--color-primary)] text-[var(--color-on-primary)] shadow"
                  : "text-[var(--color-muted)] hover:bg-[var(--color-surface-muted)]"
              }`}
            >
              {t.label}
            </button>
          ))}
        </div>

        <div className="mt-8 rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] p-6 shadow-sm md:p-8">
          {tab === "otp" && (
            <div>
              {otpStep === 1 ? (
                <form onSubmit={handleSendOtp} className="space-y-4">
                  <label className="block text-sm font-medium text-[var(--color-text)]">
                    Email
                    <input
                      type="email"
                      required
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      autoComplete="email"
                      className="mt-1.5 w-full rounded-xl border border-[var(--color-border)] px-4 py-3 text-sm focus:border-[var(--color-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]/20"
                      placeholder="you@example.com"
                    />
                  </label>
                  <button
                    type="submit"
                    disabled={loading}
                    className="btn-mustard w-full justify-center py-3 text-sm disabled:opacity-60"
                  >
                    {loading ? "Sending…" : "Send verification code"}
                  </button>
                </form>
              ) : (
                <form onSubmit={handleVerifyOtp} className="space-y-4">
                  <p className="text-sm text-[var(--color-muted)]">
                    Code sent to <strong className="text-[var(--color-text)]">{email}</strong>
                  </p>
                  <label className="block text-sm font-medium text-[var(--color-text)]">
                    One-time code
                    <input
                      type="text"
                      inputMode="numeric"
                      autoComplete="one-time-code"
                      required
                      value={otp}
                      onChange={(e) => setOtp(e.target.value)}
                      className="mt-1.5 w-full rounded-xl border border-[var(--color-border)] px-4 py-3 font-mono text-lg tracking-widest focus:border-[var(--color-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]/20"
                      placeholder="123456"
                      maxLength={8}
                    />
                  </label>
                  <p className="text-xs text-[var(--color-muted)]">
                    Use the code sent to your email (hotel guest OTP).
                  </p>
                  <div className="flex gap-2">
                    <button
                      type="button"
                      onClick={() => {
                        setOtpStep(1);
                        setOtp("");
                      }}
                      className="flex-1 rounded-full border border-[var(--color-border)] py-3 text-sm font-semibold"
                    >
                      Back
                    </button>
                    <button
                      type="submit"
                      disabled={loading}
                      className="btn-mustard flex-[2] justify-center py-3 text-sm disabled:opacity-60"
                    >
                      {loading ? "Verifying…" : "Verify & sign in"}
                    </button>
                  </div>
                </form>
              )}
            </div>
          )}

          {tab === "password" && (
            <form onSubmit={handlePassword} className="space-y-4">
              <label className="block text-sm font-medium text-[var(--color-text)]">
                Email
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="mt-1.5 w-full rounded-xl border border-[var(--color-border)] px-4 py-3 text-sm focus:border-[var(--color-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]/20"
                />
              </label>
              <label className="block text-sm font-medium text-[var(--color-text)]">
                Password
                <input
                  type="password"
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="mt-1.5 w-full rounded-xl border border-[var(--color-border)] px-4 py-3 text-sm focus:border-[var(--color-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]/20"
                  autoComplete="current-password"
                />
              </label>
              <p className="text-xs text-[var(--color-muted)]">
                Use your Yaltopia homes account password
              </p>
              <button
                type="submit"
                disabled={loading}
                className="btn-mustard w-full justify-center py-3 text-sm disabled:opacity-60"
              >
                {loading ? "Signing in…" : "Sign in"}
              </button>
            </form>
          )}

          {tab === "social" && (
            <div className="space-y-3">
              <button
                type="button"
                onClick={() => void handleGoogle()}
                className="flex w-full items-center justify-center gap-2 rounded-full border border-[var(--color-border)] bg-[var(--color-surface)] py-3 text-sm font-semibold transition hover:bg-[var(--color-surface-muted)]"
              >
                <span className="text-base" aria-hidden>
                  <svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4" />
                    <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" />
                    <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05" />
                    <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" />
                  </svg>
                </span>
                Login with Google
              </button>
            </div>
          )}

          {tab === "booking" && (
            <form onSubmit={handleBookingRef} className="space-y-4">
              <label className="block text-sm font-medium text-[var(--color-text)]">
                Booking / confirmation reference
                <input
                  type="text"
                  value={bookingRef}
                  onChange={(e) => setBookingRef(e.target.value)}
                  className="mt-1.5 w-full rounded-xl border border-[var(--color-border)] px-4 py-3 font-mono text-sm uppercase focus:border-[var(--color-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]/20"
                  placeholder="SHITAYE-2026-DEMO"
                />
              </label>
              <p className="text-xs text-[var(--color-muted)]">
                Enter the booking code from your confirmation email. You must have used the same
                email at booking so your account links for the full guest portal.
              </p>
              <button
                type="submit"
                disabled={loading}
                className="btn-mustard w-full justify-center py-3 text-sm disabled:opacity-60"
              >
                {loading ? "Signing in…" : "Continue with booking code"}
              </button>
            </form>
          )}

          {message ? (
            <p
              className={`mt-4 text-sm ${message.includes("not") || message.includes("Invalid") || message.includes("Incorrect") ? "text-red-700" : "text-[var(--color-primary)]"}`}
            >
              {message}
            </p>
          ) : null}
        </div>

        <p className="mt-8 text-center text-sm text-[var(--color-muted)]">
          <Link href="/guest" className="font-semibold text-[var(--color-accent)] hover:underline">
            Guest hub — room service & laundry
          </Link>
        </p>
      </div>
    </div>
  );
}
