// TEST ARTIFACT: Order Form with Intentional Bugs
// This component has several issues for Ghost Mechanic to diagnose

import React, { useState } from 'react';

interface OrderFormProps {
  customerId: string;
  products: Product[];
}

interface Product {
  sku: string;
  name: string;
  price: number;
  stock: number;
}

interface OrderItem {
  sku: string;
  quantity: number;
}

export function OrderForm({ customerId, products }: OrderFormProps) {
  const [items, setItems] = useState<OrderItem[]>([]);
  const [selectedSku, setSelectedSku] = useState('');
  const [quantity, setQuantity] = useState(1);
  const [notes, setNotes] = useState('');
  // BUG #1: Missing loading state
  // const [isLoading, setIsLoading] = useState(false);

  const addItem = () => {
    // BUG #2: Direct state mutation instead of creating new array
    items.push({ sku: selectedSku, quantity });
    setItems(items); // This won't trigger re-render!
  };

  const submitOrder = async (formData: any) => {
    // This is async but will be called without await
    const response = await fetch('/api/orders', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData)
    });
    return response.json();
  };

  const handleSubmit = () => {
    // BUG #3: No validation - submits even with empty items
    // BUG #4: Calling async function without await - no loading feedback
    submitOrder({
      customerId,
      items,
      notes
    });
    // User sees nothing happen!
  };

  const getTotal = () => {
    return items.reduce((sum, item) => {
      // BUG #5: Potential undefined access - product might not exist
      const product = products.find(p => p.sku === item.sku);
      return sum + (product.price * item.quantity); // Crashes if product undefined!
    }, 0);
  };

  return (
    <div className="order-form">
      <h2>New Order for Customer {customerId}</h2>
      
      <div className="product-selector">
        <select 
          value={selectedSku}
          onChange={(e) => setSelectedSku(e.target.value)}
        >
          <option value="">Select a product</option>
          {products.map(product => (
            // BUG #6: Missing key prop
            <option value={product.sku}>
              {product.name} - ${product.price}
            </option>
          ))}
        </select>
        
        <input
          type="number"
          value={quantity}
          onChange={(e) => setQuantity(parseInt(e.target.value))}
          min="1"
        />
        
        <button onClick={addItem}>Add Item</button>
      </div>

      <div className="order-items">
        <h3>Order Items</h3>
        {items.length === 0 ? (
          <p>No items added</p>
        ) : (
          <ul>
            {items.map((item, index) => (
              <li key={index}>
                {item.sku} x {item.quantity}
              </li>
            ))}
          </ul>
        )}
      </div>

      <div className="order-notes">
        <textarea
          placeholder="Order notes..."
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
        />
      </div>

      <div className="order-total">
        <strong>Total: ${getTotal().toFixed(2)}</strong>
      </div>

      {/* BUG #4 continuation: onClick calls async without await */}
      <button onClick={handleSubmit}>
        Submit Order
      </button>
    </div>
  );
}
