import React, { useEffect } from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import styles from './ItemForm.module.css';
Form submission:
● Values are sent to the server and stored in memory.
● The request payload should contain only what the user
filled/changed.
○ On create: if a user filled 4 fields, the request payload must
contain only 4 fields.
○ On edit: if a user changed only one field, the request
payload must contain 1 field 
// Define the validation schema using Yup
const schema = yup.object({
  name: yup
    .string()
    .required('Name is required')
    .max(50, 'Max length is 50 characters'),
  category: yup.string().required('Category is required'),
  quantity: yup
    .number()
    .typeError('Quantity must be a number')
    .required('Quantity is required')
    .min(1, 'Quantity must be at least 1'),
  location: yup.string().notRequired(),
  supplier: yup.string().notRequired(),
  supplierLocation: yup.string().notRequired(),
  showPriceDetails: yup
    .string()
    .oneOf(['yes', 'no'], 'Please select an option')
    .required('Please select an option'),
  priceType: yup
    .string()
    .when('showPriceDetails', {
      is: 'yes',
      then: (schema) => schema.required('Price Type is required'),
      otherwise: (schema) => schema.notRequired(),
    }),
  price: yup
    .number()
    .transform((value, originalValue) => (originalValue === '' ? undefined : value))
    .when('showPriceDetails', {
      is: 'yes',
      then: (schema) =>
        schema
          .required('Price is required')
          .typeError('Price must be a number')
          .min(1, 'Price must be at least 1'),
      otherwise: (schema) => schema.notRequired(),
    }),
  endpoints: yup.array().of(
    yup.object({
      endpoint: yup.string().required('Endpoint is required'),
      status: yup.string().required('Status is required'),
    })
  ),
});

