import React, { useState, useEffect } from 'react';
import api from '../utils/api';

// Product Search Dropdown Component (reused from OrderEditDialog)
const ProductSearchDropdown = ({ products, value, onChange }) => {
    const [searchTerm, setSearchTerm] = useState('');
    const [isOpen, setIsOpen] = useState(false);
    const [filteredProducts, setFilteredProducts] = useState(products);

    useEffect(() => {
        const filtered = products.filter(product =>
            product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            (product.sku && product.sku.toLowerCase().includes(searchTerm.toLowerCase()))
        );
        setFilteredProducts(filtered);
    }, [searchTerm, products]);

    const selectedProduct = products.find(p => p.id === parseInt(value));

    return (
        <div className="product-search-dropdown">
            <div className="search-input-container">
                <input
                    type="text"
                    placeholder="Search products..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    onFocus={() => setIsOpen(true)}
                    className="form-control"
                />
                {selectedProduct && (
                    <div className="selected-product-info">
                        Selected: {selectedProduct.name} - ${selectedProduct.price}
                    </div>
                )}
            </div>

            {isOpen && (
                <div className="dropdown-menu">
                    <div className="dropdown-header">
                        <span>Select a product ({filteredProducts.length} found)</span>
                        <button
                            type="button"
                            onClick={() => setIsOpen(false)}
                            className="close-btn"
                        >
                            ×
                        </button>
                    </div>
                    <div className="dropdown-items">
                        {filteredProducts.length === 0 ? (
                            <div className="dropdown-item disabled">
                                No products found
                            </div>
                        ) : (
                            filteredProducts.map(product => (
                                <div
                                    key={product.id}
                                    className={`dropdown-item ${value === product.id.toString() ? 'selected' : ''}`}
                                    onClick={() => {
                                        onChange(product.id.toString());
                                        setIsOpen(false);
                                        setSearchTerm('');
                                    }}
                                >
                                    <div className="product-info">
                                        <div className="product-name">{product.name}</div>
                                        <div className="product-details">
                                            SKU: {product.sku || 'N/A'} | Price: ${product.price}
                                        </div>
                                    </div>
                                </div>
                            ))
                        )}
                    </div>
                </div>
            )}
        </div>
    );
};

