import React, {useState, useEffect} from "react"
import {DropDownRegionsList} from "./DropDownRegionsList"
import {CountriesTable} from "./CountriesTable"


export const CountriesForm = props =>
{
    const [countries, setCountries] = useState([])
    const [selectedCountries, setSelectedCountries] = useState([])
    const [regions, setRegions] = useState([])
    const [selectedRegion, setSelectedRegion] = useState("All Regions")
    
    useEffect(() => 
    {
        fetch("json/countries.json")
        .then(response => response.json())
        .then(countries => 
        {
            // get the list of unique regions
            let regions = countries.map(country => country.region)
            let uniqueRegions = [...new Set(regions)].sort()
            uniqueRegions.unshift("All Regions") // add "All Regions" to the front of the array
            uniqueRegions[uniqueRegions.indexOf("")] = "None" // replace empty region (i.e. "") with "None"  
            
            setCountries(countries)
            setSelectedCountries(countries)
            setRegions(uniqueRegions)
        })
    },[])  
    
    
    const handleRegionsChange = e => 
    {
        if(e.target.value === "All Regions") // all countries
        {
            setSelectedRegion(e.target.value)
            setSelectedCountries(countries)
        }
        else if(e.target.value === "None") // Deal with the two regions Bouvet Island and Heard Island and McDonald Islands that have an empty country.region in the JSON file 
        {
            setSelectedRegion(e.target.value)
            setSelectedCountries(countries.filter(country => country.region === ""))
        }
        else  // countries from one region
        {
            setSelectedRegion(e.target.value)
            setSelectedCountries(countries.filter(country => country.region === e.target.value))
        }
    }
                    
         
    return (  
      <div id="countriesDiv">
          <DropDownRegionsList regions={regions} handleRegionsChange={handleRegionsChange}/>
          <h1>{selectedRegion}</h1>              
          <CountriesTable countries={selectedCountries} region={selectedRegion}/>             
      </div>
    )
}