export const ItemForm = ({ defaultValues, onSubmit }) => {
  const {
    register,
    handleSubmit,
    watch,
    control,
    formState: { errors },
    reset,
  } = useForm({
    defaultValues,
    resolver: yupResolver(schema),
  });

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'endpoints',
  });

  const showPriceDetails = watch('showPriceDetails') === 'yes';

  useEffect(() => {
    reset(defaultValues);
  }, [defaultValues, reset]);

  // Custom submit handler that logs affected fields
  const handleFormSubmit = (data) => {
    console.log('Submitted data:', data);
    // Additional logging if needed
    onSubmit(data); // Call the original onSubmit prop
  };

  return (
    <div className={styles.formContainer}>
      <form onSubmit={handleSubmit(handleFormSubmit)} className={styles.formWrapper}>
        {/* Basic Information */}
        <div className={`${styles.formGrid} ${styles.grid3}`}>
          {/* Name */}
          <div className={styles.formGroup}>
            <label htmlFor="name">Name*:</label>
            <input
              id="name"
              {...register('name')}
              className={errors.name ? styles.inputError : ''}
            />
            {errors.name && <p className={styles.errorMessage}>{errors.name.message}</p>}
          </div>

          {/* Category */}
          <div className={styles.formGroup}>
            <label htmlFor="category">Category*:</label>
            <select
              id="category"
              {...register('category')}
              className={errors.category ? styles.inputError : ''}
            >
              <option value="">Select category</option>
              <option value="Electronics">Electronics</option>
              <option value="Furniture">Furniture</option>
              <option value="Clothing">Clothing</option>
              <option value="Food">Food</option>
              <option value="Toys">Toys</option>
              <option value="Books">Books</option>
              <option value="Sports">Sports</option>
            </select>
            {errors.category && (
              <p className={styles.errorMessage}>{errors.category.message}</p>
            )}
          </div>

          {/* Quantity */}
          <div className={styles.formGroup}>
            <label htmlFor="quantity">Quantity*:</label>
            <input
              id="quantity"
              type="number"
              {...register('quantity')}
              className={errors.quantity ? styles.inputError : ''}
            />
            {errors.quantity && (
              <p className={styles.errorMessage}>{errors.quantity.message}</p>
            )}
          </div>
        </div>

        {/* Optional Fields */}
        <div className={`${styles.formGrid} ${styles.grid2}`}>
          {/* Supplier */}
          <div className={styles.formGroup}>
            <label htmlFor="supplier">Supplier:</label>
            <input
              id="supplier"
              {...register('supplier')}
              className={errors.supplier ? styles.inputError : ''}
            />
            {errors.supplier && (
              <p className={styles.errorMessage}>{errors.supplier.message}</p>
            )}
          </div>

          {/* Supplier Location */}
          <div className={styles.formGroup}>
            <label htmlFor="supplierLocation">Supplier Location:</label>
            <input
              id="supplierLocation"
              {...register('supplierLocation')}
              className={errors.supplierLocation ? styles.inputError : ''}
            />
            {errors.supplierLocation && (
              <p className={styles.errorMessage}>{errors.supplierLocation.message}</p>
            )}
          </div>
        </div>

        {/* Radio Button to Show Additional Fields */}
        <div className={styles.formGroup}>
          <label>Show Price Details?</label>
          <div className={styles.radioGroup}>
            <label>
              <input
                type="radio"
                value="yes"
                {...register('showPriceDetails')}
                defaultChecked={defaultValues?.showPriceDetails === 'yes'}
              />
              Yes
            </label>
            <label>
              <input
                type="radio"
                value="no"
                {...register('showPriceDetails')}
                defaultChecked={defaultValues?.showPriceDetails !== 'yes'}
              />
              No
            </label>
          </div>
          {errors.showPriceDetails && (
            <p className={styles.errorMessage}>{errors.showPriceDetails.message}</p>
          )}
        </div>

        {/* Additional Price Details */}
        {showPriceDetails && (
          <div className={`${styles.formGrid} ${styles.grid2}`}>
            {/* Price Type */}
            <div className={styles.formGroup}>
              <label htmlFor="priceType">Price Type*:</label>
              <select
                id="priceType"
                {...register('priceType')}
                className={errors.priceType ? styles.inputError : ''}
              >
                <option value="">Select type</option>
                <option value="For Sale">For Sale</option>
                <option value="For Buying">For Buying</option>
              </select>
              {errors.priceType && (
                <p className={styles.errorMessage}>{errors.priceType.message}</p>
              )}
            </div>

            {/* Price */}
            <div className={styles.formGroup}>
              <label htmlFor="price">Price*:</label>
              <input
                id="price"
                type="number"
                {...register('price')}
                className={errors.price ? styles.inputError : ''}
                placeholder="Enter price"
              />
              {errors.price && (
                <p className={styles.errorMessage}>{errors.price.message}</p>
              )}
            </div>
          </div>
        )}

        {/* Endpoints Array Field */}
        <div className={`${styles.formGroup} ${styles.fullWidth}`}>
          <h3>Endpoints</h3>
          {fields.map((field, index) => (
            <div key={field.id} className={`${styles.formGrid} ${styles.grid2}`}>
              {/* Endpoint Name */}
              <div className={styles.formGroup}>
                <label htmlFor={`endpoints.${index}.endpoint`}>Endpoint {index + 1}*:</label>
                <input
                  id={`endpoints.${index}.endpoint`}
                  {...register(`endpoints.${index}.endpoint`)}
                  className={
                    errors.endpoints?.[index]?.endpoint ? styles.inputError : ''
                  }
                />
                {errors.endpoints?.[index]?.endpoint && (
                  <p className={styles.errorMessage}>
                    {errors.endpoints[index].endpoint.message}
                  </p>
                )}
              </div>

              {/* Status */}
              <div className={styles.formGroup}>
                <label htmlFor={`endpoints.${index}.status`}>Status*:</label>
                <select
                  id={`endpoints.${index}.status`}
                  {...register(`endpoints.${index}.status`)}
                  className={
                    errors.endpoints?.[index]?.status ? styles.inputError : ''
                  }
                >
                  <option value="">Select status</option>
                  <option value="Active">Active</option>
                  <option value="Inactive">Inactive</option>
                  <option value="Completed">Completed</option>
                </select>
                {errors.endpoints?.[index]?.status && (
                  <p className={styles.errorMessage}>
                    {errors.endpoints[index].status.message}
                  </p>
                )}
              </div>

              {/* Remove Endpoint Button */}
              <div className={styles.formGroup}>
                <button
                  type="button"
                  className={styles.removeEndpointButton}
                  onClick={() => remove(index)}
                >
                  Remove
                </button>
              </div>
            </div>
          ))}

          {/* Add Endpoint Button */}
          <button
            type="button"
            className={styles.addEndpointButton}
            onClick={() => append({ endpoint: '', status: '' })}
          >
            Add Endpoint
          </button>
        </div>

        {/* Submit Button */}
        <button type="submit" className={styles.actionButton}>
          Submit
        </button>
      </form>
    </div>
  );
};