import React, { useState, useEffect } from 'react';
import { Package, User, Calendar, DollarSign, Trash2, Plus } from 'lucide-react';

export default function OrderDetail() {
  const [orderId, setOrderId] = useState('');
  const [order, setOrder] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  const fetchOrder = async () => {
    if (!orderId) return;
    setLoading(true);
    try {
      const result = await window.mcp.callTool('clover_get_order', {
        orderId,
        expand: 'lineItems,customers,payments',
      });
      setOrder(result);
    } catch (error) {
      console.error('Failed to fetch order:', error);
      alert('Failed to load order');
    } finally {
      setLoading(false);
    }
  };

  const addLineItem = async () => {
    const itemId = prompt('Enter item ID:');
    if (!itemId) return;

    try {
      await window.mcp.callTool('clover_add_line_item', {
        orderId: order.id,
        itemId,
      });
      fetchOrder();
    } catch (error) {
      alert('Failed to add line item');
    }
  };

  const removeLineItem = async (lineItemId: string) => {
    if (!confirm('Remove this item?')) return;

    try {
      await window.mcp.callTool('clover_remove_line_item', {
        orderId: order.id,
        lineItemId,
      });
      fetchOrder();
    } catch (error) {
      alert('Failed to remove line item');
    }
  };

  const fireOrder = async () => {
    if (!confirm('Fire this order to kitchen?')) return;

    try {
      await window.mcp.callTool('clover_fire_order', { orderId: order.id });
      alert('Order fired!');
    } catch (error) {
      alert('Failed to fire order');
    }
  };

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <h1 className="text-3xl font-bold text-gray-900 mb-6">Order Details</h1>

      <div className="bg-white rounded-lg shadow p-6 mb-6">
        <div className="flex gap-4">
          <input
            type="text"
            value={orderId}
            onChange={(e) => setOrderId(e.target.value)}
            placeholder="Enter Order ID"
            className="flex-1 px-4 py-2 border border-gray-300 rounded-lg"
          />
          <button
            onClick={fetchOrder}
            disabled={loading}
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400"
          >
            {loading ? 'Loading...' : 'Load Order'}
          </button>
        </div>
      </div>

      {order && (
        <>
          <div className="bg-white rounded-lg shadow p-6 mb-6">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6 mb-6">
              <InfoItem
                icon={<Package className="w-5 h-5" />}
                label="Order ID"
                value={order.id}
              />
              <InfoItem
                icon={<DollarSign className="w-5 h-5" />}
                label="Total"
                value={`$${((order.total || 0) / 100).toFixed(2)}`}
              />
              <InfoItem
                icon={<Calendar className="w-5 h-5" />}
                label="State"
                value={order.state}
              />
              <InfoItem
                icon={<User className="w-5 h-5" />}
                label="Currency"
                value={order.currency}
              />
            </div>

            <div className="flex gap-4">
              <button
                onClick={addLineItem}
                className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2"
              >
                <Plus className="w-4 h-4" />
                Add Item
              </button>
              <button
                onClick={fireOrder}
                className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700"
              >
                Fire Order
              </button>
            </div>
          </div>

          <div className="bg-white rounded-lg shadow p-6">
            <h2 className="text-xl font-semibold mb-4">Line Items</h2>
            {order.lineItems && order.lineItems.length > 0 ? (
              <div className="space-y-3">
                {order.lineItems.map((item: any) => (
                  <div
                    key={item.id}
                    className="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
                  >
                    <div>
                      <p className="font-medium">{item.name}</p>
                      <p className="text-sm text-gray-600">
                        Qty: {item.unitQty || 1} × ${(item.price / 100).toFixed(2)}
                      </p>
                    </div>
                    <div className="flex items-center gap-4">
                      <span className="font-semibold">
                        ${((item.price * (item.unitQty || 1)) / 100).toFixed(2)}
                      </span>
                      <button
                        onClick={() => removeLineItem(item.id)}
                        className="text-red-600 hover:text-red-700"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-gray-500">No items in this order</p>
            )}
          </div>
        </>
      )}
    </div>
  );
}

function InfoItem({ icon, label, value }: any) {
  return (
    <div className="flex items-start gap-3">
      <div className="text-blue-600 mt-1">{icon}</div>
      <div>
        <p className="text-sm text-gray-600">{label}</p>
        <p className="font-semibold">{value}</p>
      </div>
    </div>
  );
}
