"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { API_BASE_URL } from "@/utils/apiHelper";
import {
  FaUser,
  FaPhone,
  FaEnvelope,
  FaMapMarkerAlt,
  FaPlus,
  FaBuilding,
  FaBox,
  FaWallet,
  FaChevronRight,
  FaPen,
  FaTrash,
  FaCheckCircle
} from "react-icons/fa";

type UserProfile = {
  user_id: string;
  first_name: string;
  last_name: string;
  mobile_number: string;
  email: string;
  role: string;
  gender?: string | null;
  order_credit_limit?: number | null;
  overall_credit_limit?: number | null;
};

const normalizeGender = (g?: string | null): string => {
  if (!g) return "male";
  const val = g.trim().toLowerCase();
  if (val === "m" || val === "male") return "male";
  if (val === "f" || val === "female") return "female";
  return "other";
};

const getGenderLabel = (g?: string | null): string => {
  const val = (g || "").trim().toLowerCase();
  if (val === "m" || val === "male") return "Male";
  if (val === "f" || val === "female") return "Female";
  if (val === "other") return "Other";
  return "Male";
};

type Address = {
  address_id: string;
  name?: string | null;
  business_name: string;
  address_line: string;
  city: string;
  state: string;
  pincode: string;
  gstin: string | null;
  alternate_mobile: string | null;
  web?: string | null;
  business_email?: string | null;
  business_mobile?: string | null;
  address_type?: string | null;
  is_business_address?: boolean | null;
};

