"use client"
import React, { useState } from 'react'
import EditImage from '../../components/layout/EditImage'
import useProfile from '../UseProfile';
import AddressInfo from '../layout/AddressInfo';

const UserForm = ({user, onSave}) => {
    const [userName, setUserName] = useState(user?.name || '');
    const [image, setImage] = useState(user?.image || '');
    const [phoneNumber, setPhoneNumber] = useState(user?.phoneNumber || '');
    const [streetAddress, setStreetAddress] = useState(user?.streetAddress || '');
    const [city, setCity] = useState(user?.city || '');
    const [stateProvince, setStateProvince] = useState(user?.stateProvince || '');
    const [zipCode, setZipCode] = useState(user?.zipCode || '');
    const [country, setCountry] = useState(user?.country || '');
    const [admin, setAdmin] = useState(user?.admin || false);
    const {data:loginAsUser} = useProfile();


    function handleAddressChange(propName, value){
      if(propName === 'phoneNumber') setPhoneNumber(value);
      if(propName === 'streetAddress') setStreetAddress(value);
      if(propName === 'city') setCity(value);
      if(propName === 'stateProvince') setStateProvince(value);
      if(propName === 'zipCode') setZipCode(value);
      if(propName === 'country') setCountry(value);
    }


  return (
    <div className='max-w-md mx-auto mt-10'>
        <div className='flex flex-col gap-2 justify-center items-center max-w-[100px] mx-auto'>
          <EditImage link={image} setLink={setImage}/>
        </div>
        <form className='mt-5 text-sm sm:text-base flex flex-col gap-0 sm:gap-1' onSubmit={ev => onSave(ev, {name:userName, image, phoneNumber, streetAddress, city, stateProvince, zipCode, country, admin,})}>
          <div>
            <label className='text-gray-700 text-sm font-semibold'>Name</label>
            <input type='text' placeholder='Name' value={userName} onChange={ev => setUserName(ev.target.value)}/>
          </div>
          <div>
            <label className='text-gray-700 text-sm font-semibold'>Email</label>
            <input type='text' value={user.email} disabled={true} className='disabled:bg-gray-200 disabled:text-gray-400'/>
          </div>
          <AddressInfo addressProps={{phoneNumber, streetAddress, city, stateProvince, zipCode, country}} setAddressProps={handleAddressChange}/>
          {loginAsUser.admin && (
            <div className='flex gap-2 items-center mb-5'>
              <label htmlFor='admin' className='text-gray-700 text-sm font-semibold'>Admin:</label>
              <input type='checkbox' id='admin' value={'1'} checked={admin} onChange={ev => setAdmin(ev.target.checked)}/>
            </div>
          )}
          <button className='w-full bg-pink-500 text-white p-2 rounded-md hover:opacity-80 duration-300 disabled:cursor-not-allowed'>Save</button>
        </form>
      </div>
  )
}

export default UserForm