import React, { useState, useEffect } from 'react';
import { DollarSign, TrendingUp, ShoppingBag, RefreshCw } from 'lucide-react';

export default function SalesDashboard() {
  const [summary, setSummary] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [timeRange, setTimeRange] = useState('today');

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

  const fetchSummary = 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_sales_summary', {
        startDate,
        endDate,
      });
      setSummary(result);
    } catch (error) {
      console.error('Failed to fetch summary:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading || !summary) {
    return <div className="p-6">Loading...</div>;
  }

  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">Sales Dashboard</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>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard
          icon={<DollarSign className="w-8 h-8 text-green-600" />}
          title="Total Sales"
          value={`$${((summary.totalSales || 0) / 100).toFixed(2)}`}
          bgColor="bg-green-50"
        />
        <StatCard
          icon={<ShoppingBag className="w-8 h-8 text-blue-600" />}
          title="Total Orders"
          value={summary.totalOrders || 0}
          bgColor="bg-blue-50"
        />
        <StatCard
          icon={<TrendingUp className="w-8 h-8 text-purple-600" />}
          title="Avg Order Value"
          value={`$${((summary.averageOrderValue || 0) / 100).toFixed(2)}`}
          bgColor="bg-purple-50"
        />
        <StatCard
          icon={<RefreshCw className="w-8 h-8 text-red-600" />}
          title="Refunds"
          value={`$${((summary.totalRefunds || 0) / 100).toFixed(2)}`}
          bgColor="bg-red-50"
        />
      </div>

      <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="bg-white rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold mb-4">Net Sales</h2>
          <p className="text-3xl font-bold text-green-600">
            ${((summary.netSales || 0) / 100).toFixed(2)}
          </p>
          <p className="text-sm text-gray-600 mt-2">
            After refunds: ${((summary.totalRefunds || 0) / 100).toFixed(2)}
          </p>
        </div>

        <div className="bg-white rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold mb-4">Tax & Tips</h2>
          <div className="space-y-2">
            <p className="text-lg">
              Tax: <span className="font-semibold">${((summary.totalTax || 0) / 100).toFixed(2)}</span>
            </p>
            <p className="text-lg">
              Tips: <span className="font-semibold">${((summary.totalTips || 0) / 100).toFixed(2)}</span>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCard({ icon, title, value, bgColor }: any) {
  return (
    <div className={`${bgColor} rounded-lg p-6 shadow-sm`}>
      <div className="flex items-center justify-between mb-3">{icon}</div>
      <h3 className="text-gray-600 text-sm font-medium mb-1">{title}</h3>
      <p className="text-2xl font-bold text-gray-900">{value}</p>
    </div>
  );
}
