import React, { useState, useEffect, useContext } from 'react';
import { Container, Card, Row, Col, Button } from 'react-bootstrap';
import { useParams, useNavigate, Link } from 'react-router-dom';
import Swal from 'sweetalert2';
import UserContext from '../UserContext';

export default function ProductView() {
  const { productId } = useParams();
  const navigate = useNavigate();
  const { user } = useContext(UserContext);
  console.log(user);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [price, setPrice] = useState(0);
  const [quantity, setQuantity] = useState(1);


const retrieveDetails = (productId) => {
  
    // Fetch product details from the server
      fetch(`${ process.env.REACT_APP_API_URL }/users/userdetail`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({
          productId: productId
        })
      })
      .then(res => res.json())
      .then( data => {

        console.log(data);

      })

    }
  useEffect(() => {

    console.log(productId);

    fetch(`${ process.env.REACT_APP_API_URL }/products/${productId}`)
    .then(res => res.json())
    .then(data => {

      console.log(data);

      setName(data.name);
      setDescription(data.description);
      setPrice(data.price);

    })

  }, [productId])

  useEffect(() => {
    // Update total price whenever quantity changes
    setTotalPrice(price * quantity);
  }, [quantity, price]);

  const [totalPrice, setTotalPrice] = useState(price);

  const handleIncrement = () => {
    setQuantity(prevQuantity => prevQuantity + 1);
  }

  const handleDecrement = () => {
    if (quantity > 1) {
      setQuantity(prevQuantity => prevQuantity - 1);
    }
  }

  const checkoutOrder = () => {
  fetch(`${process.env.REACT_APP_API_URL}/orders/checkout`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${localStorage.getItem("token")}`
    },
    body: JSON.stringify({
      userId: user.id,
      products: [
        {
          productId: productId,
          quantity: quantity,
        }
      ],
      price: price,
      totalAmount: totalPrice,
      description: description
    })
  })
  .then(res => {
    console.log('Authorization Header:', `Bearer ${localStorage.getItem("token")}`); // Add this line to check the Authorization header
    console.log('Response from server:', res);
    console.log(user);
    console.log(user.id);
    console.log(productId);
    console.log(quantity);
    console.log(price);
    console.log(totalPrice);
    console.log(description);
    return res.json();
  })
  .then(data => {
    console.log(data);
    if (data) {
      Swal.fire({
        title: "Thank you for ordering",
        icon: "success",
        text: "Your order has been placed successfully."
      });
    } else {
      Swal.fire({
        title: "Something went wrong",
        icon: "error",
        text: "Please try again later."
      });
    }
  })
  .catch(error => {
  console.error('Error during checkout:', error);
  Swal.fire({
    title: "Something went wrong",
    icon: "error",
    text: "Please try again later."
  });
});

}


  return (
   <Container className="mt-5">
      <Row>
        <Col lg={{ span: 6, offset: 3 }}>
            <Card className= 'bg-secondary'>
            <Card.Body className= 'bg-info'style={{ borderRadius: '80px' }}>
              <Card.Title>{name}</Card.Title>
              <Card.Subtitle>Description:</Card.Subtitle>
              <Card.Text>{description}</Card.Text>
              <Card.Subtitle>Price:</Card.Subtitle>
              <Card.Text>PhP {price}</Card.Text>
              <div className="d-flex align-items-center mb-3"> {/* Added mb-3 class for bottom margin */}
                <Button variant="outline-secondary" onClick={handleDecrement}>-</Button>
                <input type="number" value={quantity} className="form-control mx-2 custom-quantity"onChange={(e) => setQuantity(Number(e.target.value))} readOnly /> {/* Added custom-quantity class */}
                <Button variant="outline-secondary" onClick={handleIncrement}>+</Button>
              </div>
              <Card.Subtitle>Total Price:</Card.Subtitle>
              <Card.Text>PhP {totalPrice}</Card.Text>
              {(user.id !== null) ?
                              <Button variant="primary" block onClick={checkoutOrder}>Checkout</Button>

                            :
                              <Link className="btn btn-danger btn-block" to="/login" >Log in to Checkout</Link>

                            }
                            
            </Card.Body>
          </Card>
        </Col>
      </Row>
    </Container>
  );
}
