import React, { useState, useEffect } from 'react';
import api from '../utils/api';
import ConfirmDialog from './ConfirmDialog';

// Product Search Dropdown Component
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 OrderEditDialog = ({ open, order, onClose, onOrderUpdated }) => {
    const [loading, setLoading] = useState(false);
    const [orderStatuses, setOrderStatuses] = useState([]);
    const [paymentMethods, setPaymentMethods] = useState([]);
    const [countries, setCountries] = useState([]);
    const [products, setProducts] = useState([]);

    const [orderData, setOrderData] = useState({
        status: '',
        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 [activeTab, setActiveTab] = useState('general');
    const [copyBillingToShipping, setCopyBillingToShipping] = useState(false);
    const [newLineItem, setNewLineItem] = useState({
        product_id: '',
        quantity: 1,
        total: 0
    });
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);

    useEffect(() => {
        if (open && order) {
            loadInitialData();
            populateOrderData();
        }
    }, [open, order]);

    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 {
            const [statusesRes, methodsRes, countriesRes, productsRes] = await Promise.all([
                api.getOrderStatuses(),
                api.getPaymentMethods(),
                api.getCountries(),
                api.getProducts({ per_page: 100 })
            ]);

            if (statusesRes.success) setOrderStatuses(statusesRes.statuses || []);
            if (methodsRes.success) setPaymentMethods(methodsRes.payment_methods || []);
            if (countriesRes.success) setCountries(countriesRes.countries || []);
            if (productsRes.success) setProducts(productsRes.products || []);

        } catch (error) {
            console.error('Error loading initial data:', error);
        }
    };

    const populateOrderData = async () => {
        try {
            setLoading(true);

            // Get full order details
            const response = await api.getOrder(order.id);

            if (response.success) {
                const fullOrder = response.order;
                setOrderData({
                    status: fullOrder.status || '',
                    payment_method: fullOrder.payment_method || '',
                    payment_method_title: fullOrder.payment_method_title || '',
                    customer_note: fullOrder.customer_note || '',
                    billing: fullOrder.billing || {},
                    shipping: fullOrder.shipping || {},
                    line_items: fullOrder.line_items || []
                });
            }
        } catch (error) {
            console.error('Error loading order details:', 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 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();

        try {
            setLoading(true);
            const response = await api.updateOrder(order.id, orderData);

            if (response.success) {
                onOrderUpdated(response);
                onClose();
            } else {
                throw new Error(response.message || 'Failed to update order');
            }
        } catch (error) {
            alert('Error updating order: ' + error.message);
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = () => {
        setDeleteDialogOpen(true);
    };

    const confirmDelete = async () => {
        try {
            setLoading(true);
            const response = await api.deleteOrder(order.id, false); // Move to trash

            if (response.success) {
                onOrderUpdated({ deleted: true });
                onClose();
            } else {
                throw new Error(response.message || 'Failed to delete order');
            }
        } catch (error) {
            alert('Error deleting order: ' + error.message);
        } finally {
            setLoading(false);
        }
    };

    if (!open || !order) return null;

    return (
        <div className="modal-overlay">
            <div className="modal-dialog modal-lg">
                <div className="modal-content">
                    <div className="modal-header">
                        <h2>Edit Order #{order.number || order.id}</h2>
                        <button className="modal-close" onClick={onClose}>×</button>
                    </div>

                    <form onSubmit={handleSubmit}>
                        <div className="modal-body">
                            {/* Order Info */}
                            <div className="order-info-bar mb-4 p-3 bg-gray-50 rounded">
                                <div className="grid grid-cols-4 gap-4 text-sm">
                                    <div>
                                        <strong>Order ID:</strong> #{order.number || order.id}
                                    </div>
                                    <div>
                                        <strong>Date:</strong> {new Date(order.date_created).toLocaleDateString()}
                                    </div>
                                    <div>
                                        <strong>Customer:</strong> {order.customer?.name || 'N/A'}
                                    </div>
                                    <div>
                                        <strong>Total:</strong> ${order.total}
                                    </div>
                                </div>
                            </div>

                            {/* 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>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 in this order</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) => {
                                                                                const quantity = parseInt(e.target.value) || 1;
                                                                                const newTotal = item.price * quantity;
                                                                                updateLineItem(index, 'quantity', quantity);
                                                                                updateLineItem(index, 'total', newTotal);
                                                                            }}
                                                                            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-danger"
                                onClick={handleDelete}
                                disabled={loading}
                            >
                                Delete Order
                            </button>
                            <div className="flex gap-2">
                                <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}
                                >
                                    {loading ? (
                                        <>
                                            <div className="spinner"></div>
                                            Updating Order...
                                        </>
                                    ) : (
                                        'Update Order'
                                    )}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            {/* Delete Confirmation Dialog */}
            <ConfirmDialog
                isOpen={deleteDialogOpen}
                onClose={() => setDeleteDialogOpen(false)}
                onConfirm={confirmDelete}
                title="Confirm Delete"
                confirmText="Delete Order"
                confirmButtonClass="btn-danger"
            >
                <p>Are you sure you want to delete order <strong>#{order?.number || order?.id}</strong>?</p>
                <p className="text-danger">This action cannot be undone.</p>
            </ConfirmDialog>
        </div>
    );
};

export default OrderEditDialog;