"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
import { apiFetch, ApiError } from "@/lib/apiClient";

type Tab = "profile" | "security";

const NIGERIAN_STATES = [
  "Abia","Adamawa","Akwa Ibom","Anambra","Bauchi","Bayelsa","Benue","Borno",
  "Cross River","Delta","Ebonyi","Edo","Ekiti","Enugu","Gombe","Imo","Jigawa",
  "Kaduna","Kano","Katsina","Kebbi","Kogi","Kwara","Lagos","Nasarawa","Niger",
  "Ogun","Ondo","Osun","Oyo","Plateau","Rivers","Sokoto","Taraba","Yobe",
  "Zamfara","FCT",
];

function StrengthBar({ password }: { password: string }) {
  const score = [/.{8,}/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((r) => r.test(password)).length;
  const labels = ["", "Weak", "Fair", "Good", "Strong"];
  const colors = ["", "#ba1a1a", "#FED665", "#4f57a6", "#755b00"];
  return (
    <div className="mt-2">
      <div className="flex gap-1">
        {[1, 2, 3, 4].map((i) => (
          <div key={i} className="flex-1 h-1 rounded-full transition-all"
            style={{ background: i <= score ? colors[score] : "#e2e2e2" }} />
        ))}
      </div>
      {password && <p className="text-xs mt-1" style={{ color: colors[score] }}>{labels[score]}</p>}
    </div>
  );
}

export default function ProfilePage() {
  const router = useRouter();
  const { user, isLoading, isAuthenticated, refreshUser, logout } = useAuth();
  const [tab, setTab] = useState<Tab>("profile");

  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [dob, setDob] = useState("");
  const [stateOfOrigin, setStateOfOrigin] = useState("");
  const [gender, setGender] = useState("");
  const [saving, setSaving] = useState(false);
  const [profileMsg, setProfileMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);

  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [changingPw, setChangingPw] = useState(false);
  const [pwMsg, setPwMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);

  const [loggingOut, setLoggingOut] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);
  const [uploadErr, setUploadErr] = useState<string | null>(null);

  useEffect(() => {
    if (!isLoading && !isAuthenticated) router.replace("/login");
  }, [isLoading, isAuthenticated, router]);

  useEffect(() => {
    if (user) {
      setFullName(user.fullName ?? "");
      setPhone(user.phone ?? "");
      setDob(user.dob ?? "");
      setStateOfOrigin(user.stateOfOrigin ?? "");
      setGender(user.gender ?? "");
      setAvatarUrl(user.photoUrl ?? null);
    }
  }, [user]);

  async function handleAvatarChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    setUploadErr(null);
    try {
      const form = new FormData();
      form.append("file", file);
      const res = await fetch("/api/upload/avatar", { method: "POST", body: form });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error ?? "Upload failed");
      setAvatarUrl(data.url);
      await refreshUser();
    } catch (err: any) {
      setUploadErr(err.message ?? "Upload failed");
    }
    setUploading(false);
    e.target.value = "";
  }

  async function saveProfile(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setProfileMsg(null);
    try {
      await apiFetch("/users/me", {
        method: "PATCH",
        body: JSON.stringify({ fullName, phone, dob: dob || undefined, stateOfOrigin: stateOfOrigin || undefined, gender: gender || undefined }),
      });
      await refreshUser();
      setProfileMsg({ type: "ok", text: "Profile updated successfully." });
    } catch (err) {
      setProfileMsg({ type: "err", text: err instanceof ApiError ? err.message : "Failed to save profile." });
    }
    setSaving(false);
  }

  async function changePassword(e: React.FormEvent) {
    e.preventDefault();
    if (newPassword !== confirmPassword) { setPwMsg({ type: "err", text: "Passwords do not match." }); return; }
    if (newPassword.length < 8) { setPwMsg({ type: "err", text: "Password must be at least 8 characters." }); return; }
    setChangingPw(true);
    setPwMsg(null);
    try {
      await apiFetch("/auth/change-password", {
        method: "POST",
        body: JSON.stringify({ currentPassword, newPassword }),
      });
      setPwMsg({ type: "ok", text: "Password changed. You'll be logged out." });
      setCurrentPassword(""); setNewPassword(""); setConfirmPassword("");
      setTimeout(async () => { await logout(); router.replace("/login"); }, 2000);
    } catch (err) {
      setPwMsg({ type: "err", text: err instanceof ApiError ? err.message : "Could not change password." });
    }
    setChangingPw(false);
  }

  async function handleLogout() {
    setLoggingOut(true);
    await logout();
    router.replace("/login");
  }

  if (isLoading || !user) {
    return (
      <div className="min-h-screen bg-[#f9f9f9] flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-[#040b61] border-t-transparent animate-spin" />
      </div>
    );
  }

  const initials = user.fullName.split(" ").map((n: string) => n[0]).join("").slice(0, 2).toUpperCase();

  const inputCls = "w-full pl-12 pr-4 py-3.5 bg-[#f3f3f3] border border-[#c6c5d3] rounded-xl text-[#1a1c1c] text-sm focus:outline-none focus:border-[#FED665] focus:ring-2 focus:ring-[#FED665]/20 transition-all";

  return (
    <div className="bg-[#f9f9f9] min-h-screen text-[#1a1c1c]">
      {/* Profile Header Card */}
      <header className="relative overflow-hidden text-white pb-6"
        style={{ background: "linear-gradient(135deg, #0D1145 0%, #1C2472 60%, #2D3A8C 100%)" }}>
        <div className="absolute -top-16 -right-16 w-48 h-48 bg-[#FED665]/10 rounded-full blur-[60px]" />

        <div className="flex items-center px-5 h-16 relative z-10">
          <button onClick={() => router.back()} className="text-white/60 hover:text-white p-2 -ml-2">
            <span className="material-symbols-outlined">arrow_back</span>
          </button>
          <h1 className="font-bold text-[18px] ml-2" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            My Profile
          </h1>
        </div>

        <div className="flex items-center gap-4 px-5 relative z-10">
          <div className="relative">
            <label className="cursor-pointer block" title="Change profile photo">
              <input
                type="file"
                accept="image/jpeg,image/png,image/webp"
                className="sr-only"
                onChange={handleAvatarChange}
                disabled={uploading}
              />
              {avatarUrl ? (
                /* eslint-disable-next-line @next/next/no-img-element */
                <img
                  src={avatarUrl}
                  alt="Profile"
                  className="w-20 h-20 rounded-full object-cover border-2 border-[#FED665]/60"
                />
              ) : (
                <div className="w-20 h-20 rounded-full flex items-center justify-center border-2 border-[#FED665]/60"
                  style={{ background: "linear-gradient(135deg, #755b00, #FED665)" }}>
                  <span className="text-white font-black text-2xl" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                    {initials}
                  </span>
                </div>
              )}
              <div className="absolute bottom-0 right-0 w-7 h-7 rounded-full flex items-center justify-center border-2 border-white"
                style={{ background: uploading ? "#c6c5d3" : "#FED665" }}>
                {uploading
                  ? <div className="w-3 h-3 rounded-full border-2 border-white border-t-transparent animate-spin" />
                  : <span className="material-symbols-outlined text-[#040b61]" style={{ fontSize: "14px", fontVariationSettings: "'FILL' 1" }}>photo_camera</span>
                }
              </div>
            </label>
          </div>

          <div>
            <p className="text-white font-bold text-xl" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              {user.fullName}
            </p>
            <p className="text-white/50 text-sm">{user.email}</p>
            <span className="inline-flex items-center gap-1 mt-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-[#FED665]/15 border border-[#FED665]/30 text-[#FED665]">
              <span className="material-symbols-outlined" style={{ fontSize: "12px", fontVariationSettings: "'FILL' 1" }}>verified</span>
              Verified Pilgrim
            </span>
            {uploadErr && (
              <p className="text-red-300 text-[10px] mt-1">{uploadErr}</p>
            )}
          </div>
        </div>
      </header>

      <div className="px-5 pb-32 max-w-[430px] mx-auto">
        {/* Tabs */}
        <div className="flex border-b border-[#e2e2e2] mt-6 mb-6">
          {(["profile", "security"] as Tab[]).map((t) => (
            <button key={t} onClick={() => setTab(t)}
              className="flex-1 pb-3 text-sm font-semibold capitalize relative transition-colors"
              style={{ color: tab === t ? "#1a1c1c" : "#464651" }}>
              {t === "profile" ? "Personal Info" : "Security"}
              {tab === t && <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-[#755b00]" />}
            </button>
          ))}
        </div>

        {/* ── Profile Tab ── */}
        {tab === "profile" && (
          <form onSubmit={saveProfile} className="space-y-4">
            {/* Account Details */}
            <div className="bg-white rounded-3xl p-5 space-y-4 shadow-sm">
              <div className="flex items-center gap-2 mb-2">
                <span className="material-symbols-outlined text-[#040b61]" style={{ fontVariationSettings: "'FILL' 1" }}>manage_accounts</span>
                <h2 className="font-bold text-[#1a1c1c] text-sm" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                  Account Details
                </h2>
              </div>

              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#767682]">person</span>
                <input type="text" value={fullName} onChange={(e) => setFullName(e.target.value)} required
                  placeholder="Full Name" className={inputCls} />
              </div>

              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#767682]">mail</span>
                <input type="email" value={user.email} disabled
                  className="w-full pl-12 pr-4 py-3.5 bg-[#e8e8e8] border border-[#c6c5d3] rounded-xl text-[#767682] text-sm cursor-not-allowed" />
                <p className="text-[10px] text-[#767682] mt-1 pl-1">Email cannot be changed. Contact support if needed.</p>
              </div>

              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#767682]">call</span>
                <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} required
                  placeholder="Phone Number" className={inputCls} />
              </div>
            </div>

            {/* Travel Details */}
            <div className="bg-white rounded-3xl p-5 space-y-4 shadow-sm">
              <div className="flex items-center gap-2 mb-2">
                <span className="material-symbols-outlined text-[#040b61]" style={{ fontVariationSettings: "'FILL' 1" }}>flight_takeoff</span>
                <h2 className="font-bold text-[#1a1c1c] text-sm" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                  Travel Details
                </h2>
              </div>

              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#767682]">cake</span>
                <input type="date" value={dob} onChange={(e) => setDob(e.target.value)}
                  className={inputCls} />
              </div>

              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#767682]">wc</span>
                <select value={gender} onChange={(e) => setGender(e.target.value)} className={inputCls}>
                  <option value="">Select gender</option>
                  <option value="MALE">Male</option>
                  <option value="FEMALE">Female</option>
                </select>
              </div>

              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#767682]">location_on</span>
                <select value={stateOfOrigin} onChange={(e) => setStateOfOrigin(e.target.value)} className={inputCls}>
                  <option value="">Select state of origin</option>
                  {NIGERIAN_STATES.map((s) => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
            </div>

            {profileMsg && (
              <div className={`p-3 rounded-xl text-sm text-center ${profileMsg.type === "ok" ? "bg-green-50 text-green-700 border border-green-200" : "bg-red-50 text-red-600 border border-red-200"}`}>
                {profileMsg.text}
              </div>
            )}

            <button type="submit" disabled={saving}
              className="w-full bg-[#040b61] text-white py-4 rounded-full font-semibold text-sm flex items-center justify-center gap-2 hover:bg-[#0D1145] transition-all active:scale-95 shadow-lg disabled:opacity-60">
              {saving
                ? <><div className="w-4 h-4 rounded-full border-2 border-white border-t-transparent animate-spin" /> Saving...</>
                : <><span className="material-symbols-outlined text-[#FED665] text-[20px]">save</span> Save Changes</>}
            </button>
          </form>
        )}

        {/* ── Security Tab ── */}
        {tab === "security" && (
          <div className="space-y-4">
            {/* Change Password */}
            <form onSubmit={changePassword} className="bg-white rounded-3xl p-5 space-y-4 shadow-sm">
              <div className="flex items-center gap-2 mb-2">
                <span className="material-symbols-outlined text-[#040b61]" style={{ fontVariationSettings: "'FILL' 1" }}>lock</span>
                <h2 className="font-bold text-[#1a1c1c] text-sm" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
                  Change Password
                </h2>
              </div>

              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#767682]">lock</span>
                <input type={showCurrent ? "text" : "password"} value={currentPassword}
                  onChange={(e) => setCurrentPassword(e.target.value)} required placeholder="Current Password"
                  className={inputCls + " pr-12"} />
                <button type="button" onClick={() => setShowCurrent((v) => !v)}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-[#767682] hover:text-[#1a1c1c]">
                  <span className="material-symbols-outlined">{showCurrent ? "visibility_off" : "visibility"}</span>
                </button>
              </div>

              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#767682]">lock_reset</span>
                <input type={showNew ? "text" : "password"} value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)} required minLength={8} placeholder="New Password"
                  className={inputCls + " pr-12"} />
                <button type="button" onClick={() => setShowNew((v) => !v)}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-[#767682] hover:text-[#1a1c1c]">
                  <span className="material-symbols-outlined">{showNew ? "visibility_off" : "visibility"}</span>
                </button>
                <StrengthBar password={newPassword} />
              </div>

              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#767682]">lock</span>
                <input type="password" value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)} required placeholder="Confirm New Password"
                  className={inputCls} />
                {confirmPassword && newPassword !== confirmPassword && (
                  <p className="text-xs text-[#ba1a1a] mt-1 pl-1">Passwords do not match</p>
                )}
              </div>

              {pwMsg && (
                <div className={`p-3 rounded-xl text-sm text-center ${pwMsg.type === "ok" ? "bg-green-50 text-green-700 border border-green-200" : "bg-red-50 text-red-600 border border-red-200"}`}>
                  {pwMsg.text}
                </div>
              )}

              <button type="submit" disabled={changingPw}
                className="w-full bg-[#040b61] text-white py-4 rounded-full font-semibold text-sm flex items-center justify-center gap-2 hover:bg-[#0D1145] transition-all active:scale-95 shadow-lg disabled:opacity-60">
                {changingPw
                  ? <><div className="w-4 h-4 rounded-full border-2 border-white border-t-transparent animate-spin" /> Updating...</>
                  : "Update Password"}
              </button>
            </form>

            {/* Withdrawal Request */}
            <div className="bg-white rounded-3xl p-5 shadow-sm border border-[#c6c5d3]/30">
              <div className="flex items-center gap-2 mb-3">
                <span className="material-symbols-outlined text-[#040b61]" style={{ fontVariationSettings: "'FILL' 1" }}>account_balance</span>
                <h2 className="font-bold text-[#1a1c1c] text-sm">Savings Withdrawal</h2>
              </div>
              <p className="text-xs text-[#767682] mb-3 leading-relaxed">
                Need to withdraw your savings? A 10% processing fee applies. Processing takes 3–5 business days after admin approval.
              </p>
              <button
                onClick={() => router.push("/withdrawal")}
                className="w-full py-3.5 rounded-xl border-2 border-[#040b61] text-[#040b61] font-semibold text-sm flex items-center justify-center gap-2 hover:bg-[#040b61]/5 transition-colors"
              >
                <span className="material-symbols-outlined text-[20px]">request_quote</span>
                Request Withdrawal
              </button>
            </div>

            {/* Danger Zone */}
            <div className="bg-white rounded-3xl p-5 space-y-3 shadow-sm border border-[#ffdad6]">
              <div className="flex items-center gap-2 mb-1">
                <span className="material-symbols-outlined text-[#ba1a1a]" style={{ fontVariationSettings: "'FILL' 1" }}>warning</span>
                <h2 className="font-bold text-[#ba1a1a] text-sm">Danger Zone</h2>
              </div>

              <button onClick={handleLogout} disabled={loggingOut}
                className="w-full py-3.5 rounded-xl border-2 border-[#040b61] text-[#040b61] font-semibold text-sm flex items-center justify-center gap-2 disabled:opacity-50 hover:bg-[#040b61]/5 transition-colors">
                {loggingOut
                  ? <div className="w-4 h-4 rounded-full border-2 border-[#040b61] border-t-transparent animate-spin" />
                  : <span className="material-symbols-outlined text-[20px]">logout</span>}
                Sign Out
              </button>

              {!showDeleteConfirm ? (
                <button onClick={() => setShowDeleteConfirm(true)}
                  className="w-full py-3.5 rounded-xl border-2 border-[#ffdad6] text-[#ba1a1a] font-semibold text-sm hover:bg-[#ffdad6]/30 transition-colors flex items-center justify-center gap-2">
                  <span className="material-symbols-outlined text-[20px]">delete_forever</span>
                  Delete Account
                </button>
              ) : (
                <div className="p-4 bg-[#ffdad6]/30 rounded-2xl border border-[#ffdad6] space-y-3">
                  <p className="text-[#ba1a1a] text-sm font-semibold">This cannot be undone. Are you sure?</p>
                  <p className="text-[#93000a] text-xs">All your savings data and bookings will be permanently removed. Contact support if you have a pending balance.</p>
                  <div className="flex gap-2">
                    <button onClick={() => setShowDeleteConfirm(false)}
                      className="flex-1 py-2 rounded-xl bg-white border border-[#c6c5d3] text-[#464651] text-sm font-semibold hover:bg-[#f3f3f3]">
                      Cancel
                    </button>
                    <a href="mailto:travels@al-bakkah.com?subject=Account%20Deletion%20Request"
                      className="flex-1 py-2 rounded-xl bg-[#ba1a1a] text-white text-sm font-semibold text-center hover:bg-[#93000a]">
                      Contact Support
                    </a>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
