"use client";

import { useEffect, useState, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";
import { CheckCircle2, User, Phone, Mail, AlertCircle } from "lucide-react";
import { TopBar } from "@/components/ui/TopBar";
import { Button } from "@/components/ui/Button";
import { useAuth } from "@/lib/auth/auth-provider";
import { apiPost, ApiError } from "@/lib/api/client";
import { useTranslation } from "@/lib/i18n/LanguageProvider";

function Field({
  label,
  icon: Icon,
  ...props
}: {
  label: string;
  icon: typeof User;
} & React.InputHTMLAttributes<HTMLInputElement>) {
  return (
    <div>
      <label className="mb-2 block text-sm font-medium text-muted">{label}</label>
      <div className="flex items-center gap-3 rounded-2xl glass px-4 py-3.5">
        <Icon size={17} className="text-muted" strokeWidth={2} />
        <input
          {...props}
          className="w-full bg-transparent text-[15px] outline-none placeholder:text-muted"
        />
      </div>
    </div>
  );
}

export default function EditProfilePage() {
  return (
    <Suspense fallback={null}>
      <EditProfileContent />
    </Suspense>
  );
}

function EditProfileContent() {
  const { user, profile, refreshProfile } = useAuth();
  const { t } = useTranslation();
  const searchParams = useSearchParams();
  const emailChangeStatus = searchParams.get("emailChangeStatus");
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [hydrated, setHydrated] = useState(false);
  const [saved, setSaved] = useState(false);
  const [emailChangePending, setEmailChangePending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  // Sync form fields once real user/profile data arrives — only once, so
  // we don't clobber in-progress edits if the profile refreshes later.
  useEffect(() => {
    if (hydrated || (!user && !profile)) return;
    setName(profile?.full_name ?? "");
    setPhone(profile?.phone ?? "");
    setEmail(user?.email ?? "");
    setHydrated(true);
  }, [user, profile, hydrated]);

  async function handleSave() {
    if (!user) return;
    setError(null);
    setLoading(true);

    try {
      await apiPost("/api/auth/me", { fullName: name.trim(), phone: phone.trim() }, "PATCH");
    } catch (err) {
      setLoading(false);
      setError(err instanceof ApiError ? err.message : t("common.genericError"));
      return;
    }

    let emailChanged = false;
    if (email.trim() && email.trim() !== user.email) {
      try {
        await apiPost("/api/auth/change-email", { newEmail: email.trim() });
        emailChanged = true;
      } catch (err) {
        setLoading(false);
        setError(err instanceof ApiError ? err.message : t("common.genericError"));
        return;
      }
    }

    setLoading(false);
    await refreshProfile();
    setEmailChangePending(emailChanged);
    setSaved(true);
    setTimeout(() => setSaved(false), 2800);
  }

  return (
    <div className="relative flex flex-1 flex-col">
      <TopBar title={t("editProfilePage.title")} />

      <div className="flex flex-1 flex-col gap-6 px-4 pb-6 pt-4">
        {emailChangeStatus === "success" && (
          <div className="flex items-start gap-2 rounded-xl bg-teal/10 px-3.5 py-3 text-sm text-teal-dim dark:text-teal">
            <CheckCircle2 size={16} className="mt-0.5 shrink-0" />
            {t("editProfilePage.emailChangeConfirmed")}
          </div>
        )}
        {emailChangeStatus === "invalid" && (
          <div className="flex items-start gap-2 rounded-xl bg-danger/10 px-3.5 py-3 text-sm text-danger">
            <AlertCircle size={16} className="mt-0.5 shrink-0" />
            {t("editProfilePage.emailChangeInvalid")}
          </div>
        )}

        <div className="flex flex-col items-center gap-3">
          <div className="flex h-20 w-20 items-center justify-center rounded-3xl bg-gradient-to-br from-gold-bright to-gold-dim font-display text-2xl font-bold text-ink shadow-glow-gold">
            {name.trim() ? name.trim().slice(0, 2).toUpperCase() : "?"}
          </div>
          <button className="text-xs font-semibold text-gold-dim dark:text-gold-bright">
            {t("editProfilePage.changePhoto")}
          </button>
        </div>

        <div className="flex flex-col gap-4">
          <Field label={t("editProfilePage.fullName")} icon={User} value={name} onChange={(e) => setName(e.target.value)} />
          <Field
            label={t("editProfilePage.mobileNumber")}
            icon={Phone}
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            inputMode="numeric"
          />
          <Field
            label={t("editProfilePage.email")}
            icon={Mail}
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="you@example.com"
            type="email"
          />
          {email.trim() !== (user?.email ?? "") && email.trim() && (
            <p className="-mt-2 text-xs text-muted">
              {t("editProfilePage.emailChangeNotice")}
            </p>
          )}
        </div>

        {error && (
          <div className="flex items-start gap-2 rounded-xl bg-danger/10 px-3.5 py-3 text-sm text-danger">
            <AlertCircle size={16} className="mt-0.5 shrink-0" />
            {error}
          </div>
        )}

        <div className="mt-auto">
          <Button size="lg" fullWidth onClick={handleSave} disabled={loading}>
            {loading ? t("editProfilePage.saving") : t("editProfilePage.saveChanges")}
          </Button>
        </div>
      </div>

      <AnimatePresence>
        {saved && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 20 }}
            className="pointer-events-none absolute inset-x-4 bottom-24 flex items-center gap-2 rounded-2xl bg-teal px-4 py-3 text-sm font-semibold text-ink shadow-glow-teal"
          >
            <CheckCircle2 size={16} strokeWidth={2.5} />
            {emailChangePending ? t("editProfilePage.savedEmailPending") : t("editProfilePage.savedProfile")}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
