"use client";

import React, { useState,useEffect } from 'react';
import { Address } from './types';
import { toast } from 'sonner';
import { apiCall } from '@/utils/callApi';
import { useAuthContext } from '@/contexts/AuthProvider';



interface SavedAddressesProps {
  onAddressSelect: (addressId: string) => void;
  errors: any;
}

const SavedAddresses = ({ onAddressSelect, errors }: SavedAddressesProps) => {
  const [selectedId, setSelectedId] = useState<string>('');
  const [savedAddresses, setSavedAddresses] = useState<Address[]>([]);
 const { clienttoken } = useAuthContext();

     const fetchAddresses = async () => {
      try {
        const res = await apiCall<{ data: Address[] }>(
          "/clientapi/users/address",
          {
            method: "GET",
            headers: {
              Authorization: `Bearer ${clienttoken}`,
            },
          }
        );

        if (res?.data) {
          setSavedAddresses(res.data.data);
        } else {
          toast.error("Failed to fetch addresses");
        }
      } catch (error: any) {
        toast.error(error?.message || "Failed to fetch addresses");
      }
    };
 useEffect(() => {


    if (clienttoken) {
      fetchAddresses();
    }
  }, [clienttoken]);
  const handleSelect = (id: string) => {
    setSelectedId(id);
    onAddressSelect(id);
    // Save selected address to localStorage for retrieval
    const address = savedAddresses.find(addr => addr.id === id);
    if (address) {
      localStorage.setItem(`address_${id}`, JSON.stringify(address));
    }
  };

  return (
    <div className="saved-address">
      <div className="row flex flex-wrap -mx-2 lg:-mx-3 mt-2 mb-3">
        {savedAddresses.map((address) => {
          console.log(address);
          
          return(
          <div key={address.id} className="xl:w-6/12 lg:w-6/12 md:w-6/12 sm:w-6/12 w-full px-2 lg:px-3 mt-3">
            <div className={`shipping-box customRadio m-0 ${selectedId === address.id ? 'border-primary' : ''}`}>
              <input 
                type="radio" 
                name="ship_addr_id" 
                value={address.id} 
                id={`ship-addr-${address.id}`}
                checked={selectedId === address.id}
                onChange={() => handleSelect(address.id)}
              />
              <label className="option option-1" htmlFor={`ship-addr-${address.id}`}>
                <h6>{address.name}</h6>                                                      
                <p>{address?.addressLine1} {address?.addressLine2}, {address?.city}, {address?.state?.name} {address?.zipCode}</p>
                <p>Phone No: {address.phone}</p>
              </label>
            </div>
          </div>
        )})}
      </div>
      {errors.shipping_address && (
        <p className="text-red-500 text-xs mt-1">{errors.shipping_address}</p>
      )}
    </div>
  );
};

export default SavedAddresses;