import { useNavigate, useParams } from 'react-router-dom';
import DrugForm from '../components/Shared/DrugForm';
import Header from '../components/Shared/Header';
import axios from 'axios';
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import Drug from '../interfaces/Drug';
import { getDrugById } from '../redux/selectors';
import { RootState } from '../redux/store';

const Update = () => {
  const id = parseInt(useParams().id ?? '-1');
  const [drug, setDrug] = useState<Drug | null>(null);
  const navigate = useNavigate();
  const potentialDrug = useSelector((state: RootState) =>
    getDrugById(state, id)
  );

  useEffect(() => {
    const fetchDrugById = async (id: number) => {
      try {
        const drug = await axios.get<Drug>(
          `https://silkroadapi.azurewebsites.net/Drug/get-drug/${id}`,
          { withCredentials: true }
        );
        setDrug(drug.data);
        console.log(drug);
      } catch (error) {
        console.error(error);
        navigate('/error');
      }
    };
    if (potentialDrug) setDrug(potentialDrug);
    else fetchDrugById(id);
  }, [id, navigate, potentialDrug]);
  return (
    drug && (
      <>
        <Header />
        <DrugForm updateDrug={drug} />
      </>
    )
  );
};

export default Update;