const OrderCreateDialog = ({ open, onClose, onOrderCreated }) => {
    const [loading, setLoading] = useState(false);
    const [customers, setCustomers] = useState([]);
    const [products, setProducts] = useState([]);
    const [orderStatuses, setOrderStatuses] = useState([]);
    const [paymentMethods, setPaymentMethods] = useState([]);
    const [countries, setCountries] = useState([]);

    const [orderData, setOrderData] = useState({
        customer_id: '',
        status: 'pending',
        payment_method: '',
        payment_method_title: '',
        customer_note: '',
        billing: {
            first_name: '',
            last_name: '',
            company: '',
            address_1: '',
            address_2: '',
            city: '',
            state: '',
            postcode: '',
            country: '',
            email: '',
            phone: ''
        },
        shipping: {
            first_name: '',
            last_name: '',
            company: '',
            address_1: '',
            address_2: '',
            city: '',
            state: '',
            postcode: '',
            country: ''
        },
        line_items: []
    });

    const [newLineItem, setNewLineItem] = useState({
        product_id: '',
        quantity: 1,
        total: 0
    });

    const [activeTab, setActiveTab] = useState('general');
    const [copyBillingToShipping, setCopyBillingToShipping] = useState(false);

    useEffect(() => {
        if (open) {
            loadInitialData();
        }
    }, [open]);

    useEffect(() => {
        if (copyBillingToShipping) {
            setOrderData(prev => ({
                ...prev,
                shipping: {
                    ...prev.billing,
                    email: '', // Don't copy email to shipping
                    phone: ''  // Don't copy phone to shipping
                }
            }));
        }
    }, [copyBillingToShipping, orderData.billing]);

    const loadInitialData = async () => {
        try {
            setLoading(true);

            const [customersRes, productsRes, statusesRes, methodsRes, countriesRes] = await Promise.all([
                api.getCustomers(),
                api.getProducts({ per_page: 100 }),
                api.getOrderStatuses(),
                api.getPaymentMethods(),
                api.getCountries()
            ]);

            if (customersRes.success) setCustomers(customersRes.customers || []);
            if (productsRes.success) setProducts(productsRes.products || []);
            if (statusesRes.success) setOrderStatuses(statusesRes.statuses || []);
            if (methodsRes.success) setPaymentMethods(methodsRes.payment_methods || []);
            if (countriesRes.success) setCountries(countriesRes.countries || []);

        } catch (error) {
            console.error('Error loading initial data:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleInputChange = (section, field, value) => {
        if (section) {
            setOrderData(prev => ({
                ...prev,
                [section]: {
                    ...prev[section],
                    [field]: value
                }
            }));
        } else {
            setOrderData(prev => ({
                ...prev,
                [field]: value
            }));
        }
    };

    const handleCustomerChange = (customerId) => {
        const customer = customers.find(c => c.id === parseInt(customerId));
        if (customer) {
            setOrderData(prev => ({
                ...prev,
                customer_id: customerId,
                billing: {
                    ...prev.billing,
                    first_name: customer.first_name || '',
                    last_name: customer.last_name || '',
                    email: customer.email || ''
                }
            }));
        } else {
            setOrderData(prev => ({
                ...prev,
                customer_id: customerId
            }));
        }
    };

    const addLineItem = () => {
        if (!newLineItem.product_id || newLineItem.quantity <= 0) {
            return;
        }

        const product = products.find(p => p.id === parseInt(newLineItem.product_id));
        if (!product) return;

        const lineItem = {
            product_id: parseInt(newLineItem.product_id),
            name: product.name,
            quantity: parseInt(newLineItem.quantity),
            total: newLineItem.total || (product.price * newLineItem.quantity),
            price: product.price
        };

        setOrderData(prev => ({
            ...prev,
            line_items: [...prev.line_items, lineItem]
        }));

        setNewLineItem({
            product_id: '',
            quantity: 1,
            total: 0
        });
    };

    const removeLineItem = (index) => {
        setOrderData(prev => ({
            ...prev,
            line_items: prev.line_items.filter((_, i) => i !== index)
        }));
    };

    const updateLineItem = (index, field, value) => {
        setOrderData(prev => ({
            ...prev,
            line_items: prev.line_items.map((item, i) =>
                i === index ? { ...item, [field]: value } : item
            )
        }));
    };

    const calculateTotal = () => {
        return orderData.line_items.reduce((total, item) => total + parseFloat(item.total || 0), 0);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        if (orderData.line_items.length === 0) {
            alert('Please add at least one product to the order');
            return;
        }

        try {
            setLoading(true);
            const response = await api.createOrder(orderData);

            if (response.success) {
                onOrderCreated(response);
                onClose();
                // Reset form
                setOrderData({
                    customer_id: '',
                    status: 'pending',
                    payment_method: '',
                    payment_method_title: '',
                    customer_note: '',
                    billing: {
                        first_name: '', last_name: '', company: '', address_1: '', address_2: '',
                        city: '', state: '', postcode: '', country: '', email: '', phone: ''
                    },
                    shipping: {
                        first_name: '', last_name: '', company: '', address_1: '', address_2: '',
                        city: '', state: '', postcode: '', country: ''
                    },
                    line_items: []
                });
                setActiveTab('general');
            } else {
                throw new Error(response.message || 'Failed to create order');
            }
        } catch (error) {
            alert('Error creating order: ' + error.message);
        } finally {
            setLoading(false);
        }
    };

    if (!open) return null;

    return (
        <div className="modal-overlay">
            <div className="modal-dialog modal-lg">
                <div className="modal-content">
                    <div className="modal-header">
                        <h2>Create New Order</h2>
                        <button className="modal-close" onClick={onClose}>×</button>
                    </div>

                    <form onSubmit={handleSubmit}>
                        <div className="modal-body">
                            {/* Tab Navigation */}
                            <div className="tab-navigation mb-4">
                                <button
                                    type="button"
                                    className={`tab-button ${activeTab === 'general' ? 'active' : ''}`}
                                    onClick={() => setActiveTab('general')}
                                >
                                    General
                                </button>
                                <button
                                    type="button"
                                    className={`tab-button ${activeTab === 'products' ? 'active' : ''}`}
                                    onClick={() => setActiveTab('products')}
                                >
                                    Products
                                </button>
                                <button
                                    type="button"
                                    className={`tab-button ${activeTab === 'billing' ? 'active' : ''}`}
                                    onClick={() => setActiveTab('billing')}
                                >
                                    Billing
                                </button>
                                <button
                                    type="button"
                                    className={`tab-button ${activeTab === 'shipping' ? 'active' : ''}`}
                                    onClick={() => setActiveTab('shipping')}
                                >
                                    Shipping
                                </button>
                            </div>

                            {/* General Tab */}
                            {activeTab === 'general' && (
                                <div className="tab-content">
                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="form-group">
                                            <label>Customer *</label>
                                            <select
                                                value={orderData.customer_id}
                                                onChange={(e) => handleCustomerChange(e.target.value)}
                                                required
                                            >
                                                <option value="">Select Customer</option>
                                                {customers.map(customer => (
                                                    <option key={customer.id} value={customer.id}>
                                                        {customer.first_name} {customer.last_name} ({customer.email})
                                                    </option>
                                                ))}
                                            </select>
                                        </div>

                                        <div className="form-group">
                                            <label>Order Status</label>
                                            <select
                                                value={orderData.status}
                                                onChange={(e) => handleInputChange(null, 'status', e.target.value)}
                                            >
                                                {orderStatuses.map(status => (
                                                    <option key={status.status} value={status.status}>
                                                        {status.label}
                                                    </option>
                                                ))}
                                            </select>
                                        </div>

                                        <div className="form-group">
                                            <label>Payment Method</label>
                                            <select
                                                value={orderData.payment_method}
                                                onChange={(e) => {
                                                    const method = paymentMethods.find(m => m.id === e.target.value);
                                                    handleInputChange(null, 'payment_method', e.target.value);
                                                    handleInputChange(null, 'payment_method_title', method?.title || e.target.value);
                                                }}
                                            >
                                                <option value="">Select Payment Method</option>
                                                {paymentMethods.map(method => (
                                                    <option key={method.id} value={method.id}>
                                                        {method.title}
                                                    </option>
                                                ))}
                                            </select>
                                        </div>

                                        <div className="form-group col-span-2">
                                            <label>Customer Note</label>
                                            <textarea
                                                value={orderData.customer_note}
                                                onChange={(e) => handleInputChange(null, 'customer_note', e.target.value)}
                                                rows="3"
                                                placeholder="Add a note for this order..."
                                            />
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* Products Tab */}
                            {activeTab === 'products' && (
                                <div className="tab-content">
                                    {/* Add Product Form */}
                                    <div className="card mb-4">
                                        <div className="card-header">
                                            <h3>Add Product</h3>
                                        </div>
                                        <div className="card-content">
                                            <div className="grid grid-cols-4 gap-4 items-end">
                                                <div className="form-group">
                                                    <label>Product</label>
                                                    <ProductSearchDropdown
                                                        products={products}
                                                        value={newLineItem.product_id}
                                                        onChange={(productId) => {
                                                            const product = products.find(p => p.id === parseInt(productId));
                                                            setNewLineItem(prev => ({
                                                                ...prev,
                                                                product_id: productId,
                                                                total: product ? product.price * prev.quantity : 0
                                                            }));
                                                        }}
                                                    />
                                                </div>
                                                <div className="form-group">
                                                    <label>Quantity</label>
                                                    <input
                                                        type="number"
                                                        min="1"
                                                        value={newLineItem.quantity}
                                                        onChange={(e) => {
                                                            const quantity = parseInt(e.target.value) || 1;
                                                            const product = products.find(p => p.id === parseInt(newLineItem.product_id));
                                                            setNewLineItem(prev => ({
                                                                ...prev,
                                                                quantity,
                                                                total: product ? product.price * quantity : 0
                                                            }));
                                                        }}
                                                    />
                                                </div>
                                                <div className="form-group">
                                                    <label>Total</label>
                                                    <input
                                                        type="number"
                                                        step="0.01"
                                                        value={newLineItem.total}
                                                        onChange={(e) => setNewLineItem(prev => ({
                                                            ...prev,
                                                            total: parseFloat(e.target.value) || 0
                                                        }))}
                                                    />
                                                </div>
                                                <div className="form-group">
                                                    <button
                                                        type="button"
                                                        className="btn btn-primary"
                                                        onClick={addLineItem}
                                                    >
                                                        Add Product
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Order Items */}
                                    <div className="card">
                                        <div className="card-header">
                                            <h3>Order Items</h3>
                                        </div>
                                        <div className="card-content">
                                            {orderData.line_items.length === 0 ? (
                                                <p className="text-gray-500">No products added yet</p>
                                            ) : (
                                                <div className="table-container">
                                                    <table>
                                                        <thead>
                                                            <tr>
                                                                <th>Product</th>
                                                                <th>Quantity</th>
                                                                <th>Price</th>
                                                                <th>Total</th>
                                                                <th>Actions</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            {orderData.line_items.map((item, index) => (
                                                                <tr key={index}>
                                                                    <td>{item.name}</td>
                                                                    <td>
                                                                        <input
                                                                            type="number"
                                                                            min="1"
                                                                            value={item.quantity}
                                                                            onChange={(e) => updateLineItem(index, 'quantity', parseInt(e.target.value) || 1)}
                                                                            className="w-20"
                                                                        />
                                                                    </td>
                                                                    <td>${item.price}</td>
                                                                    <td>
                                                                        <input
                                                                            type="number"
                                                                            step="0.01"
                                                                            value={item.total}
                                                                            onChange={(e) => updateLineItem(index, 'total', parseFloat(e.target.value) || 0)}
                                                                            className="w-24"
                                                                        />
                                                                    </td>
                                                                    <td>
                                                                        <button
                                                                            type="button"
                                                                            className="btn btn-danger btn-sm"
                                                                            onClick={() => removeLineItem(index)}
                                                                        >
                                                                            Remove
                                                                        </button>
                                                                    </td>
                                                                </tr>
                                                            ))}
                                                        </tbody>
                                                        <tfoot>
                                                            <tr>
                                                                <td colSpan="3"><strong>Total:</strong></td>
                                                                <td><strong>${calculateTotal().toFixed(2)}</strong></td>
                                                                <td></td>
                                                            </tr>
                                                        </tfoot>
                                                    </table>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* Billing Tab */}
                            {activeTab === 'billing' && (
                                <div className="tab-content">
                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="form-group">
                                            <label>First Name</label>
                                            <input
                                                type="text"
                                                value={orderData.billing.first_name}
                                                onChange={(e) => handleInputChange('billing', 'first_name', e.target.value)}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>Last Name</label>
                                            <input
                                                type="text"
                                                value={orderData.billing.last_name}
                                                onChange={(e) => handleInputChange('billing', 'last_name', e.target.value)}
                                            />
                                        </div>
                                        <div className="form-group col-span-2">
                                            <label>Company</label>
                                            <input
                                                type="text"
                                                value={orderData.billing.company}
                                                onChange={(e) => handleInputChange('billing', 'company', e.target.value)}
                                            />
                                        </div>
                                        <div className="form-group col-span-2">
                                            <label>Address Line 1</label>
                                            <input
                                                type="text"
                                                value={orderData.billing.address_1}
                                                onChange={(e) => handleInputChange('billing', 'address_1', e.target.value)}
                                            />
                                        </div>
                                        <div className="form-group col-span-2">
                                            <label>Address Line 2</label>
                                            <input
                                                type="text"
                                                value={orderData.billing.address_2}
                                                onChange={(e) => handleInputChange('billing', 'address_2', e.target.value)}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>City</label>
                                            <input
                                                type="text"
                                                value={orderData.billing.city}
                                                onChange={(e) => handleInputChange('billing', 'city', e.target.value)}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>State/Province</label>
                                            <input
                                                type="text"
                                                value={orderData.billing.state}
                                                onChange={(e) => handleInputChange('billing', 'state', e.target.value)}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>Postal Code</label>
                                            <input
                                                type="text"
                                                value={orderData.billing.postcode}
                                                onChange={(e) => handleInputChange('billing', 'postcode', e.target.value)}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>Country</label>
                                            <select
                                                value={orderData.billing.country}
                                                onChange={(e) => handleInputChange('billing', 'country', e.target.value)}
                                            >
                                                <option value="">Select Country</option>
                                                {countries.map(country => (
                                                    <option key={country.code} value={country.code}>
                                                        {country.name}
                                                    </option>
                                                ))}
                                            </select>
                                        </div>
                                        <div className="form-group">
                                            <label>Email</label>
                                            <input
                                                type="email"
                                                value={orderData.billing.email}
                                                onChange={(e) => handleInputChange('billing', 'email', e.target.value)}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>Phone</label>
                                            <input
                                                type="tel"
                                                value={orderData.billing.phone}
                                                onChange={(e) => handleInputChange('billing', 'phone', e.target.value)}
                                            />
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* Shipping Tab */}
                            {activeTab === 'shipping' && (
                                <div className="tab-content">
                                    <div className="form-group mb-4">
                                        <label className="checkbox-label">
                                            <input
                                                type="checkbox"
                                                checked={copyBillingToShipping}
                                                onChange={(e) => setCopyBillingToShipping(e.target.checked)}
                                            />
                                            Copy billing address to shipping address
                                        </label>
                                    </div>

                                    <div className="grid grid-cols-2 gap-4">
                                        <div className="form-group">
                                            <label>First Name</label>
                                            <input
                                                type="text"
                                                value={orderData.shipping.first_name}
                                                onChange={(e) => handleInputChange('shipping', 'first_name', e.target.value)}
                                                disabled={copyBillingToShipping}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>Last Name</label>
                                            <input
                                                type="text"
                                                value={orderData.shipping.last_name}
                                                onChange={(e) => handleInputChange('shipping', 'last_name', e.target.value)}
                                                disabled={copyBillingToShipping}
                                            />
                                        </div>
                                        <div className="form-group col-span-2">
                                            <label>Company</label>
                                            <input
                                                type="text"
                                                value={orderData.shipping.company}
                                                onChange={(e) => handleInputChange('shipping', 'company', e.target.value)}
                                                disabled={copyBillingToShipping}
                                            />
                                        </div>
                                        <div className="form-group col-span-2">
                                            <label>Address Line 1</label>
                                            <input
                                                type="text"
                                                value={orderData.shipping.address_1}
                                                onChange={(e) => handleInputChange('shipping', 'address_1', e.target.value)}
                                                disabled={copyBillingToShipping}
                                            />
                                        </div>
                                        <div className="form-group col-span-2">
                                            <label>Address Line 2</label>
                                            <input
                                                type="text"
                                                value={orderData.shipping.address_2}
                                                onChange={(e) => handleInputChange('shipping', 'address_2', e.target.value)}
                                                disabled={copyBillingToShipping}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>City</label>
                                            <input
                                                type="text"
                                                value={orderData.shipping.city}
                                                onChange={(e) => handleInputChange('shipping', 'city', e.target.value)}
                                                disabled={copyBillingToShipping}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>State/Province</label>
                                            <input
                                                type="text"
                                                value={orderData.shipping.state}
                                                onChange={(e) => handleInputChange('shipping', 'state', e.target.value)}
                                                disabled={copyBillingToShipping}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>Postal Code</label>
                                            <input
                                                type="text"
                                                value={orderData.shipping.postcode}
                                                onChange={(e) => handleInputChange('shipping', 'postcode', e.target.value)}
                                                disabled={copyBillingToShipping}
                                            />
                                        </div>
                                        <div className="form-group">
                                            <label>Country</label>
                                            <select
                                                value={orderData.shipping.country}
                                                onChange={(e) => handleInputChange('shipping', 'country', e.target.value)}
                                                disabled={copyBillingToShipping}
                                            >
                                                <option value="">Select Country</option>
                                                {countries.map(country => (
                                                    <option key={country.code} value={country.code}>
                                                        {country.name}
                                                    </option>
                                                ))}
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>

                        <div className="modal-footer">
                            <button
                                type="button"
                                className="btn btn-secondary"
                                onClick={onClose}
                                disabled={loading}
                            >
                                Cancel
                            </button>
                            <button
                                type="submit"
                                className={`btn btn-primary ${loading ? 'btn-loading' : ''}`}
                                disabled={loading || orderData.line_items.length === 0}
                            >
                                {loading ? (
                                    <>
                                        <div className="spinner"></div>
                                        Creating Order...
                                    </>
                                ) : (
                                    'Create Order'
                                )}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
};

export default OrderCreateDialog;