"use client";

import { useState, useEffect } from "react";
import AddressDialog from "../_components/AddressDialog";
import { useAuthContext } from "@/contexts/AuthProvider";
import { apiCall } from "@/utils/callApi";
export default function AddressesPage() {
  const [addresses, setAddresses] = useState<any[]>([]);
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const { clienttoken } = useAuthContext();

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

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

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

  return (
    <div>
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl sm:text-2xl 2xl:text-3xl font-semibold">My Addresses</h2>
        <button
          onClick={() => {
            setEditing(null);
            setOpen(true);
          }}
          className="theme-btn"
        >
          Add New Address
        </button>
      </div>

      <div className="grid gap-4">
        {addresses.map((addr) => (
          <div key={addr._id} className="bg-white rounded-xl border p-4">
            <p><strong>{addr.name}</strong></p>
            <p>{addr.addressLine1}</p>
            <p>{addr.city}, {addr.state?.name}</p>
            <p>{addr.pincode}</p>
            <p>Phone: {addr.phone}</p>
            <div className="flex gap-2 mt-3">
              <button
                onClick={() => {
                  setEditing(addr);
                  setOpen(true);
                }}
                className="px-3 py-1 text-primary border border-primary rounded hover:bg-primary hover:text-white transition"
              >
                Edit
              </button>
              <button
                onClick={() => handleDelete(addr._id)}
                className="px-3 py-1 text-red-600 border border-red-600 rounded hover:bg-red-600 hover:text-white transition"
              >
                Delete
              </button>
            </div>
          </div>
        ))}
      </div>

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