"use client";

import { FormEvent, useEffect, useState } from "react";
import { ArrowRight, CheckCircle2, ImagePlus, Loader2, LogOut, Smartphone } from "lucide-react";
import { apiBaseUrl, apiHeaders, apiPath } from "@/lib/api-url";
import { uploadProfileImage } from "@/lib/storage";

type Step = "mobile" | "otp" | "register" | "done";
type Status = "idle" | "loading" | "error";

type AuthUser = {
  id: number;
  name: string;
  email: string | null;
  mobile: string;
  profileImage: string | null;
};

type VerifyOtpResponse = {
  success?: boolean;
  authToken?: string;
  exists?: boolean;
  requiresRegistration?: boolean;
  user?: AuthUser;
  error?: string;
};

type RequestOtpResponse = {
  success: boolean;
  message: string;
};

type RegisterResponse = {
  success: boolean;
  message: string;
  user: AuthUser;
};

const tokenStorageKey = "userAuthToken";

async function apiRequest<T>(path: string, init: RequestInit = {}) {
  const response = await fetch(`${apiBaseUrl}${apiPath(path)}`, {
    ...init,
    headers: apiHeaders({
      "Content-Type": "application/json",
      ...(init.headers ?? {}),
    }),
  });
  const data = (await response.json()) as T & { error?: string };

  if (!response.ok) {
    throw new Error(data.error ?? "Request failed");
  }

  return data;
}

