"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PhoneInput } from "@/components/ui/phone-input";
import { usePublicSession } from "@/components/shop/public-session-context";
import { useAuthModal } from "@/components/shop/auth-modal-context";
import DataService from "@/config/axios";
import { getApiErrorMessage } from "@/lib/api-error";
import { looksLikeEmail } from "@/lib/auth-identity";
import { toast } from "sonner";

const SYNTHETIC_EMAIL_DOMAIN = "@users.nizamify.local";

function isSyntheticEmail(email?: string | null) {
  return Boolean(email && email.toLowerCase().endsWith(SYNTHETIC_EMAIL_DOMAIN));
}

/** Hide internal phone-placeholder emails in the form. */
function displayEmail(email?: string | null) {
  if (!email || isSyntheticEmail(email)) return "";
  return email;
}

function ProfileBackButton() {
  const router = useRouter();

  const goBack = () => {
    if (typeof window !== "undefined" && window.history.length > 1) {
      router.back();
      return;
    }
    router.push("/account");
  };

  return (
    <div className="mb-4 flex items-center gap-3">
      <Button
        type="button"
        variant="ghost"
        size="sm"
        className="-ml-2 h-9 gap-1.5 px-2 text-slate-700"
        onClick={goBack}
        aria-label="Go back"
      >
        <ArrowLeft className="size-4" />
        Back
      </Button>
      <Link
        href="/account"
        className="text-sm text-gray-500 underline-offset-2 hover:text-slate-900 hover:underline"
      >
        My account
      </Link>
    </div>
  );
}

export default function AccountProfilePage() {
  const { isAuthenticated, loading, user, refresh } = usePublicSession();
  const { openAuthModal } = useAuthModal();
  const [busy, setBusy] = useState(false);
  const [form, setForm] = useState({
    firstName: "",
    lastName: "",
    phone: "",
    email: "",
  });

  useEffect(() => {
    if (!user) return;
    setForm({
      firstName: user.firstName || "",
      lastName: user.lastName || "",
      phone: user.phone || "",
      email: displayEmail(user.email),
    });
  }, [user]);

  const save = async (e: React.FormEvent) => {
    e.preventDefault();
    const email = form.email.trim();
    const phone = form.phone.trim();

    if (email && !looksLikeEmail(email)) {
      toast.error("Enter a valid email address");
      return;
    }
    if (!email && !phone) {
      toast.error("Add an email or phone number");
      return;
    }

    setBusy(true);
    try {
      await DataService.patch("/user/me", {
        firstName: form.firstName.trim(),
        lastName: form.lastName.trim(),
        phone,
        ...(email ? { email } : {}),
      });
      toast.success("Profile updated");
      await refresh();
    } catch (err: unknown) {
      toast.error(getApiErrorMessage(err, "Could not update profile"));
    } finally {
      setBusy(false);
    }
  };

  if (loading) return <p className="text-gray-500">Loading…</p>;

  if (!isAuthenticated) {
    return (
      <div>
        <ProfileBackButton />
        <h1 className="text-2xl font-bold text-slate-900">Profile</h1>
        <p className="mt-4 text-gray-600">Sign in to edit your profile.</p>
        <Button className="mt-4" type="button" onClick={() => openAuthModal("login")}>
          Log in
        </Button>
      </div>
    );
  }

  return (
    <div>
      <ProfileBackButton />
      <h1 className="text-2xl font-bold text-slate-900">Profile</h1>
      <form onSubmit={save} className="mt-6 max-w-md space-y-4 rounded-lg border bg-white p-4">
        <div className="grid gap-2">
          <Label htmlFor="firstName">First name</Label>
          <Input
            id="firstName"
            value={form.firstName}
            onChange={(e) => setForm((f) => ({ ...f, firstName: e.target.value }))}
          />
        </div>
        <div className="grid gap-2">
          <Label htmlFor="lastName">Last name</Label>
          <Input
            id="lastName"
            value={form.lastName}
            onChange={(e) => setForm((f) => ({ ...f, lastName: e.target.value }))}
          />
        </div>
        <div className="grid gap-2">
          <Label htmlFor="phone">Phone</Label>
          <PhoneInput
            id="phone"
            value={form.phone}
            onChange={(phone) => setForm((f) => ({ ...f, phone }))}
          />
        </div>
        <div className="grid gap-2">
          <Label htmlFor="email">Email</Label>
          <Input
            id="email"
            type="email"
            inputMode="email"
            autoComplete="email"
            placeholder="you@example.com"
            value={form.email}
            onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
          />
          <p className="text-xs text-gray-500">
            {isSyntheticEmail(user?.email)
              ? "Add your email to receive order updates and receipts."
              : "You can update your email anytime."}
          </p>
        </div>
        <Button type="submit" disabled={busy}>
          {busy ? "Saving…" : "Save changes"}
        </Button>
      </form>
    </div>
  );
}
