import { useState, useEffect } from 'react';
import './styles.css';

interface OrderItem {
  id: string;
  name: string;
  quantity: number;
  modifiers: string[];
  instructions?: string;
  status: 'new' | 'preparing' | 'ready';
}

interface KitchenOrder {
  id: string;
  orderNumber: string;
  type: string;
  table?: string;
  server: string;
  items: OrderItem[];
  createdAt: string;
  elapsedMinutes: number;
  priority: 'normal' | 'high' | 'urgent';
}

export default function KitchenDisplay() {
  const [orders, setOrders] = useState<KitchenOrder[]>([]);
  const [filter, setFilter] = useState<'all' | 'new' | 'preparing'>('all');

  useEffect(() => {
    // Mock data
    setOrders([
      {
        id: '1',
        orderNumber: 'ORD-142',
        type: 'Dine In',
        table: 'Table 12',
        server: 'Mike',
        elapsedMinutes: 2,
        priority: 'normal',
        createdAt: new Date().toISOString(),
        items: [
          { id: '1', name: 'Classic Burger', quantity: 2, modifiers: ['No Onions', 'Extra Cheese'], instructions: 'Medium rare', status: 'preparing' },
          { id: '2', name: 'Caesar Salad', quantity: 1, modifiers: ['Add Chicken'], status: 'preparing' },
        ],
      },
      {
        id: '2',
        orderNumber: 'ORD-143',
        type: 'Takeout',
        server: 'Lisa',
        elapsedMinutes: 5,
        priority: 'normal',
        createdAt: new Date().toISOString(),
        items: [
          { id: '3', name: 'Grilled Salmon', quantity: 1, modifiers: [], status: 'preparing' },
          { id: '4', name: 'French Fries', quantity: 2, modifiers: [], status: 'ready' },
        ],
      },
      {
        id: '3',
        orderNumber: 'ORD-144',
        type: 'Delivery',
        server: 'Tom',
        elapsedMinutes: 12,
        priority: 'high',
        createdAt: new Date().toISOString(),
        items: [
          { id: '5', name: 'Margherita Pizza', quantity: 2, modifiers: ['Extra Basil'], status: 'preparing' },
          { id: '6', name: 'Chicken Wings', quantity: 1, modifiers: ['BBQ Sauce'], status: 'preparing' },
          { id: '7', name: 'Garlic Bread', quantity: 1, modifiers: [], status: 'ready' },
        ],
      },
      {
        id: '4',
        orderNumber: 'ORD-145',
        type: 'Dine In',
        table: 'Table 5',
        server: 'Mike',
        elapsedMinutes: 18,
        priority: 'urgent',
        createdAt: new Date().toISOString(),
        items: [
          { id: '8', name: 'Ribeye Steak', quantity: 1, modifiers: ['Medium Well'], instructions: 'Rush order', status: 'new' },
          { id: '9', name: 'Mashed Potatoes', quantity: 1, modifiers: ['Extra Butter'], status: 'new' },
        ],
      },
      {
        id: '5',
        orderNumber: 'ORD-146',
        type: 'Dine In',
        table: 'Table 8',
        server: 'Lisa',
        elapsedMinutes: 1,
        priority: 'normal',
        createdAt: new Date().toISOString(),
        items: [
          { id: '10', name: 'Fish & Chips', quantity: 2, modifiers: [], status: 'new' },
          { id: '11', name: 'Coleslaw', quantity: 2, modifiers: [], status: 'new' },
        ],
      },
    ]);
  }, []);

  const filteredOrders = orders.filter((order) => {
    if (filter === 'all') return true;
    return order.items.some(item => item.status === filter);
  });

  const getPriorityColor = (priority: string) => {
    const colors = {
      normal: '#3b82f6',
      high: '#fbbf24',
      urgent: '#ef4444',
    };
    return colors[priority as keyof typeof colors];
  };

  const stats = {
    total: orders.length,
    new: orders.filter(o => o.items.some(i => i.status === 'new')).length,
    preparing: orders.filter(o => o.items.some(i => i.status === 'preparing')).length,
    avgTime: Math.round(orders.reduce((sum, o) => sum + o.elapsedMinutes, 0) / orders.length),
  };

  return (
    <div className="app kds">
      <header className="kds-header">
        <h1>🍳 Kitchen Display</h1>
        <div className="header-stats">
          <div className="header-stat">
            <span className="stat-value">{stats.total}</span>
            <span className="stat-label">Active Orders</span>
          </div>
          <div className="header-stat">
            <span className="stat-value new">{stats.new}</span>
            <span className="stat-label">New</span>
          </div>
          <div className="header-stat">
            <span className="stat-value preparing">{stats.preparing}</span>
            <span className="stat-label">Preparing</span>
          </div>
          <div className="header-stat">
            <span className="stat-value time">{stats.avgTime}m</span>
            <span className="stat-label">Avg Time</span>
          </div>
        </div>
      </header>

      <div className="filters">
        {['all', 'new', 'preparing'].map((status) => (
          <button
            key={status}
            className={`filter-btn ${filter === status ? 'active' : ''}`}
            onClick={() => setFilter(status as any)}
          >
            {status.charAt(0).toUpperCase() + status.slice(1)}
          </button>
        ))}
      </div>

      <div className="orders-grid">
        {filteredOrders.map((order) => (
          <div
            key={order.id}
            className={`order-ticket ${order.priority}`}
            style={{ borderTopColor: getPriorityColor(order.priority) }}
          >
            <div className="ticket-header">
              <div className="ticket-info">
                <span className="order-number">{order.orderNumber}</span>
                <span className="order-type">{order.type}</span>
                {order.table && <span className="order-table">🪑 {order.table}</span>}
              </div>
              <div className="ticket-time">
                <span className={`elapsed ${order.priority}`}>
                  {order.elapsedMinutes}m
                </span>
                <span className="server">Server: {order.server}</span>
              </div>
            </div>

            <div className="ticket-items">
              {order.items.map((item) => (
                <div key={item.id} className={`ticket-item ${item.status}`}>
                  <div className="item-header">
                    <span className="item-quantity">{item.quantity}×</span>
                    <span className="item-name">{item.name}</span>
                    <span className={`item-status ${item.status}`}>
                      {item.status === 'new' && '🔴'}
                      {item.status === 'preparing' && '🟡'}
                      {item.status === 'ready' && '✓'}
                    </span>
                  </div>
                  {item.modifiers.length > 0 && (
                    <div className="item-modifiers">
                      {item.modifiers.map((mod, idx) => (
                        <span key={idx} className="modifier">• {mod}</span>
                      ))}
                    </div>
                  )}
                  {item.instructions && (
                    <div className="item-instructions">📝 {item.instructions}</div>
                  )}
                </div>
              ))}
            </div>

            <div className="ticket-actions">
              <button className="btn-action start">Start</button>
              <button className="btn-action ready">Ready</button>
              <button className="btn-action complete">Complete</button>
            </div>
          </div>
        ))}
      </div>

      {filteredOrders.length === 0 && (
        <div className="no-orders">
          <div className="no-orders-icon">🎉</div>
          <div className="no-orders-text">All caught up!</div>
        </div>
      )}
    </div>
  );
}
