"use client";

import { useState, useEffect } from "react";
import { User, MapPin, Smartphone, Camera, Check } from "lucide-react";
import useAuth from "@/hooks/useAuth";
import { userApi, addressApi, whatsappApi } from "@/lib/api";
import { useSnackbar } from "@/context/SnackbarContext";
import ProfileSettingsShell from "@/components/customer/ProfileSettingsShell";
import { confirmDelete } from "@/lib/sweetAlert";
import { resolveImageAlt, IMAGE_ALT_FALLBACKS } from "@/lib/imageAlt";
import LocationFields from "@/components/forms/LocationFields";
import { isValidZip, normalizePhonePk, validatePhone } from "@/lib/validators";

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8000/api/v1";
const STORAGE_BASE = API_BASE.replace(/\/api\/v1\/?$/, "");

export default function CustomerProfile({ hidePageHero = false }) {
  const { user, refresh } = useAuth();
  const { showSuccess, showError } = useSnackbar();
  const [profile, setProfile] = useState({ name: "", phone: "" });
  const [addresses, setAddresses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [phoneEditing, setPhoneEditing] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [avatarAlt, setAvatarAlt] = useState("");
  const [showAddAddress, setShowAddAddress] = useState(false);
  const [wachatEnabled, setWachatEnabled] = useState(false);
  const [waVerified, setWaVerified] = useState(false);
  const [waOtpSent, setWaOtpSent] = useState(false);
  const [waOtpPhone, setWaOtpPhone] = useState("");
  const [waOtp, setWaOtp] = useState("");
  const [waBusy, setWaBusy] = useState(false);
  const [newAddress, setNewAddress] = useState({
    type: "shipping",
    first_name: "",
    last_name: "",
    phone: "",
    address_line_1: "",
    address_line_2: "",
    city: "",
    state: "",
    country: "Pakistan",
    zip_code: "",
  });

  useEffect(() => {
    if (!user) return;
    setProfile({ name: user.name || "", phone: user.phone || "" });
    setAvatarAlt(user.avatar_alt || "");
    setWaVerified(!!user.whatsapp_verified_at);
  }, [user]);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      try {
        const [addrRes, waRes] = await Promise.all([
          addressApi.list(),
          whatsappApi.status().catch(() => null),
        ]);
        setAddresses(addrRes.addresses || []);
        if (waRes) {
          setWachatEnabled(!!waRes.wachat_enabled);
          setWaVerified(!!waRes.whatsapp_verified);
        }
      } catch {
        setAddresses([]);
      } finally {
        setLoading(false);
      }
    };
    if (user) load();
  }, [user]);

  const handleProfileSave = async (e) => {
    e.preventDefault();
    const phoneErr = validatePhone(profile.phone, { required: false });
    if (phoneErr) {
      showError?.(phoneErr);
      return;
    }
    const normalized = profile.phone?.trim() ? normalizePhonePk(profile.phone) : "";
    const previousPhone = user?.phone?.trim() ? normalizePhonePk(user.phone) : "";
    const phoneChanged = normalized && normalized !== previousPhone;
    setSubmitting(true);
    try {
      const res = await userApi.updateProfile({ ...profile, phone: normalized || profile.phone });
      await refresh();
      if (phoneChanged) {
        setPhoneEditing(false);
        setWaOtpSent(false);
        setWaOtp("");
        setWaOtpPhone("");
      } else if (waOtpPhone && normalized && normalized !== waOtpPhone) {
        setWaOtpSent(false);
        setWaOtp("");
        setWaOtpPhone("");
      }
      if (res?.user) {
        setWaVerified(!!res.user.whatsapp_verified_at);
      } else if (phoneChanged) {
        setWaVerified(false);
      }
      showSuccess?.("Profile updated.");
    } catch (err) {
      showError?.(err?.message || "Failed to update profile.");
    } finally {
      setSubmitting(false);
    }
  };

  const handleSendWaOtp = async () => {
    const phoneErr = validatePhone(profile.phone);
    if (phoneErr) {
      showError?.(phoneErr);
      return;
    }
    const phone = normalizePhonePk(profile.phone);
    setWaBusy(true);
    try {
      await userApi.updateProfile({ name: profile.name, phone });
      const res = await whatsappApi.sendOtp({ phone });
      const sentTo = res.phone || phone;
      setProfile((p) => ({ ...p, phone: sentTo }));
      setWaOtpPhone(sentTo);
      setWaOtp("");
      setWaOtpSent(true);
      showSuccess?.(res?.message || "OTP sent to WhatsApp.");
      // Refresh auth in background — do not reset OTP step
      refresh().catch(() => {});
    } catch (err) {
      setWaOtpSent(false);
      showError?.(err?.data?.message || err?.message || "Failed to send WhatsApp OTP.");
    } finally {
      setWaBusy(false);
    }
  };

  const handleVerifyWaOtp = async (e) => {
    e?.preventDefault?.();
    const code = String(waOtp || "").replace(/\D/g, "");
    if (code.length !== 6) {
      showError?.("Enter the 6-digit code from WhatsApp.");
      return;
    }
    setWaBusy(true);
    try {
      const res = await whatsappApi.verifyOtp({ otp: code });
      setWaVerified(true);
      setPhoneEditing(false);
      setWaOtpSent(false);
      setWaOtp("");
      setWaOtpPhone("");
      await refresh();
      showSuccess?.(res?.message || "WhatsApp verified.");
    } catch (err) {
      showError?.(err?.data?.message || err?.message || "Invalid or expired code.");
    } finally {
      setWaBusy(false);
    }
  };

  const handleCancelWaOtp = () => {
    setWaOtpSent(false);
    setWaOtp("");
    setWaOtpPhone("");
  };

  const handleAvatarChange = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const fd = new FormData();
    fd.append("avatar", file);
    if (avatarAlt?.trim()) fd.append("avatar_alt", avatarAlt.trim());
    try {
      const res = await userApi.uploadAvatar(fd);
      if (res.success) await refresh();
      showSuccess?.("Avatar updated.");
    } catch (err) {
      showError?.(err?.message || "Failed to upload avatar.");
    }
  };

  const handleAddAddress = async (e) => {
    e.preventDefault();
    const phoneErr = validatePhone(newAddress.phone);
    if (phoneErr) {
      showError?.(phoneErr);
      return;
    }
    if (!isValidZip(newAddress.zip_code)) {
      showError?.("Enter a valid postal code.");
      return;
    }
    setSubmitting(true);
    try {
      const phone = normalizePhonePk(newAddress.phone);
      await addressApi.create({ ...newAddress, phone });
      const res = await addressApi.list();
      setAddresses(res.addresses || []);
      setShowAddAddress(false);
      setNewAddress({ type: "shipping", first_name: "", last_name: "", phone: "", address_line_1: "", address_line_2: "", city: "", state: "", country: "Pakistan", zip_code: "" });
      showSuccess?.("Address added.");
    } catch (err) {
      showError?.(err?.data?.message || err?.message || "Failed to add address.");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDeleteAddress = async (id) => {
    const confirmed = await confirmDelete({
      title: "Remove address?",
      text: "This address will be removed from your account.",
      confirmButtonText: "Yes, remove",
    });
    if (!confirmed) return;
    try {
      await addressApi.delete(id);
      setAddresses((prev) => prev.filter((a) => a.id !== id));
      showSuccess?.("Address removed.");
    } catch (err) {
      showError?.(err?.message || "Failed to remove address.");
    }
  };

  const handleSetDefaultAddress = async (id) => {
    try {
      await addressApi.setDefault(id);
      const res = await addressApi.list();
      setAddresses(res.addresses || []);
      showSuccess?.("Default address updated.");
    } catch (err) {
      showError?.(err?.message || "Failed to set default.");
    }
  };

  const phoneLocked = waVerified && !phoneEditing;
  const avatarUrl = user?.avatar_url || (user?.avatar ? `${STORAGE_BASE}/storage/${user.avatar}` : null);

  return (
    <ProfileSettingsShell showHero={!hidePageHero}>
      {/* Profile & Avatar */}
      <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-200/80 mb-6">
        <h2 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
          <User className="w-5 h-5 text-[#1790d7]" />
          Profile
        </h2>
        <div className="flex flex-col sm:flex-row items-start gap-6">
          <div className="relative shrink-0">
            <div className="w-24 h-24 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden">
              {avatarUrl ? <img src={avatarUrl} alt={resolveImageAlt(user?.avatar_alt || avatarAlt, user?.name || IMAGE_ALT_FALLBACKS.avatar)} className="w-full h-full object-cover" /> : <User className="w-12 h-12 text-gray-400" />}
            </div>
            <label className="absolute bottom-0 right-0 w-8 h-8 bg-[#1790d7] rounded-full flex items-center justify-center cursor-pointer hover:bg-[#1277b8] transition">
              <Camera className="w-4 h-4 text-white" />
              <input type="file" accept="image/*" className="hidden" onChange={handleAvatarChange} />
            </label>
          </div>
          <form onSubmit={handleProfileSave} className="flex-1 space-y-4 w-full min-w-0">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Avatar alt text (optional)</label>
              <input
                type="text"
                value={avatarAlt}
                onChange={(e) => setAvatarAlt(e.target.value)}
                placeholder="Describe your profile photo for accessibility"
                className="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#1790d7]/20 focus:border-[#1790d7]"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Name</label>
              <input
                type="text"
                value={profile.name}
                onChange={(e) => setProfile((p) => ({ ...p, name: e.target.value }))}
                className="w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#1790d7]/20 focus:border-[#1790d7]"
              />
            </div>
            <div>
              <div className="flex flex-wrap items-center justify-between gap-2 mb-2">
                <label className="block text-sm font-medium text-gray-700">Phone</label>
                {waVerified && !phoneEditing && (
                  <button
                    type="button"
                    onClick={() => setPhoneEditing(true)}
                    className="text-sm font-medium text-[#1790d7] hover:underline"
                  >
                    Change mobile number
                  </button>
                )}
                {phoneEditing && (
                  <button
                    type="button"
                    onClick={() => {
                      setPhoneEditing(false);
                      setProfile((p) => ({ ...p, phone: user?.phone || "" }));
                    }}
                    className="text-sm text-gray-500 hover:underline"
                  >
                    Cancel
                  </button>
                )}
              </div>
              <input
                type="text"
                value={profile.phone}
                readOnly={phoneLocked}
                onChange={(e) => setProfile((p) => ({ ...p, phone: e.target.value }))}
                placeholder="03XXXXXXXXX"
                className={`w-full px-4 py-2.5 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#1790d7]/20 focus:border-[#1790d7] ${
                  phoneLocked ? "bg-gray-50 text-gray-700 cursor-not-allowed" : ""
                }`}
              />
              <p className="text-xs text-gray-500 mt-1">
                {phoneLocked
                  ? "Verified number is locked. Use Change mobile number to update."
                  : "Format: 03XXXXXXXXX (also accepts 923… / +923…)"}
              </p>
            </div>

            <button
              type="submit"
              disabled={submitting}
              className="inline-flex items-center gap-2 px-4 py-2 bg-[#1790d7] hover:bg-[#1277b8] text-white font-semibold rounded-xl disabled:opacity-60"
            >
              <Check className="w-4 h-4" /> Save
            </button>
          </form>
        </div>
      </div>

      {wachatEnabled && (
        <div className="bg-white rounded-2xl p-6 shadow-sm border border-emerald-100 mb-6">
          <h2 className="font-bold text-gray-900 mb-1 flex items-center gap-2">
            <Smartphone className="w-5 h-5 text-emerald-600" />
            WhatsApp verification
          </h2>
          <p className="text-sm text-gray-500 mb-4">
            Verify your phone to receive order and payment updates on WhatsApp.
          </p>

          <div className="flex flex-wrap items-center gap-2 mb-4">
            {waVerified ? (
              <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-semibold bg-emerald-100 text-emerald-800">
                <Check className="w-3.5 h-3.5" /> Verified
                {profile.phone ? ` · ${profile.phone}` : ""}
              </span>
            ) : (
              <span className="inline-flex px-2.5 py-1 rounded-lg text-xs font-semibold bg-amber-100 text-amber-800">
                Not verified
              </span>
            )}
          </div>

          {!waVerified && !waOtpSent && (
            <div className="rounded-xl border border-gray-200 bg-gray-50/80 p-4 space-y-3">
              <p className="text-sm text-gray-700">
                We will send a 6-digit code to{" "}
                <span className="font-semibold font-mono">{profile.phone?.trim() || "your phone number"}</span>{" "}
                on WhatsApp. Save your phone above first if you changed it.
              </p>
              <button
                type="button"
                disabled={waBusy || !profile.phone?.trim()}
                onClick={handleSendWaOtp}
                className="inline-flex items-center gap-2 px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-semibold rounded-xl disabled:opacity-60"
              >
                {waBusy ? "Sending…" : "Send OTP on WhatsApp"}
              </button>
            </div>
          )}

          {!waVerified && waOtpSent && (
            <form
              onSubmit={handleVerifyWaOtp}
              className="rounded-xl border border-emerald-200 bg-emerald-50/50 p-4 space-y-4"
            >
              <div>
                <p className="text-sm font-semibold text-gray-900">Enter verification code</p>
                <p className="text-xs text-gray-600 mt-1">
                  Code sent to <span className="font-mono font-medium">{waOtpPhone || profile.phone}</span> via WhatsApp.
                </p>
              </div>
              <div>
                <label htmlFor="wa-otp-code" className="block text-sm font-medium text-gray-700 mb-2">
                  6-digit OTP
                </label>
                <input
                  id="wa-otp-code"
                  type="text"
                  name="otp"
                  inputMode="numeric"
                  autoComplete="one-time-code"
                  autoFocus
                  maxLength={6}
                  value={waOtp}
                  onChange={(e) => setWaOtp(e.target.value.replace(/\D/g, "").slice(0, 6))}
                  placeholder="••••••"
                  className="w-full max-w-xs px-4 py-3 border border-gray-200 rounded-xl text-center text-xl tracking-[0.4em] font-semibold focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500"
                />
              </div>
              <div className="flex flex-wrap items-center gap-3">
                <button
                  type="submit"
                  disabled={waBusy || String(waOtp).replace(/\D/g, "").length !== 6}
                  className="inline-flex items-center justify-center px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-semibold rounded-xl disabled:opacity-60"
                >
                  {waBusy ? "Verifying…" : "Verify OTP"}
                </button>
                <button
                  type="button"
                  disabled={waBusy}
                  onClick={handleSendWaOtp}
                  className="text-sm font-medium text-emerald-700 hover:underline disabled:opacity-60"
                >
                  Resend code
                </button>
                <button
                  type="button"
                  disabled={waBusy}
                  onClick={handleCancelWaOtp}
                  className="text-sm text-gray-500 hover:underline disabled:opacity-60"
                >
                  Change number
                </button>
              </div>
            </form>
          )}

        </div>
      )}

      {/* Addresses */}
      <div className="bg-white rounded-2xl p-6 shadow-sm border border-gray-100 mb-6">
        <h2 className="font-bold text-gray-900 mb-4 flex items-center gap-2">
          <MapPin className="w-5 h-5 text-[#1790d7]" />
          Addresses
        </h2>
        {loading ? (
          <p className="text-gray-500">Loading...</p>
        ) : (
          <>
            <div className="space-y-3 mb-4">
              {addresses.map((a) => (
                <div key={a.id} className="p-4 bg-gray-50 rounded-xl flex justify-between items-start">
                  <div>
                    <p className="font-medium text-gray-900">{a.first_name} {a.last_name}</p>
                    <p className="text-sm text-gray-600">{a.address_line_1}, {a.city}, {a.country}</p>
                    {a.is_default && <span className="text-xs text-[#1790d7] font-medium">Default</span>}
                  </div>
                  <div className="flex gap-2">
                    {!a.is_default && <button onClick={() => handleSetDefaultAddress(a.id)} className="text-sm text-[#1790d7] hover:underline">Set default</button>}
                    <button onClick={() => handleDeleteAddress(a.id)} className="text-sm text-red-600 hover:underline">Remove</button>
                  </div>
                </div>
              ))}
            </div>
            {!showAddAddress ? (
              <button onClick={() => setShowAddAddress(true)} className="text-[#1790d7] font-semibold hover:underline">+ Add address</button>
            ) : (
              <form onSubmit={handleAddAddress} className="space-y-3 p-4 bg-gray-50 rounded-xl">
                <input type="text" placeholder="First name" value={newAddress.first_name} onChange={(e) => setNewAddress((p) => ({ ...p, first_name: e.target.value }))} required className="w-full px-4 py-2 border border-gray-200 rounded-lg" />
                <input type="text" placeholder="Last name" value={newAddress.last_name} onChange={(e) => setNewAddress((p) => ({ ...p, last_name: e.target.value }))} required className="w-full px-4 py-2 border border-gray-200 rounded-lg" />
                <input type="text" placeholder="Phone (03XXXXXXXXX)" value={newAddress.phone} onChange={(e) => setNewAddress((p) => ({ ...p, phone: e.target.value }))} required className="w-full px-4 py-2 border border-gray-200 rounded-lg" />
                <input type="text" placeholder="Address line 1" value={newAddress.address_line_1} onChange={(e) => setNewAddress((p) => ({ ...p, address_line_1: e.target.value }))} required className="w-full px-4 py-2 border border-gray-200 rounded-lg" />
                <LocationFields
                  country={newAddress.country}
                  state={newAddress.state}
                  city={newAddress.city}
                  zipCode={newAddress.zip_code}
                  showZip
                  onZipChange={(zip) => setNewAddress((p) => ({ ...p, zip_code: zip }))}
                  onChange={({ country, state, city }) =>
                    setNewAddress((p) => ({ ...p, country, state, city }))
                  }
                />
                <div className="flex gap-2">
                  <button type="submit" disabled={submitting} className="px-4 py-2 bg-[#1790d7] text-white rounded-lg font-medium">Add</button>
                  <button type="button" onClick={() => setShowAddAddress(false)} className="px-4 py-2 border border-gray-200 rounded-lg">Cancel</button>
                </div>
              </form>
            )}
          </>
        )}
      </div>
    </ProfileSettingsShell>
  );
}
