import './App.css';
import {useState, useEffect } from 'react';
import React, {useCallback} from 'react'
import {useDropzone} from 'react-dropzone'

const Dots = ({count,active, onChange}) =>{
  let arrImg = []; 
  for (let i = 0; i < count; i++) {
    arrImg.push(i)
  }
 
   return (
    <>
   
    <ul>
      {arrImg.map(( _, index) => <li key = {index} className = {`dotBase ${active === index? 'dotActive' : 'dotNotActive'}`} onClick = {() => onChange(index)}></li>)}
    </ul>
      
    </>
  )
}

const Gallery = ({images = ['https://kot-pes.com/wp-content/uploads/2018/12/post_5c249026dde11.jpg',
'https://bigpicture.ru/wp-content/uploads/2019/12/DmrVIH7W4AAU_90-800x533.jpg', 
'https://lh3.googleusercontent.com/proxy/NBss1i5HXdYP-YI9ygt53JYbC1CZm1SDRk8o5DGZqp_Nr_LZ6Me47RRn8Rex4_goswBpwPGakuNWO7HIifvorG5Rwm3tSWFbXclY8ANMBMRwlQ18U-wpGbzn8OXfaQX15W7dNdp8']}) => {

  const [index, setIndex] = useState(0);

  function next () { 
    if(index === (images.length - 1)) { 
      setIndex(0);
    } else setIndex(index + 1);
  }

  function back () { 
    if(index === 0) { 
      setIndex(images.length - 1);
    } else setIndex(index - 1);
  }
  function change (id) { 
    setIndex(id)

  }

  return (
    <>
      <img className = "carousel-item" src = {images[index]} alt="cat"></img>
      <Dots count = {images.length} active = {index}  onChange = {change}/>
      <button onClick = {next}>Вперед</button>
      <button onClick= {back}>Назад</button>
      
    </>
  )
}

const countries ={
  "AF": "Afghanistan",
  "AX": "Åland Islands",
  "AL": "Albania",
  "DZ": "Algeria",
  "AS": "American Samoa",
  "AD": "AndorrA",
  "AO": "Angola",
  "AI": "Anguilla",
  "AQ": "Antarctica",
}

const MySelect = ({options=countries, value='AX', onChange }) => {
  const newCountry = Object.entries(options);

  return (
    <select value = {value} onChange = {(e) => onChange(e.target.value)} >
    {newCountry.map((item) => <option key = {item[0]} value = {item[0]} > {item[1]}</option>)}

    </select>
  )
}


const PhoneBookEntry = ({data:{name, phone}={name: '', phone: ''}, 
                                onChange,  //по изменению
                                onMoveUp,  //сдвинуть вверх
                                onMoveDown,//сдвинуть вниз
                                onDelete,  //удалить этот
                                onAddL}) => //добавить под ним еще один
<>
    
    <input value={name} onChange={(e) => onChange({'name': e.target.value, phone })} />
   
    <input value={phone} onChange={(e) =>(onChange({name, 'phone': e.target.value}))} />
    <button onClick={onMoveUp}>^</button>
    <button onClick={onMoveDown}>v</button>
    <button onClick={onDelete}>x</button>
    <button onClick={onAddL}>+</button>
</>

const defaultPeople = [{name: 'John', phone: '102'}, 
                            {name: 'Paul', phone: '103'}]
const PhoneBook = ({people=defaultPeople,
                    onSave}) => {
    const [ppl, setPpl] = useState(people)
    const [keys, setKeys] = useState(people.map(() => Math.random()))
//    const keys  = useRef(people.map(() => Math.random()))
    //должно меняться соответственно элементам списка - сдвигаться удаляться и тп
    useEffect(() => {
        setPpl(people);
        setKeys(people.map(() => Math.random()));//тут и keys обновить
    },[people])
    //обеспечить для PhoneBookEntry:
    //   onChange, onMoveUp, onMoveDown, onDelete
    const onChange = (newData, i) => { //{name: 'НАМЕ', phone: 'НУМБЕР'}
        const newPeople = [...ppl];//создаем новый массив ppl на базе старого, заменяем один элемент и делаем setPpl
        newPeople[i] = newData; //ничего НЕ ДЕЛАЕМ с keys
        setPpl(newPeople);
    }
    const onDelete = (i) => {  //фильтрует ppl и keys удаляя i-ый элемент
      const newPeople = ppl.filter((_, index) => index!==i);
      setPpl(newPeople);

      const newKeys = keys.filter((_, index) => index!==i);
      setKeys(newKeys);
    }

    const onMoveUp = (data, i) => {
      const newPeople = [...ppl];
      newPeople.splice(i, 1);
      newPeople.splice((i-1), 0, data);
      setPpl(newPeople);

      const newKeys = [...keys];
      newKeys.splice(i, 1);
      newKeys.splice(i-1, 0, keys[i]);
      setKeys(newKeys);

    }

    const onMoveDown = (data, i) => {
      const newPeople = [...ppl];
      newPeople.splice(i, 1);
      newPeople.splice((i+1), 0, data);
      setPpl(newPeople);

      const newkeys = [...keys];
      newkeys.splice(i, 1);
      newkeys.splice(i+1, 0, keys[i]);
    }

    const onAddFirst = () => {
      const newPeople = [...ppl];
      newPeople.unshift({'name': '', 'phone': ''});
      setPpl(newPeople);

      const newKeys =[...keys];
      newKeys.unshift(Math.random());
      setKeys(newKeys);
    }

    const onAddL = () => {
      const newPeople = [...ppl];
      newPeople.push({'name': '', 'phone': ''});
      setPpl(newPeople);

      const newKeys =[...keys];
      newKeys.push(Math.random());
      setKeys(newKeys);
    }

    console.log(keys, ppl)
    return (
        <>
            <button onClick={onAddFirst}>+</button> 
            <div className='PhoneBook'>
            
                {ppl.map((data, i) =><div key={keys[i]} > <PhoneBookEntry data={data}   //не забудьте keys
                                                 onChange={data => onChange(data, i)}
                                                 onDelete={() => onDelete(i)}
                                                 onMoveDown={() => onMoveDown(data, i)} 
                                                 onMoveUp={() => onMoveUp(data, i)}
                                                 onAddL={onAddL}

                                                 />
                                      </div>  )}
            </div>
            <button onClick={() => onSave(ppl)}>Save</button>
        </>
    )
}




function App() {
  const [country, setCountry] = useState('AX')
  return (
    < >
      <div className="App">
        {console.log(country)}
        <MySelect value={country} onChange = {(w) => setCountry(w)} />
        <Gallery/>
      </div>
      <div>
      <PhoneBook/>
      </div>
      <div>
      
      </div>
     </>

  );
}

export default App;
