"use client";

import { useEffect, useState } from "react";
import ProfileSection from "./ProfileSection";
import AddressDialog from "./AddressDialog";
import { useAuthContext } from "@/contexts/AuthProvider";
import { apiCall } from "@/utils/callApi";

export default function ProfilePage() {
  const [customer, setCustomer] = useState<any>(null);
  const [addresses, setAddresses] = useState<any[]>([]);
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const { clienttoken } = useAuthContext()

  //  FETCH PROFILE 
  const fetchProfile = async () => {
    const res = await apiCall<any>("/clientapi/users/details", {
      headers: {
        Authorization: `Bearer ${clienttoken}`
      }
    });
    if(res.data?.success) {
      setCustomer(res.data?.data);
    }
  };

  //  FETCH ADDRESS 
  const fetchAddresses = async () => {
    const res = await apiCall<any>("/clientapi/users/address", {
      headers: {
        Authorization: `Bearer ${clienttoken}`
      }
    });
    if(res.data?.success) {
      setAddresses(res.data?.data || []);
    }
  };

  useEffect(() => {
    fetchProfile();
    fetchAddresses();
  }, []);

  // DELETE
  const handleDelete = async (id: string) => {
    await fetch(`/clientapi/users/address?addressId=${id}`, {
      method: "DELETE",
    });

    fetchAddresses();
  };

  return (
    <div>
      <ProfileSection customer={customer} />

      {/* ADDRESS SECTION */}
      <div className="mt-6">
        <div className="flex justify-between items-center">
          <h2 className="text-xl font-semibold">Addresses</h2>

          <button
            onClick={() => {
              setEditing(null);
              setOpen(true);
            }}
            className="px-3 py-1 bg-black text-white rounded"
          >
            Add Address
          </button>
        </div>

        <div className="grid gap-3 mt-4">
          {addresses.map((addr) => (
            <div key={addr._id} className="border p-3 rounded">
              <p><b>{addr.name}</b></p>
              <p>{addr.addressLine1}</p>
              <p>{addr.city}</p>
              <p>{addr.state?.name}</p>
              <p>{addr.pincode}</p>

              <div className="flex gap-2 mt-2">
                <button
                  onClick={() => {
                    setEditing(addr);
                    setOpen(true);
                  }}
                >
                  Edit
                </button>

                <button onClick={() => handleDelete(addr._id)}>
                  Delete
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* DIALOG */}
      <AddressDialog
        open={open}
        onOpenChange={setOpen}
        editing={editing}
        refresh={fetchAddresses}
      />
    </div>
  );
}