import React from 'react';

type Person = {
	readonly id: number,
  readonly name: string,
  readonly profession: Profession,
  readonly accomplishment: string,
  readonly imageId: string
}

type People = Person[]

type Profession =
	| 'mathematician'
	| 'chemist'
	| 'physicist'
	| 'astrophysicist'

type GroupedProfession<U extends Profession> = {
	[Key in U as `${Key}s`]: Person[];
} & { everyone: Person[]; }

const people: People = [{
  id: 0,
  name: 'Creola Katherine Johnson',
  profession: 'mathematician',
  accomplishment: 'spaceflight calculations',
  imageId: 'MK3eW3A',
}, {
  id: 1,
  name: 'Mario José Molina-Pasquel Henríquez',
  profession: 'chemist',
  accomplishment: 'discovery of Arctic ozone hole',
  imageId: 'mynHUSa',
}, {
  id: 2,
  name: 'Mohammad Abdus Salam',
  profession: 'physicist',
  accomplishment: 'electromagnetism theory',
  imageId: 'bE7W1ji',
}, {
  id: 3,
  name: 'Percy Lavon Julian',
  profession: 'chemist',
  accomplishment: 'pioneering cortisone drugs, steroids and birth control pills',
  imageId: 'IOjWm71',
}, {
  id: 4,
  name: 'Subrahmanyan Chandrasekhar',
  profession: 'astrophysicist',
  accomplishment: 'white dwarf star mass calculations',
  imageId: 'lrWQx8l',
}];

export function getImageUrl(person: Person) {
  return (
    'https://i.imgur.com/' +
    person.imageId +
    's.jpg'
  );
}

type ListPeopleProps = {
	title: string;
	people: People;
}

const ListPeople: React.FC<ListPeopleProps> = ({title, people}) => {
  const listItems = people.map(person =>
    <li key={person.id}>
      <img
        src={getImageUrl(person)}
        alt={person.name}
      />
      <p>
        <b>{person.name}:</b>
        {' ' + person.profession + ' '}
        known for {person.accomplishment}
      </p>
    </li>,
  );
  return (
    <article>
      <h1>{title}</h1>
      <ul>{listItems}</ul>
    </article>
  );
};

export default function List() {
  const {everyone, chemists } = people.reduce((acc, p) => {
    if(p.profession === 'chemist') acc.chemists.push(p);
    else acc.everyone.push(p);
    return acc;
  }, {chemists:[], everyone:[]} as unknown as GroupedProfession<'chemist'>);

  return (
    <React.Fragment>
      <ListPeople title='Scientists' people={everyone} />
      <ListPeople title='Chemists' people={chemists} />
    </React.Fragment>
  );
}