export default function UserLoginPage() {
  const [step, setStep] = useState<Step>("mobile");
  const [status, setStatus] = useState<Status>("idle");
  const [message, setMessage] = useState("");
  const [mobile, setMobile] = useState("");
  const [otp, setOtp] = useState("");
  const [token, setToken] = useState("");
  const [user, setUser] = useState<AuthUser | null>(null);
  const [profileImagePreview, setProfileImagePreview] = useState("");

  useEffect(() => {
    const savedToken = window.localStorage.getItem(tokenStorageKey);

    if (!savedToken) {
      return;
    }

    apiRequest<{ user: AuthUser }>("/api/auth/me", {
      headers: {
        Authorization: `Bearer ${savedToken}`,
      },
    })
      .then((data) => {
        setToken(savedToken);
        setUser(data.user);
        setStep(data.user.email && data.user.name !== "User" ? "done" : "register");
      })
      .catch(() => {
        window.localStorage.removeItem(tokenStorageKey);
      });
  }, []);

  async function requestOtp(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setStatus("loading");
    setMessage("");

    try {
      await apiRequest<RequestOtpResponse>("/api/auth/request-otp", {
        method: "POST",
        body: JSON.stringify({ mobile }),
      });

      setStep("otp");
      setMessage("OTP sent successfully.");
      setStatus("idle");
    } catch (error) {
      setStatus("error");
      setMessage(error instanceof Error ? error.message : "Could not request OTP");
    }
  }

  async function verifyOtp(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setStatus("loading");
    setMessage("");

    try {
      const data = await apiRequest<VerifyOtpResponse>("/api/auth/verify-otp", {
        method: "POST",
        body: JSON.stringify({
          mobile,
          otp,
          deviceName: navigator.userAgent.includes("Mobile") ? "Mobile browser" : "Web browser",
        }),
      });

      if (!data.authToken || !data.user) {
        throw new Error("Login failed");
      }

      window.localStorage.setItem(tokenStorageKey, data.authToken);
      setToken(data.authToken);
      setUser(data.user);
      setStep(data.requiresRegistration ? "register" : "done");
      setMessage(data.exists ? "Welcome back." : "Mobile verified. Complete your profile.");
      setStatus("idle");
    } catch (error) {
      setStatus("error");
      setMessage(error instanceof Error ? error.message : "Could not verify OTP");
    }
  }

  async function completeRegistration(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setStatus("loading");
    setMessage("");

    const formData = new FormData(e.currentTarget);
    const image = formData.get("profileImage");

    try {
      let profileImage: string | undefined;

      if (image instanceof File && image.size > 0) {
        profileImage = await uploadProfileImage(image, user ? String(user.id) : mobile);
      }

      const data = await apiRequest<RegisterResponse>("/api/auth/register", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          name: String(formData.get("name") ?? ""),
          email: String(formData.get("email") ?? ""),
          profileImage,
        }),
      });

      setUser(data.user);
      setStep("done");
      setStatus("idle");
      setMessage("Registration completed.");
    } catch (error) {
      setStatus("error");
      setMessage(error instanceof Error ? error.message : "Could not complete registration");
    }
  }

  async function logout() {
    if (token) {
      await fetch(`${apiBaseUrl}${apiPath("/api/auth/logout")}`, {
        method: "POST",
        headers: apiHeaders({
          Authorization: `Bearer ${token}`,
        }),
      }).catch(() => undefined);
    }

    window.localStorage.removeItem(tokenStorageKey);
    setToken("");
    setUser(null);
    setOtp("");
    setStep("mobile");
    setMessage("");
  }

  return (
    <main className="min-h-screen bg-zinc-50 flex items-center justify-center p-4 sm:p-6 lg:p-8 font-['Space_Grotesk'] text-zinc-950">
      <section className="w-full max-w-4xl min-h-[600px] grid overflow-hidden rounded-2xl border border-zinc-200 bg-white shadow-[0_32px_64px_-16px_rgba(15,23,42,0.08)] lg:grid-cols-[0.86fr_1.14fr]">
        
        {/* Sidebar Info Section */}
        <aside className="hidden bg-zinc-950 p-10 text-white lg:flex lg:flex-col lg:justify-between relative overflow-hidden">
          <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.03),transparent)] pointer-events-none" />
          <div className="relative z-10">
            <div className="grid h-12 w-12 place-items-center rounded-xl bg-white text-zinc-950 shadow-sm">
              <Smartphone className="h-5 w-5" />
            </div>
            <h1 className="mt-8 text-3xl font-black tracking-tight">Ride N Revive</h1>
            <p className="mt-4 text-sm font-semibold leading-relaxed text-zinc-400">
              Mobile OTP login for customer accounts and secure device sessions.
            </p>
          </div>
          <div className="relative z-10 flex items-center gap-2">
            <span className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse" />
            <p className="text-xs font-bold uppercase tracking-[0.2em] text-zinc-500">
              Static OTP enabled
            </p>
          </div>
        </aside>

        {/* Dynamic Multi-step Form Container */}
        <div className="flex flex-col justify-center p-8 sm:p-12 lg:p-16 relative">
          <div className="w-full max-w-sm mx-auto space-y-6">
            
            {/* Context Header Tag */}
            <div className="inline-flex items-center gap-2 rounded-full border border-zinc-200 bg-zinc-50/50 px-3 py-1 text-xs font-black uppercase tracking-[0.16em] text-primary">
              <span className="h-1.5 w-1.5 rounded-full bg-primary" />
              User login
            </div>

            {/* Step 1: Mobile Number Submission */}
            {step === "mobile" ? (
              <form onSubmit={requestOtp} className="space-y-5 animate-in fade-in slide-in-from-bottom-2 duration-300">
                <div className="space-y-1">
                  <h2 className="text-3xl font-black tracking-tight">Enter mobile number</h2>
                  <p className="text-sm font-semibold text-zinc-500">We'll send a one-time verification code.</p>
                </div>
                <div className="space-y-2">
                  <label className="block text-xs font-black uppercase tracking-[0.14em] text-zinc-500">
                    Mobile Number
                  </label>
                  <div className="relative">
                    <input
                      required
                      type="tel"
                      value={mobile}
                      onChange={(e) => setMobile(e.target.value)}
                      placeholder="9876543210"
                      className="h-12 w-full rounded-xl border border-zinc-200 bg-zinc-50/30 px-4 text-base font-bold outline-none transition duration-200 placeholder:text-zinc-400 focus:border-primary focus:bg-white focus:ring-4 focus:ring-primary/10"
                    />
                  </div>
                </div>
                <SubmitButton loading={status === "loading"} label="Request OTP" />
              </form>
            ) : null}

            {/* Step 2: OTP Verification */}
            {step === "otp" ? (
              <form onSubmit={verifyOtp} className="space-y-5 animate-in fade-in slide-in-from-bottom-2 duration-300">
                <div className="space-y-1">
                  <h2 className="text-3xl font-black tracking-tight">Verify OTP</h2>
                  <p className="text-sm font-semibold text-zinc-500">Sent to <span className="text-zinc-950 font-bold">{mobile}</span></p>
                </div>
                <div className="space-y-2">
                  <label className="block text-xs font-black uppercase tracking-[0.14em] text-zinc-500">
                    Verification Code
                  </label>
                  <input
                    required
                    value={otp}
                    onChange={(e) => setOtp(e.target.value)}
                    maxLength={5}
                    placeholder="12345"
                    className="h-14 w-full rounded-xl border border-zinc-200 bg-zinc-50/30 px-4 text-center text-2xl font-black tracking-[0.3em] outline-none transition duration-200 placeholder:text-zinc-300 placeholder:tracking-normal focus:border-primary focus:bg-white focus:ring-4 focus:ring-primary/10"
                  />
                </div>
                <div className="pt-1 space-y-3">
                  <SubmitButton loading={status === "loading"} label="Verify OTP" />
                  <button
                    type="button"
                    onClick={() => setStep("mobile")}
                    className="flex w-full justify-center text-sm font-bold text-zinc-500 transition duration-150 hover:text-zinc-950"
                  >
                    Change mobile number
                  </button>
                </div>
              </form>
            ) : null}

            {/* Step 3: Registration Profile Completion */}
            {step === "register" ? (
              <form onSubmit={completeRegistration} className="space-y-5 animate-in fade-in slide-in-from-bottom-2 duration-300">
                <div className="space-y-1">
                  <h2 className="text-3xl font-black tracking-tight">Complete registration</h2>
                  <p className="text-sm font-semibold text-zinc-500">Set up your profile details for {mobile || user?.mobile}</p>
                </div>
                <div className="space-y-4">
                  <Field
                    label="Full Name"
                    name="name"
                    defaultValue={user?.name === "User" ? "" : user?.name}
                  />
                  <Field label="Email Address" name="email" type="email" defaultValue={user?.email ?? ""} />
                  <div className="space-y-2">
                    <label className="block text-xs font-black uppercase tracking-[0.14em] text-zinc-500">
                      Profile Image
                    </label>
                    <label className="flex h-24 cursor-pointer items-center gap-4 rounded-xl border-2 border-dashed border-zinc-200 bg-zinc-50/30 px-4 transition duration-200 hover:border-primary hover:bg-white group">
                      <span className="grid h-12 w-12 shrink-0 place-items-center rounded-xl bg-zinc-100 text-zinc-600 transition group-hover:bg-primary/10 group-hover:text-primary">
                        <ImagePlus className="h-5 w-5" />
                      </span>
                      <div className="min-w-0 flex-1">
                        <span className="block text-sm font-bold text-zinc-700 truncate">
                          {profileImagePreview || "Choose an image"}
                        </span>
                        <span className="block text-xs font-semibold text-zinc-400 mt-0.5">
                          PNG, JPG up to 5MB
                        </span>
                      </div>
                      <input
                        name="profileImage"
                        type="file"
                        accept="image/*"
                        className="sr-only"
                        onChange={(e) => setProfileImagePreview(e.target.files?.[0]?.name ?? "")}
                      />
                    </label>
                  </div>
                </div>
                <div className="pt-2">
                  <SubmitButton loading={status === "loading"} label="Save profile" />
                </div>
              </form>
            ) : null}

            {/* Step 4: Access Allowed / Signed In Overview */}
            {step === "done" ? (
              <div className="space-y-6 animate-in fade-in duration-300">
                <div className="flex items-center gap-4">
                  <div className="grid h-12 w-12 place-items-center rounded-xl bg-emerald-50 text-emerald-600 border border-emerald-100">
                    <CheckCircle2 className="h-6 w-6" />
                  </div>
                  <div>
                    <h2 className="text-2xl font-black tracking-tight">Successfully Logged In</h2>
                    <p className="text-sm font-semibold text-zinc-500">Welcome to your dashboard session.</p>
                  </div>
                </div>
                <div className="divide-y divide-zinc-100 rounded-xl border border-zinc-200 bg-zinc-50/50 px-4 py-1 text-sm font-semibold text-zinc-700">
                  <div className="flex justify-between py-3">
                    <span className="text-zinc-400">Name</span>
                    <span className="font-bold text-zinc-950">{user?.name}</span>
                  </div>
                  <div className="flex justify-between py-3">
                    <span className="text-zinc-400">Email</span>
                    <span className="font-bold text-zinc-950">{user?.email || "—"}</span>
                  </div>
                  <div className="flex justify-between py-3">
                    <span className="text-zinc-400">Mobile</span>
                    <span className="font-bold text-zinc-950">{user?.mobile}</span>
                  </div>
                </div>
                <button
                  onClick={logout}
                  className="inline-flex h-12 w-full items-center justify-center gap-2 rounded-xl border border-zinc-200 bg-white px-4 text-sm font-black text-zinc-700 shadow-sm transition duration-150 hover:bg-zinc-50 hover:text-zinc-950 focus:outline-none focus:ring-4 focus:ring-zinc-100"
                >
                  <LogOut className="h-4 w-4" />
                  Logout Account
                </button>
              </div>
            ) : null}

            {/* Operation Banner Feedback messages */}
            {message ? (
              <div
                className={`rounded-xl border p-4 text-sm font-semibold shadow-sm animate-in fade-in duration-200 ${
                  status === "error"
                    ? "border-red-100 bg-red-50/60 text-red-700"
                    : "border-emerald-100 bg-emerald-50/60 text-emerald-800"
                }`}
              >
                {message}
              </div>
            ) : null}
          </div>
        </div>
      </section>
    </main>
  );
}

function SubmitButton({ loading, label }: { loading: boolean; label: string }) {
  return (
    <button
      disabled={loading}
      className="inline-flex h-12 w-full items-center justify-center gap-2 rounded-xl bg-primary px-4 text-sm font-black text-primary-foreground shadow-sm transition duration-150 hover:opacity-95 focus:outline-none focus:ring-4 focus:ring-primary/20 disabled:opacity-60 disabled:cursor-not-allowed"
    >
      {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <ArrowRight className="h-4 w-4" />}
      {label}
    </button>
  );
}

function Field({
  label,
  name,
  type = "text",
  defaultValue,
}: {
  label: string;
  name: string;
  type?: string;
  defaultValue?: string;
}) {
  return (
    <div className="space-y-2">
      <label className="block text-xs font-black uppercase tracking-[0.14em] text-zinc-500">
        {label}
      </label>
      <input
        required
        name={name}
        type={type}
        defaultValue={defaultValue}
        className="h-12 w-full rounded-xl border border-zinc-200 bg-zinc-50/30 px-4 text-sm font-bold outline-none transition duration-200 focus:border-primary focus:bg-white focus:ring-4 focus:ring-primary/10"
      />
    </div>
  );
}