import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import { useNavigate, useParams } from 'react-router-dom';
import { useEffect, useState } from 'react';
import Divider from '@mui/material/Divider';
import axios from 'axios';
import Manufacturer from '../../interfaces/Manufacturer';

export default function DrugDetails() {
  const navigate = useNavigate();

  const id = parseInt(useParams().id ?? '0');

  const [drug, setDrug] = useState<Manufacturer | null>(null);

  useEffect(() => {
    const fetchDrugById = async (id: number) => {
      try {
        const drug = await axios.get<Manufacturer>(
          `https://silkroadapi.azurewebsites.net/Manufacturer/get-manufacturer/${id}`,
          { withCredentials: true }
        );
        setDrug(drug.data);
        console.log(drug);
      } catch (error) {
        console.error(error);
        navigate('/error');
      }
    };
    fetchDrugById(id);
  }, [id, navigate]);

  const handleBackButton = () => {
    navigate(-1);
  };

  return (
    !!drug && (
      <div style={{ marginLeft: '15%', marginRight: '15%' }}>
        <Card sx={{ maxWidth: 1600 }}>
          <CardContent>
            <Typography variant='h3' gutterBottom>
              {drug?.name}
            </Typography>
            <Typography variant='h4' component='div'>
              {drug?.address}
            </Typography>
            <Typography sx={{ mb: 1.5 }} color='text.secondary'>
              {drug?.contact}
            </Typography>
            <Divider />
            <Typography variant='body1'>
              Total Count:
              <br />
              {drug?.totalCount}
            </Typography>
          </CardContent>
          <CardActions>
            <Button size='small' onClick={handleBackButton}>
              Back
            </Button>
          </CardActions>
        </Card>
      </div>
    )
  );
}
