import React, { useState, useEffect } from 'react';
import { Package, TrendingUp } from 'lucide-react';

export default function RevenueByItem() {
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [timeRange, setTimeRange] = useState('today');

  useEffect(() => {
    fetchRevenue();
  }, [timeRange]);

  const fetchRevenue = async () => {
    setLoading(true);
    try {
      const endDate = Date.now();
      let startDate = endDate;
      
      if (timeRange === 'today') {
        startDate = new Date().setHours(0, 0, 0, 0);
      } else if (timeRange === 'week') {
        startDate = endDate - 7 * 24 * 60 * 60 * 1000;
      } else if (timeRange === 'month') {
        startDate = endDate - 30 * 24 * 60 * 60 * 1000;
      }

      const result = await window.mcp.callTool('clover_revenue_by_item', {
        startDate,
        endDate,
      });
      setItems(result.items || []);
    } catch (error) {
      console.error('Failed to fetch revenue:', error);
    } finally {
      setLoading(false);
    }
  };

  const sortedItems = [...items].sort((a, b) => b.totalRevenue - a.totalRevenue);

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-gray-900">Revenue by Item</h1>
        <select
          value={timeRange}
          onChange={(e) => setTimeRange(e.target.value)}
          className="px-4 py-2 border border-gray-300 rounded-lg"
        >
          <option value="today">Today</option>
          <option value="week">This Week</option>
          <option value="month">This Month</option>
        </select>
      </div>

      {loading ? (
        <div className="text-center py-12 text-gray-500">Loading...</div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {sortedItems.map((item, idx) => (
            <div key={item.itemId} className="bg-white rounded-lg shadow p-6">
              <div className="flex items-start justify-between mb-4">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-2">
                    <span className="text-2xl font-bold text-blue-600">#{idx + 1}</span>
                    <Package className="w-6 h-6 text-gray-400" />
                  </div>
                  <h3 className="text-lg font-semibold text-gray-900">{item.itemName}</h3>
                </div>
              </div>
              
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-gray-600">Revenue:</span>
                  <span className="font-bold text-green-600">
                    ${(item.totalRevenue / 100).toFixed(2)}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Quantity Sold:</span>
                  <span className="font-semibold">{item.quantitySold}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Avg Price:</span>
                  <span className="font-semibold">
                    ${(item.averagePrice / 100).toFixed(2)}
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
