import React, { useState, useEffect } from 'react';
import { ShoppingCart, DollarSign, Clock, TrendingUp } from 'lucide-react';

interface OrderStats {
  totalOrders: number;
  openOrders: number;
  totalRevenue: number;
  averageOrderValue: number;
}

export default function OrderDashboard() {
  const [stats, setStats] = useState<OrderStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [timeRange, setTimeRange] = useState('today');

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

  const fetchStats = 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 summary = await window.mcp.callTool('clover_sales_summary', {
        startDate,
        endDate,
      });

      const openOrders = await window.mcp.callTool('clover_list_orders', {
        filter: 'state=open',
      });

      setStats({
        totalOrders: summary.totalOrders || 0,
        openOrders: openOrders.count || 0,
        totalRevenue: summary.totalSales || 0,
        averageOrderValue: summary.averageOrderValue || 0,
      });
    } catch (error) {
      console.error('Failed to fetch order stats:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-gray-500">Loading dashboard...</div>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="mb-6 flex justify-between items-center">
        <h1 className="text-3xl font-bold text-gray-900">Order 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 mb-8">
        <StatCard
          icon={<ShoppingCart className="w-8 h-8 text-blue-600" />}
          title="Total Orders"
          value={stats?.totalOrders || 0}
          bgColor="bg-blue-50"
        />
        <StatCard
          icon={<Clock className="w-8 h-8 text-yellow-600" />}
          title="Open Orders"
          value={stats?.openOrders || 0}
          bgColor="bg-yellow-50"
        />
        <StatCard
          icon={<DollarSign className="w-8 h-8 text-green-600" />}
          title="Total Revenue"
          value={`$${((stats?.totalRevenue || 0) / 100).toFixed(2)}`}
          bgColor="bg-green-50"
        />
        <StatCard
          icon={<TrendingUp className="w-8 h-8 text-purple-600" />}
          title="Avg Order Value"
          value={`$${((stats?.averageOrderValue || 0) / 100).toFixed(2)}`}
          bgColor="bg-purple-50"
        />
      </div>

      <div className="bg-white rounded-lg shadow p-6">
        <h2 className="text-xl font-semibold mb-4">Quick Actions</h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <button
            onClick={() => window.mcp.showApp('order-grid')}
            className="px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            View All Orders
          </button>
          <button
            onClick={() => window.mcp.callTool('clover_create_order', {})}
            className="px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700"
          >
            New Order
          </button>
          <button
            onClick={() => window.mcp.showApp('order-detail')}
            className="px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
          >
            Order Details
          </button>
          <button
            onClick={() => window.mcp.showApp('payment-history')}
            className="px-4 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
          >
            Payment History
          </button>
        </div>
      </div>
    </div>
  );
}

function StatCard({
  icon,
  title,
  value,
  bgColor,
}: {
  icon: React.ReactNode;
  title: string;
  value: string | number;
  bgColor: string;
}) {
  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>
  );
}
