import React, { useState, useEffect } from 'react';
import { DollarSign, TrendingUp, TrendingDown, List } from 'lucide-react';

export default function CashDrawer() {
  const [deviceId, setDeviceId] = useState('');
  const [drawerInfo, setDrawerInfo] = useState<any>(null);
  const [events, setEvents] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchDrawerInfo = async () => {
    if (!deviceId) return;
    setLoading(true);
    try {
      const result = await window.mcp.callTool('clover_get_cash_drawer', { deviceId });
      setDrawerInfo(result);

      const eventsResult = await window.mcp.callTool('clover_list_cash_events', {
        deviceId,
        limit: 20,
      });
      setEvents(eventsResult.cashEvents || []);
    } catch (error) {
      alert('Failed to load cash drawer');
    } finally {
      setLoading(false);
    }
  };

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

      <div className="bg-white rounded-lg shadow p-6 mb-6">
        <div className="flex gap-4">
          <input
            type="text"
            value={deviceId}
            onChange={(e) => setDeviceId(e.target.value)}
            placeholder="Enter Device ID"
            className="flex-1 px-4 py-2 border border-gray-300 rounded-lg"
          />
          <button
            onClick={fetchDrawerInfo}
            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 Drawer'}
          </button>
        </div>
      </div>

      {drawerInfo && (
        <>
          <div className="bg-white rounded-lg shadow p-6 mb-6">
            <div className="flex items-center gap-4 mb-4">
              <DollarSign className="w-12 h-12 text-green-600" />
              <div>
                <h2 className="text-2xl font-bold text-gray-900">
                  ${(drawerInfo.currentBalance / 100).toFixed(2)}
                </h2>
                <p className="text-gray-600">Current Balance</p>
              </div>
            </div>
            <p className="text-sm text-gray-500">
              {drawerInfo.eventCount} total events
            </p>
          </div>

          <div className="bg-white rounded-lg shadow p-6">
            <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
              <List className="w-6 h-6" />
              Recent Events
            </h2>
            {events.length > 0 ? (
              <div className="space-y-3">
                {events.map((event) => (
                  <div
                    key={event.id}
                    className="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
                  >
                    <div className="flex items-center gap-3">
                      {event.amountChange > 0 ? (
                        <TrendingUp className="w-5 h-5 text-green-600" />
                      ) : (
                        <TrendingDown className="w-5 h-5 text-red-600" />
                      )}
                      <div>
                        <p className="font-medium">{event.type}</p>
                        <p className="text-sm text-gray-600">
                          {new Date(event.timestamp).toLocaleString()}
                        </p>
                        {event.note && (
                          <p className="text-sm text-gray-500">{event.note}</p>
                        )}
                      </div>
                    </div>
                    <p
                      className={`text-lg font-semibold ${
                        event.amountChange > 0 ? 'text-green-600' : 'text-red-600'
                      }`}
                    >
                      {event.amountChange > 0 ? '+' : ''}
                      ${(event.amountChange / 100).toFixed(2)}
                    </p>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-gray-500">No events found</p>
            )}
          </div>
        </>
      )}
    </div>
  );
}
