import React, { useState, useEffect } from 'react';
import { Folder, BarChart } from 'lucide-react';

export default function RevenueByCategory() {
  const [categories, setCategories] = 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_category', {
        startDate,
        endDate,
      });
      setCategories(result.categories || []);
    } catch (error) {
      console.error('Failed to fetch revenue:', error);
    } finally {
      setLoading(false);
    }
  };

  const sortedCategories = [...categories].sort((a, b) => b.totalRevenue - a.totalRevenue);
  const totalRevenue = categories.reduce((sum, c) => sum + c.totalRevenue, 0);

  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 Category</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="bg-white rounded-lg shadow p-6 mb-6">
            <h2 className="text-xl font-semibold mb-2">Total Revenue</h2>
            <p className="text-3xl font-bold text-green-600">
              ${(totalRevenue / 100).toFixed(2)}
            </p>
          </div>

          <div className="space-y-4">
            {sortedCategories.map((category, idx) => {
              const percentage = totalRevenue > 0 
                ? ((category.totalRevenue / totalRevenue) * 100).toFixed(1)
                : 0;

              return (
                <div key={category.categoryId} className="bg-white rounded-lg shadow p-6">
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-3">
                      <Folder className="w-6 h-6 text-blue-600" />
                      <div>
                        <h3 className="text-lg font-semibold">{category.categoryName}</h3>
                        <p className="text-sm text-gray-600">{category.itemCount} items</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-2xl font-bold text-green-600">
                        ${(category.totalRevenue / 100).toFixed(2)}
                      </p>
                      <p className="text-sm text-gray-600">{percentage}%</p>
                    </div>
                  </div>
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div
                      className="bg-blue-600 h-2 rounded-full"
                      style={{ width: `${percentage}%` }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </>
      )}
    </div>
  );
}