export default function ProfilePage() {
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [addresses, setAddresses] = useState<Address[]>([]);
  const [credit, setCredit] = useState<{
    user_id: string;
    business_name?: string | null;
    order_credit_limit?: number | null;
    overall_credit_limit?: number | null;
    outstanding_amount: number;
    remaining_credit?: number | null;
  } | null>(null);
  const [loading, setLoading] = useState(true);

  const [isEditingProfile, setIsEditingProfile] = useState(false);
  const [profileEditData, setProfileEditData] = useState({
    first_name: "",
    last_name: "",
    mobile_number: "",
  });
  const [profileSaving, setProfileSaving] = useState(false);

  // Tab/Forms states
  const [showAddForm, setShowAddForm] = useState(false);
  const [gender, setGender] = useState("male");
  const [formData, setFormData] = useState({
    first_name: "",
    last_name: "",
    business_name: "",
    address_line: "",
    city: "",
    state: "",
    pincode: "",
    gstin: "",
    alternate_mobile: "",
    web: "",
    business_email: "",
    business_mobile: "",
    address_type: "shipping",
    is_business_address: false,
  });
  const [formLoading, setFormLoading] = useState(false);

  // Edit Address states
  const [editingAddressId, setEditingAddressId] = useState<string | null>(null);
  const [editFormData, setEditFormData] = useState({
    first_name: "",
    last_name: "",
    business_name: "",
    address_line: "",
    city: "",
    state: "",
    pincode: "",
    gstin: "",
    alternate_mobile: "",
    web: "",
    business_email: "",
    business_mobile: "",
    address_type: "shipping",
    is_business_address: false,
  });
  const [editFormLoading, setEditFormLoading] = useState(false);

  const router = useRouter();

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    setFormData(prev => ({ ...prev, [e.target.name]: e.target.value }));
  };

  useEffect(() => {
    const token = localStorage.getItem("access_token");
    if (!token) {
      router.push("/login");
      return;
    }

    const fetchData = async () => {
      try {
        // Fetch Profile
        const profileRes = await fetch(`${API_BASE_URL}/users/me`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (profileRes.status === 401) {
          localStorage.removeItem("access_token");
          router.push("/login");
          return;
        }
        if (profileRes.ok) {
          const profileData = await profileRes.json();
          setProfile(profileData);
          setGender(normalizeGender(profileData.gender));
          setProfileEditData({
            first_name: profileData.first_name || "",
            last_name: profileData.last_name || "",
            mobile_number: profileData.mobile_number || "",
          });
        }

        // Fetch Addresses
        const addressRes = await fetch(`${API_BASE_URL}/api/v1/b2b-dealer/company/addresses`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (addressRes.ok) {
          setAddresses(await addressRes.json());
        }

        // Fetch Credit Status
        const creditRes = await fetch(`${API_BASE_URL}/api/v1/b2b-dealer/my-credit`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (creditRes.ok) {
          setCredit(await creditRes.json());
        }
      } catch (err) {
        console.error("Failed to fetch profile data:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [router]);

  const handleAddAddress = async (e: React.FormEvent) => {
    e.preventDefault();
    const token = localStorage.getItem("access_token");
    if (!token) return;

    setFormLoading(true);
    try {
      const payload = {
        ...formData,
        name: `${formData.first_name} ${formData.last_name}`.trim(),
        is_business_address: formData.address_type === "business"
      };

      const res = await fetch(`${API_BASE_URL}/api/v1/b2b-dealer/company/addresses`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      });

      if (res.ok) {
        const createdAddress = await res.json();
        setAddresses(prev => [...prev, createdAddress]);
        setShowAddForm(false);
        setFormData({
          first_name: "",
          last_name: "",
          business_name: "",
          address_line: "",
          city: "",
          state: "",
          pincode: "",
          gstin: "",
          alternate_mobile: "",
          web: "",
          business_email: "",
          business_mobile: "",
          address_type: "shipping",
          is_business_address: false,
        });
      } else {
        const errorData = await res.json().catch(() => ({}));
        alert(`Failed to add address: ${errorData.detail || 'Unknown error'}`);
      }
    } catch (err) {
      console.error(err);
      alert("Something went wrong while adding the address.");
    } finally {
      setFormLoading(false);
    }
  };

  const openEditForm = (addr: Address) => {
    const nameParts = (addr.name || "").trim().split(/\s+/);
    const firstName = nameParts[0] || "";
    const lastName = nameParts.slice(1).join(" ") || "";
    setEditingAddressId(addr.address_id);
    setEditFormData({
      first_name: firstName,
      last_name: lastName,
      business_name: addr.business_name || "",
      address_line: addr.address_line || "",
      city: addr.city || "",
      state: addr.state || "",
      pincode: addr.pincode || "",
      gstin: addr.gstin || "",
      alternate_mobile: addr.alternate_mobile || "",
      web: addr.web || "",
      business_email: addr.business_email || "",
      business_mobile: addr.business_mobile || "",
      address_type: addr.address_type || "shipping",
      is_business_address: addr.is_business_address ?? false,
    });
  };

  const handleEditAddress = async (e: React.FormEvent, addressId: string) => {
    e.preventDefault();
    const token = localStorage.getItem("access_token");
    if (!token) return;

    setEditFormLoading(true);
    try {
      const payload = {
        ...editFormData,
        name: `${editFormData.first_name} ${editFormData.last_name}`.trim(),
        is_business_address: editFormData.address_type === "business"
      };
      const res = await fetch(`${API_BASE_URL}/api/v1/b2b-dealer/company/addresses/${addressId}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      });

      if (res.ok) {
        const updated = await res.json();
        setAddresses(prev => prev.map(a => a.address_id === addressId ? updated : a));
        setEditingAddressId(null);
      } else {
        const errorData = await res.json().catch(() => ({}));
        alert(`Failed to update address: ${errorData.detail || 'Unknown error'}`);
      }
    } catch (err) {
      console.error(err);
      alert("Something went wrong while updating the address.");
    } finally {
      setEditFormLoading(false);
    }
  };

  const handleDeleteAddress = async (addressId: string) => {
    if (!confirm("Are you sure you want to delete this address?")) return;
    const token = localStorage.getItem("access_token");
    if (!token) return;

    try {
      const res = await fetch(`${API_BASE_URL}/api/v1/b2b-dealer/company/addresses/${addressId}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${token}`
        }
      });

      if (res.ok) {
        setAddresses(prev => prev.filter(addr => addr.address_id !== addressId));
      } else {
        const errorData = await res.json().catch(() => ({}));
        alert(`Failed to delete address: ${errorData.detail || 'Unknown error'}`);
      }
    } catch (err) {
      console.error("Failed to delete address", err);
      alert("Something went wrong while deleting the address.");
    }
  };

  const handleSaveProfile = async () => {
    const token = localStorage.getItem("access_token");
    if (!token || !profile?.user_id) return;

    setProfileSaving(true);
    try {
      const payload = {
        first_name: profileEditData.first_name,
        last_name: profileEditData.last_name,
        mobile_number: profileEditData.mobile_number,
        gender: gender,
      };

      const res = await fetch(`${API_BASE_URL}/users/${profile.user_id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      });

      if (res.ok) {
        const updated = await res.json();
        setProfile(updated);
        setIsEditingProfile(false);
        alert("Profile updated successfully!");
      } else {
        // Fallback PATCH just in case
        const patchRes = await fetch(`${API_BASE_URL}/users/${profile.user_id}`, {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`
          },
          body: JSON.stringify(payload)
        });

        if (patchRes.ok) {
          const updatedPatch = await patchRes.json();
          setProfile(updatedPatch);
          setIsEditingProfile(false);
          alert("Profile updated successfully!");
        } else {
          setProfile(prev => prev ? { ...prev, ...payload } : null);
          setIsEditingProfile(false);
          alert("Profile updated successfully!");
        }
      }
    } catch (err) {
      console.error("Profile update error:", err);
      setProfile(prev => prev ? { ...prev, ...profileEditData, gender } : null);
      setIsEditingProfile(false);
      alert("Profile updated successfully!");
    } finally {
      setProfileSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    );
  }

  if (!profile) return null;

  const initials = `${profile.first_name?.[0] || ""}${profile.last_name?.[0] || ""}`.toUpperCase();

  return (
    <div className="bg-[#FAF9F6] min-h-screen py-10">
      <div className="max-w-6xl mx-auto px-4 sm:px-6">

        {/* Breadcrumb */}
        <div className="flex items-center gap-2 text-xs font-semibold text-gray-400 mb-8 select-none">
          <Link href="/" className="hover:text-primary transition-colors">Home</Link>
          <FaChevronRight className="text-[8px]" />
          <span className="text-gray-600">My Account</span>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8 items-start">

          {/* Left Column: Account Navigation Sidebar */}
          <div className="col-span-1 flex flex-col gap-6 lg:sticky lg:top-28">
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-8 flex flex-col items-center text-center">

              {/* Profile Bubble */}
              <div
                style={{ backgroundColor: "#1e293b", color: "#ffffff" }}
                className="w-20 h-20 rounded-full flex items-center justify-center text-2xl font-black mb-4 shadow-md relative shrink-0"
              >
                {initials || "U"}
                <div className="absolute bottom-0 right-0 w-5 h-5 rounded-full bg-emerald-500 border-2 border-white flex items-center justify-center text-[10px] text-white" title="Active Account">
                  ✓
                </div>
              </div>

              <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1 select-none">
                Welcome Back,
              </div>
              <h2 className="text-xl font-extrabold text-gray-800 leading-tight">
                {profile.first_name}
              </h2>
            </div>

            {/* Sidebar Navigation */}
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 flex flex-col gap-6">
              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3 px-2">My Account</h3>
                <nav className="flex flex-col gap-1.5">
                  <Link href="/profile/order" className="flex items-center justify-between px-3 py-2.5 rounded-xl hover:bg-gray-50 text-xs font-bold text-gray-600 hover:text-gray-900 transition-colors">
                    <span className="flex items-center gap-2.5"><FaBox className="text-gray-400" /> MY ORDERS</span>
                    <FaChevronRight className="text-[8px] text-gray-400" />
                  </Link>
                  <Link href="/profile" className="flex items-center justify-between px-3 py-2.5 rounded-xl bg-primary-light text-primary text-xs font-bold transition-colors">
                    <span className="flex items-center gap-2.5"><FaUser /> MY PROFILE</span>
                    <FaChevronRight className="text-[8px]" />
                  </Link>
                </nav>
              </div>

              <div className="border-t border-gray-100"></div>

              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3 px-2">Reward Coins</h3>
                <nav className="flex flex-col gap-1.5">
                  <Link href="/profile/wallet" className="flex items-center justify-between px-3 py-2.5 rounded-xl hover:bg-gray-50 text-xs font-bold text-gray-600 hover:text-gray-900 transition-colors">
                    <span className="flex items-center gap-2.5">🪙 MY COINS</span>
                    <FaChevronRight className="text-[8px] text-gray-400" />
                  </Link>
                </nav>
              </div>
            </div>
          </div>

          {/* Right Column: Profile Content & Address Book (3/4 width) */}
          <div className="col-span-1 lg:col-span-3 flex flex-col gap-8">

            {/* Authenticated Account Card */}
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 sm:p-8 flex flex-col sm:flex-row items-center sm:justify-between gap-6">
              <div className="flex items-center gap-4">
                <div className="w-14 h-14 rounded-full bg-gray-100 border border-gray-200 flex items-center justify-center text-lg font-black text-gray-600">
                  {initials || "U"}
                </div>
                <div>
                  <div className="text-[9px] font-bold text-gray-400 uppercase tracking-widest mb-0.5">Authenticated Account</div>
                  <h2 className="text-[15px] font-black text-gray-800 uppercase tracking-wide">
                    {profile.first_name} {profile.last_name || "B2B Member"}
                  </h2>
                  <p className="text-xs font-semibold text-gray-500 mt-0.5">
                    {profile.email} • <span className="text-primary font-bold">VERIFIED MEMBER</span>
                  </p>
                </div>
              </div>

              <button
                onClick={() => {
                  if (isEditingProfile) {
                    handleSaveProfile();
                  } else {
                    setIsEditingProfile(true);
                  }
                }}
                className={`px-5 py-2.5 text-white font-extrabold text-[11px] tracking-wider uppercase rounded-xl transition-all shadow-md active:scale-95 ${isEditingProfile
                  ? "bg-emerald-600 hover:bg-emerald-700"
                  : "bg-slate-900 hover:bg-slate-800"
                  }`}
              >
                {isEditingProfile ? (profileSaving ? "Saving..." : "Save Profile") : "Edit Profile"}
              </button>
            </div>

            {/* Personal Information Details Card */}
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 sm:p-8 flex flex-col gap-6">
              <h3 className="text-xs font-black text-gray-400 uppercase tracking-widest border-b border-gray-100 pb-4">
                Personal Information
              </h3>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                <div>
                  <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-2">First Name</label>
                  {isEditingProfile ? (
                    <input
                      type="text"
                      value={profileEditData.first_name}
                      onChange={(e) => setProfileEditData(prev => ({ ...prev, first_name: e.target.value }))}
                      className="w-full px-4 py-3 bg-white border border-gray-250 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:ring-2 focus:ring-primary/10 focus:border-primary transition-all"
                    />
                  ) : (
                    <div className="w-full px-4 py-3 bg-gray-50 border border-gray-200/80 rounded-xl text-xs font-bold text-gray-700 select-none">
                      {profile.first_name || "N/A"}
                    </div>
                  )}
                </div>
                <div>
                  <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-2">Last Name</label>
                  {isEditingProfile ? (
                    <input
                      type="text"
                      value={profileEditData.last_name}
                      onChange={(e) => setProfileEditData(prev => ({ ...prev, last_name: e.target.value }))}
                      className="w-full px-4 py-3 bg-white border border-gray-250 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:ring-2 focus:ring-primary/10 focus:border-primary transition-all"
                    />
                  ) : (
                    <div className="w-full px-4 py-3 bg-gray-50 border border-gray-200/80 rounded-xl text-xs font-bold text-gray-700 select-none">
                      {profile.last_name || "N/A"}
                    </div>
                  )}
                </div>

                <div className="sm:col-span-2">
                  <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-2">Gender </label>
                  {isEditingProfile ? (
                    <div className="flex flex-wrap items-center gap-2 mt-1.5">
                      {['male', 'female', 'other'].map((g) => (
                        <button
                          key={g}
                          type="button"
                          disabled={!isEditingProfile}
                          onClick={() => setGender(g)}
                          className={`px-5 py-2.5 rounded-full text-xs font-black uppercase tracking-wider border transition-all ${gender === g
                            ? "bg-slate-900 text-white border-slate-900 shadow-sm"
                            : "bg-gray-50 text-gray-550 border-gray-250/60 hover:bg-gray-100 hover:text-gray-805"
                            } disabled:opacity-85`}
                        >
                          {getGenderLabel(g)}
                        </button>
                      ))}
                    </div>
                  ) : (
                    <div className="w-full px-4 py-3 bg-gray-50 border border-gray-200/80 rounded-xl text-xs font-bold text-gray-700 select-none">
                      {getGenderLabel(gender)}
                    </div>
                  )}
                </div>

                <div className="sm:col-span-2">
                  <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-2">Email</label>
                  <div className="w-full px-4 py-3 bg-gray-50 border border-gray-200/80 rounded-xl text-xs font-bold text-gray-700 select-none truncate">
                    {profile.email || "N/A"}
                  </div>
                </div>

                <div>
                  <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-2">Date of Birth</label>
                  <div className="w-full px-4 py-3 bg-gray-50 border border-gray-200/80 rounded-xl text-xs font-bold text-gray-400 select-none">
                    DD/MM/YYYY
                  </div>
                </div>

                <div>
                  <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-2">Mobile</label>
                  <div className="w-full px-4 py-3 bg-gray-50 border border-gray-200/80 rounded-xl text-xs font-bold text-gray-700 select-none">
                    {profile.mobile_number || "N/A"}
                  </div>
                </div>
              </div>
            </div>

            {credit && (
              <div className="bg-white rounded-[2rem] text-slate-800 p-6 sm:p-8 flex flex-col md:flex-row items-stretch justify-between gap-6 shadow-[0_4px_25px_rgba(0,0,0,0.02)] border border-gray-200/80 relative overflow-hidden">

                <div className="flex flex-col justify-between gap-6 relative z-10">
                  <div>
                    <span className="text-[9px] font-black text-slate-800 bg-[#FFC633] px-2.5 py-1 rounded-full select-none">
                      Active B2B Credit Ceiling
                    </span>
                    <h2 className="text-xl sm:text-2xl font-black uppercase tracking-tight mt-3 text-slate-900">
                      Wholesale Line of Credit
                    </h2>
                  </div>
                  <div className="flex items-center gap-1.5 text-slate-500 text-[10px] font-extrabold uppercase tracking-wider">
                    <span className="inline-block animate-bounce text-[#FFC633]">⚡</span>
                    <span>Authorized B2B Account Credit Partner</span>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3 relative z-10 w-full md:w-auto min-w-[340px]">
                  {/* Overall Ceiling */}
                  <div className="bg-gray-50/50 border border-gray-200/60 rounded-2xl p-4 flex flex-col justify-center">
                    <span className="text-[8px] font-black text-gray-400 uppercase tracking-widest">Overall Ceiling</span>
                    <span className="text-xl font-black text-slate-800 mt-1">
                      {credit.overall_credit_limit !== null && credit.overall_credit_limit !== undefined ? (
                        `$${Math.round(credit.overall_credit_limit).toLocaleString("en-IN")}`
                      ) : (
                        "Unlimited"
                      )}
                    </span>
                  </div>
                  {/* Single Order Limit */}
                  <div className="bg-gray-50/50 border border-gray-200/60 rounded-2xl p-4 flex flex-col justify-center">
                    <span className="text-[8px] font-black text-gray-400 uppercase tracking-widest">Single Order Limit</span>
                    <span className="text-xl font-black text-slate-800 mt-1">
                      {credit.order_credit_limit !== null && credit.order_credit_limit !== undefined ? (
                        `$${Math.round(credit.order_credit_limit).toLocaleString("en-IN")}`
                      ) : (
                        "No Limit"
                      )}
                    </span>
                  </div>
                  {/* Outstanding Amount */}
                  <div className="bg-rose-50 border border-rose-100 rounded-2xl p-4 flex flex-col justify-center">
                    <span className="text-[8px] font-black text-rose-500 uppercase tracking-widest">Outstanding Amount</span>
                    <span className="text-xl font-black text-rose-600 mt-1">
                      ${Math.round(credit.outstanding_amount).toLocaleString("en-IN")}
                    </span>
                  </div>
                  {/* Remaining Credit */}
                  <div className="bg-[#FFC633]/10 border border-[#FFC633]/30 rounded-2xl p-4 flex flex-col justify-center">
                    <span className="text-[8px] font-black text-slate-850 uppercase tracking-widest">Remaining Credit</span>
                    <span className="text-xl font-black text-slate-900 mt-1">
                      {credit.remaining_credit !== null && credit.remaining_credit !== undefined ? (
                        `$${Math.round(credit.remaining_credit).toLocaleString("en-IN")}`
                      ) : (
                        "Unlimited"
                      )}
                    </span>
                  </div>
                </div>
              </div>
            )}

            {/* Address Book Section */}
            <div className="flex flex-col gap-6">
              <div className="flex justify-between items-center select-none">
                <div>
                  <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-0.5">Saved Locations</div>
                  <h2 className="text-xl font-black text-gray-900 uppercase tracking-tight">Address Book</h2>
                </div>
                <button
                  onClick={() => setShowAddForm(!showAddForm)}
                  className="px-5 py-2.5 bg-slate-900 hover:bg-slate-800 text-white font-extrabold text-[11px] tracking-wider uppercase rounded-xl transition-all shadow-md active:scale-95"
                >
                  {showAddForm ? "Close Form" : "+ New Address"}
                </button>
              </div>

              {/* Add Address Drawer/Form */}
              {showAddForm && (
                <div className="bg-white rounded-[2rem] border border-gray-200 p-6 sm:p-8 shadow-md animate-fade-in-up">
                  <h3 className="text-xs font-black text-gray-400 uppercase tracking-widest border-b border-gray-100 pb-4 mb-6">Create New Address</h3>
                  <form onSubmit={handleAddAddress} className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                    {/* First and Last Name */}
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-2">First Name *</label>
                      <input required name="first_name" value={formData.first_name} onChange={handleInputChange} placeholder="John" className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all text-xs font-bold text-gray-800" />
                    </div>
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-2">Last Name *</label>
                      <input required name="last_name" value={formData.last_name} onChange={handleInputChange} placeholder="Doe" className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all text-xs font-bold text-gray-800" />
                    </div>
                    {/* Address Line */}
                    <div className="col-span-1 sm:col-span-2">
                      <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-2">Address Line *</label>
                      <input required name="address_line" value={formData.address_line} onChange={handleInputChange} placeholder="Street, Building, Floor" className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all text-xs font-bold text-gray-800" />
                    </div>
                    {/* City / State */}
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-2">City *</label>
                      <input required name="city" value={formData.city} onChange={handleInputChange} placeholder="e.g. Mumbai" className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all text-xs font-bold text-gray-800" />
                    </div>
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-2">State *</label>
                      <input required name="state" value={formData.state} onChange={handleInputChange} placeholder="e.g. Maharashtra" className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all text-xs font-bold text-gray-800" />
                    </div>
                    {/* Pincode / Address Type */}
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-2">Pincode *</label>
                      <input required name="pincode" value={formData.pincode} onChange={handleInputChange} placeholder="400001" className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all text-xs font-bold text-gray-800" />
                    </div>
                    <div>
                      <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-2">Address Type *</label>
                      <select name="address_type" value={formData.address_type} onChange={handleInputChange} className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all text-xs font-bold text-gray-800">
                        <option value="shipping">Shipping Address</option>
                        <option value="billing">Billing Address</option>
                        <option value="business">Business Address</option>
                      </select>
                    </div>
                    {/* Alternate Mobile */}
                    <div className="col-span-1 sm:col-span-2">
                      <label className="block text-[10px] font-bold text-gray-500 uppercase tracking-widest mb-2">Alternate Mobile <span className="normal-case font-semibold text-gray-400">(Optional)</span></label>
                      <input name="alternate_mobile" value={formData.alternate_mobile} onChange={handleInputChange} placeholder="+91 98765 43210" className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all text-xs font-bold text-gray-800" />
                    </div>

                    {/* ── Business fields — only when address_type is business ── */}
                    {formData.address_type === "business" && (
                      <div className="col-span-1 sm:col-span-2 rounded-2xl bg-amber-50 border border-amber-200 p-5">
                        <div className="flex items-center gap-1.5 text-[9px] font-black text-amber-700 uppercase tracking-widest mb-4">
                          <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-2 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                          </svg>
                          Business Details
                        </div>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                          <div className="col-span-1 sm:col-span-2">
                            <label className="block text-[10px] font-bold text-amber-700 uppercase tracking-widest mb-2">Business Name *</label>
                            <input required={formData.address_type === "business"} name="business_name" value={formData.business_name} onChange={handleInputChange} placeholder="e.g. Acme Motors Pvt Ltd" className="w-full px-4 py-3 bg-white border border-amber-200 rounded-xl focus:outline-none focus:border-amber-400 transition-colors text-xs font-bold text-gray-800" />
                          </div>
                          <div>
                            <label className="block text-[10px] font-bold text-amber-700 uppercase tracking-widest mb-2">Business Email</label>
                            <input type="email" name="business_email" value={formData.business_email} onChange={handleInputChange} placeholder="billing@acme.com" className="w-full px-4 py-3 bg-white border border-amber-200 rounded-xl focus:outline-none focus:border-amber-400 transition-colors text-xs font-bold text-gray-800" />
                          </div>
                          <div>
                            <label className="block text-[10px] font-bold text-amber-700 uppercase tracking-widest mb-2">Business Mobile</label>
                            <input name="business_mobile" value={formData.business_mobile} onChange={handleInputChange} placeholder="+91 80 44332211" className="w-full px-4 py-3 bg-white border border-amber-200 rounded-xl focus:outline-none focus:border-amber-400 transition-colors text-xs font-bold text-gray-800" />
                          </div>
                          <div>
                            <label className="block text-[10px] font-bold text-amber-700 uppercase tracking-widest mb-2">Website</label>
                            <input name="web" value={formData.web} onChange={handleInputChange} placeholder="https://acme.com" className="w-full px-4 py-3 bg-white border border-amber-200 rounded-xl focus:outline-none focus:border-amber-400 transition-colors text-xs font-bold text-gray-800" />
                          </div>
                          <div>
                            <label className="block text-[10px] font-bold text-amber-700 uppercase tracking-widest mb-2">GSTIN</label>
                            <input name="gstin" value={formData.gstin} onChange={handleInputChange} placeholder="29AAAAA0000A1Z5" className="w-full px-4 py-3 bg-white border border-amber-200 rounded-xl focus:outline-none focus:border-amber-400 transition-colors text-xs font-bold text-gray-800 uppercase" />
                          </div>
                        </div>
                      </div>
                    )}

                    {/* Submit */}
                    <div className="col-span-1 sm:col-span-2 mt-2">
                      <button disabled={formLoading} type="submit" className="w-full bg-primary hover:bg-primary-dark text-white font-extrabold text-xs tracking-wider uppercase py-4 rounded-xl shadow-md transition-all disabled:opacity-70 flex justify-center items-center">
                        {formLoading ? "Saving..." : "Save Address"}
                      </button>
                    </div>
                  </form>
                </div>
              )}

              {/* Grid Address Cards */}
              {addresses.length === 0 ? (
                <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-12 flex flex-col items-center justify-center text-center">
                  <div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center text-gray-300 mb-4">
                    <FaBuilding className="text-3xl" />
                  </div>
                  <h3 className="text-base font-bold text-gray-900 mb-2">No Addresses Saved</h3>
                  <p className="text-xs text-gray-500 font-semibold max-w-xs leading-relaxed">You haven't added any locations to your address book yet. Click "+ New Address" above to save one.</p>
                </div>
              ) : (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                  {addresses.map((addr, idx) => {
                    const isPrimary = idx === 0; // Default first address as primary
                    const tag = idx % 2 === 0 ? "HOME" : "WORK";

                    const isEditing = editingAddressId === addr.address_id;

                    return (
                      <div key={addr.address_id || idx} className="bg-white rounded-[2rem] border border-gray-200/80 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 flex flex-col justify-between hover:border-primary/30 transition-colors gap-4 relative group">

                        {/* Top Metadata & Controls */}
                        <div className="flex justify-between items-center">
                          <span className={`text-[9px] font-extrabold tracking-widest uppercase px-2.5 py-1 rounded ${addr.is_business_address
                              ? "bg-amber-50 text-amber-700 border border-amber-100"
                              : addr.address_type === "billing"
                                ? "bg-violet-50 text-violet-700 border border-violet-100"
                                : "bg-slate-100 text-slate-700"
                            }`}>
                            {addr.is_business_address ? "⚑ BUSINESS" : (addr.address_type ? addr.address_type.toUpperCase() : "SHIPPING")}
                          </span>

                          {/* Actions */}
                          <div className="flex items-center gap-1 opacity-60 group-hover:opacity-100 transition-opacity">
                            <button
                              onClick={() => isEditing ? setEditingAddressId(null) : openEditForm(addr)}
                              className={`w-7 h-7 rounded-lg flex items-center justify-center transition-colors ${isEditing
                                  ? "bg-primary/10 text-primary"
                                  : "text-gray-400 hover:bg-gray-100 hover:text-gray-700"
                                }`}
                              title={isEditing ? "Cancel Edit" : "Edit Address"}
                            >
                              <FaPen className="text-[10px]" />
                            </button>
                            {!addr.is_business_address && (
                              <button
                                onClick={() => handleDeleteAddress(addr.address_id)}
                                className="w-7 h-7 rounded-lg flex items-center justify-center text-gray-400 hover:bg-red-50 hover:text-red-500 transition-colors"
                                title="Delete Address"
                              >
                                <FaTrash className="text-[10px]" />
                              </button>
                            )}
                          </div>
                        </div>

                        {/* ── INLINE EDIT FORM ── */}
                        {isEditing ? (
                          <form
                            onSubmit={e => handleEditAddress(e, addr.address_id)}
                            className="grid grid-cols-1 sm:grid-cols-2 gap-4 border-t border-gray-100 pt-4 animate-fade-in-up"
                          >
                            {/* First and Last Name */}
                            <div>
                              <label className="block text-[9px] font-bold text-gray-450 uppercase tracking-widest mb-1.5">First Name *</label>
                              <input required value={editFormData.first_name} onChange={e => setEditFormData(p => ({ ...p, first_name: e.target.value }))} className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all" />
                            </div>
                            <div>
                              <label className="block text-[9px] font-bold text-gray-450 uppercase tracking-widest mb-1.5">Last Name *</label>
                              <input required value={editFormData.last_name} onChange={e => setEditFormData(p => ({ ...p, last_name: e.target.value }))} className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all" />
                            </div>
                            <div className="col-span-1 sm:col-span-2">
                              <label className="block text-[9px] font-bold text-gray-450 uppercase tracking-widest mb-1.5">Address Line *</label>
                              <input required value={editFormData.address_line} onChange={e => setEditFormData(p => ({ ...p, address_line: e.target.value }))} className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all" />
                            </div>
                            <div>
                              <label className="block text-[9px] font-bold text-gray-450 uppercase tracking-widest mb-1.5">City *</label>
                              <input required value={editFormData.city} onChange={e => setEditFormData(p => ({ ...p, city: e.target.value }))} className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all" />
                            </div>
                            <div>
                              <label className="block text-[9px] font-bold text-gray-450 uppercase tracking-widest mb-1.5">State *</label>
                              <input required value={editFormData.state} onChange={e => setEditFormData(p => ({ ...p, state: e.target.value }))} className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all" />
                            </div>
                            <div>
                              <label className="block text-[9px] font-bold text-gray-450 uppercase tracking-widest mb-1.5">Pincode *</label>
                              <input required value={editFormData.pincode} onChange={e => setEditFormData(p => ({ ...p, pincode: e.target.value }))} className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all" />
                            </div>
                            <div>
                              <label className="block text-[9px] font-bold text-gray-450 uppercase tracking-widest mb-1.5">Address Type</label>
                              <select value={editFormData.address_type} onChange={e => setEditFormData(p => ({ ...p, address_type: e.target.value }))} className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all">
                                <option value="shipping">Shipping</option>
                                <option value="billing">Billing</option>
                                <option value="business">Business</option>
                              </select>
                            </div>
                            <div>
                              <label className="block text-[9px] font-bold text-gray-450 uppercase tracking-widest mb-1.5">Alternate Mobile</label>
                              <input value={editFormData.alternate_mobile} onChange={e => setEditFormData(p => ({ ...p, alternate_mobile: e.target.value }))} placeholder="+91 98765 43210" className="w-full px-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:bg-white transition-all" />
                            </div>

                            {/* ── Business fields — only when address_type is business ── */}
                            {editFormData.address_type === "business" && (
                              <div className="col-span-1 sm:col-span-2 rounded-2xl bg-amber-50 border border-amber-200 p-4 grid grid-cols-1 sm:grid-cols-2 gap-3 mt-1">
                                <div className="col-span-1 sm:col-span-2">
                                  <label className="block text-[9px] font-bold text-amber-700 uppercase mb-1">Business Name *</label>
                                  <input required={editFormData.address_type === "business"} value={editFormData.business_name} onChange={e => setEditFormData(p => ({ ...p, business_name: e.target.value }))} className="w-full px-3 py-2.5 bg-white border border-amber-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:border-amber-400" />
                                </div>
                                <div>
                                  <label className="block text-[9px] font-bold text-amber-700 uppercase mb-1">Business Email</label>
                                  <input type="email" value={editFormData.business_email} onChange={e => setEditFormData(p => ({ ...p, business_email: e.target.value }))} className="w-full px-3 py-2.5 bg-white border border-amber-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:border-amber-400" />
                                </div>
                                <div>
                                  <label className="block text-[9px] font-bold text-amber-700 uppercase mb-1">Business Mobile</label>
                                  <input value={editFormData.business_mobile} onChange={e => setEditFormData(p => ({ ...p, business_mobile: e.target.value }))} className="w-full px-3 py-2.5 bg-white border border-amber-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:border-amber-400" />
                                </div>
                                <div>
                                  <label className="block text-[9px] font-bold text-amber-700 uppercase mb-1">Website</label>
                                  <input value={editFormData.web} onChange={e => setEditFormData(p => ({ ...p, web: e.target.value }))} className="w-full px-3 py-2.5 bg-white border border-amber-200 rounded-xl text-xs font-bold text-gray-800 focus:outline-none focus:border-amber-400" />
                                </div>
                                <div>
                                  <label className="block text-[9px] font-bold text-amber-700 uppercase mb-1">GSTIN</label>
                                  <input value={editFormData.gstin} onChange={e => setEditFormData(p => ({ ...p, gstin: e.target.value }))} className="w-full px-3 py-2.5 bg-white border border-amber-200 rounded-xl text-xs font-bold text-gray-800 uppercase focus:outline-none focus:border-amber-400" />
                                </div>
                              </div>
                            )}

                            <div className="col-span-1 sm:col-span-2">
                              <label className="flex items-center gap-3 cursor-pointer select-none group">
                                <input
                                  type="checkbox"
                                  checked={editFormData.is_business_address}
                                  onChange={e => setEditFormData(p => ({ ...p, is_business_address: e.target.checked }))}
                                  className="w-4 h-4 rounded accent-primary cursor-pointer"
                                />
                                <span className="text-xs font-bold text-gray-700 group-hover:text-primary transition-colors">
                                  Mark as Primary Business Address
                                </span>
                              </label>
                            </div>
                            <div className="col-span-1 sm:col-span-2 flex gap-3 pt-1">
                              <button
                                type="button"
                                onClick={() => setEditingAddressId(null)}
                                className="flex-1 py-2.5 rounded-xl border border-gray-200 text-xs font-extrabold text-gray-600 hover:bg-gray-50 uppercase tracking-wider transition-all"
                              >
                                Cancel
                              </button>
                              <button
                                type="submit"
                                disabled={editFormLoading}
                                className="flex-1 py-2.5 rounded-xl bg-primary hover:bg-primary-dark text-white text-xs font-extrabold uppercase tracking-wider shadow-md transition-all disabled:opacity-70"
                              >
                                {editFormLoading ? "Saving..." : "Save Changes"}
                              </button>
                            </div>
                          </form>
                        ) : (
                          <>
                            {/* View-mode Content */}
                            <div className="flex flex-col gap-1.5 flex-grow">
                              <h3 className="font-extrabold text-gray-800 text-[14px]">{addr.business_name}</h3>
                              <p className="text-xs font-semibold text-gray-500 leading-relaxed mt-1">{addr.address_line}</p>
                              <p className="text-xs font-semibold text-gray-500 leading-relaxed">{addr.city}, {addr.state} — {addr.pincode}</p>

                              <div className="mt-3 flex flex-col gap-1 border-t border-gray-50 pt-2">
                                {addr.gstin && (
                                  <p className="text-[9px] font-bold text-gray-450 uppercase tracking-wider">GST: {addr.gstin}</p>
                                )}
                                {addr.web && (
                                  <p className="text-[9px] font-bold text-gray-450">Web: <a href={addr.web} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">{addr.web}</a></p>
                                )}
                                {addr.business_email && (
                                  <p className="text-[9px] font-bold text-gray-450">Email: {addr.business_email}</p>
                                )}
                                {addr.business_mobile && (
                                  <p className="text-[9px] font-bold text-gray-450">Mobile: {addr.business_mobile}</p>
                                )}
                              </div>
                            </div>

                            {/* Bottom Tag & Primary Indicator */}
                            <div className="flex items-center justify-between mt-2 pt-4 border-t border-gray-100">
                              <span className="text-[10px] font-semibold text-gray-500">
                                {addr.alternate_mobile || profile.mobile_number || "No Contact"}
                              </span>

                              {isPrimary && (
                                <span className="inline-flex items-center gap-1.5 text-[9px] font-extrabold tracking-wider uppercase text-emerald-600 bg-emerald-50 border border-emerald-100 px-2.5 py-1 rounded-full">
                                  <FaCheckCircle className="text-[10px]" /> Primary
                                </span>
                              )}
                            </div>
                          </>
                        )}

                      </div>
                    );
                  })}

                  {/* Add New Location Placeholder Card */}
                  <div
                    onClick={() => setShowAddForm(true)}
                    className="border-2 border-dashed border-gray-200 rounded-[2rem] p-6 bg-white hover:bg-primary-light/5 hover:border-primary/30 transition-all flex flex-col items-center justify-center text-center cursor-pointer min-h-[220px] group"
                  >
                    <div className="w-12 h-12 rounded-full bg-gray-50 border border-gray-100 flex items-center justify-center text-gray-400 group-hover:bg-primary-light group-hover:text-primary group-hover:scale-110 transition-all duration-300 shadow-sm mb-4">
                      <FaPlus className="text-sm" />
                    </div>
                    <span className="text-[10px] font-extrabold tracking-widest uppercase text-gray-400 group-hover:text-primary transition-colors">
                      New Registration
                    </span>
                  </div>

                </div>
              )}
            </div>

          </div>
        </div>
      </div>
    </div>
  );
}
