import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faChevronLeft } from '@fortawesome/free-solid-svg-icons';
import Sidebar from '../sidebar/Sidebar';
import '../../styles/Customize.css';

const Customize = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [style, setStyle] = useState('');
  const [material, setMaterial] = useState('');
  const [productImage, setProductImage] = useState('');

  useEffect(() => {
    // Fetch the product image URL based on the product ID
    const fetchProductImage = async () => {
      try {
        const response = await fetch(`/api/products/${id}`);
        const data = await response.json();
        setProductImage(data.imageUrl); // Assume `data.imageUrl` is the URL of the product image
      } catch (error) {
        console.error('Error fetching product image:', error);
      }
    };

    fetchProductImage();
  }, [id]);

  const handleStyleChange = (event) => {
    setStyle(event.target.value);
  };

  const handleMaterialChange = (event) => {
    setMaterial(event.target.value);
  };

  const handleSave = () => {
    const customization = {
      productId: id,
      style,
      material,
    };

    navigate('/setmeasurements');

    fetch('/api/saveCustomization', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(customization),
    })
      .then(response => response.json())
      .then(data => {
        console.log('Success:', data);
        navigate('/setmeasurements'); // Redirect to the Set Measurements page
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  };

  return (
    <div className="flex h-screen">
      {/* Sidebar */}
      <Sidebar />

      {/* Main content */}
      <div className="flex-grow flex flex-col">
        {/* Header */}
        <div className="bg-white p-4 flex items-center ">
          <Link to="/CategoryList">
            <FontAwesomeIcon icon={faChevronLeft} className="text-gray-700" />
          </Link>
          <h1 className="ml-4 text-2xl font-medium text-gray-700">Customize Product</h1>
        </div>

        {/* Content */}
        <div className="flex-grow flex items-stretch p-8">
          {/* Customization Options */}
          <div className="bg-white p-6 rounded-lg w-1/3 mr-4">
            <h2 className="text-lg font-medium text-gray-700 mb-4">Customize</h2>

            {/* Style Selection */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700">
                Style:
                <select
                  value={style}
                  onChange={handleStyleChange}
                  className="mt-1 block w-full py-2 px-3 border border-gray-300 rounded-md"
                >
                  <option value="">Select style</option>
                  <option value="collar">Collar</option>
                  <option value="cuff">Cuff</option>
                  <option value="placket">Placket</option>
                </select>
              </label>
            </div>

            {/* Material Selection */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700">
                Material:
                <select
                  value={material}
                  onChange={handleMaterialChange}
                  className="mt-1 block w-full py-2 px-3 border border-gray-300 rounded-md"
                >
                  <option value="">Select material</option>
                  <option value="cotton">Cotton</option>
                  <option value="polyester">Polyester</option>
                  <option value="linen">Linen</option>
                </select>
              </label>
            </div>

            {/* Save Button */}
            <button
              onClick={handleSave}
              className="w-full py-2 px-4"
            >
              Save Style and Material
            </button>
          </div>

          {/* Product Image */}
          <div className="bg-white p-6 rounded-lg flex-grow">
            {productImage ? (
              <img src={productImage} alt="Product" className="w-full h-auto rounded-lg" />
            ) : (
              <p className="ml-4 text-xl text-gray-700" >Loading image...</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Customize;
