import React, { useState, useEffect } from 'react';
import { Users, UserCheck, Clock, DollarSign } from 'lucide-react';

export default function EmployeeDashboard() {
  const [stats, setStats] = useState<any>(null);
  const [loading, setLoading] = useState(true);

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

  const fetchStats = async () => {
    setLoading(true);
    try {
      const employeesResult = await window.mcp.callTool('clover_list_employees', {
        limit: 100,
      });
      const employees = employeesResult.employees || [];

      const totalEmployees = employees.length;
      const activeEmployees = employees.filter(
        (e: any) => !e.deletedTime
      ).length;

      // Get performance for today
      const startDate = new Date().setHours(0, 0, 0, 0);
      const endDate = Date.now();

      const perfResult = await window.mcp.callTool(
        'clover_employee_performance',
        {
          startDate,
          endDate,
        }
      );

      setStats({
        totalEmployees,
        activeEmployees,
        topPerformers: perfResult.employees?.slice(0, 3) || [],
      });
    } catch (error) {
      console.error('Failed to fetch employee 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">
      <h1 className="text-3xl font-bold text-gray-900 mb-6">
        Employee Dashboard
      </h1>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
        <StatCard
          icon={<Users className="w-8 h-8 text-blue-600" />}
          title="Total Employees"
          value={stats?.totalEmployees || 0}
          bgColor="bg-blue-50"
        />
        <StatCard
          icon={<UserCheck className="w-8 h-8 text-green-600" />}
          title="Active Employees"
          value={stats?.activeEmployees || 0}
          bgColor="bg-green-50"
        />
        <StatCard
          icon={<Clock className="w-8 h-8 text-purple-600" />}
          title="Clocked In"
          value="N/A"
          bgColor="bg-purple-50"
        />
      </div>

      <div className="bg-white rounded-lg shadow p-6 mb-6">
        <h2 className="text-xl font-semibold mb-4">Top Performers (Today)</h2>
        {stats?.topPerformers.length > 0 ? (
          <div className="space-y-4">
            {stats.topPerformers.map((emp: any, idx: number) => (
              <div
                key={emp.employeeId}
                className="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
              >
                <div className="flex items-center gap-4">
                  <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center font-bold text-blue-600">
                    #{idx + 1}
                  </div>
                  <div>
                    <p className="font-semibold">{emp.employeeName}</p>
                    <p className="text-sm text-gray-600">
                      {emp.orderCount} orders
                    </p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-lg font-bold text-green-600">
                    ${(emp.totalSales / 100).toFixed(2)}
                  </p>
                  <p className="text-sm text-gray-600">
                    Avg: ${(emp.averageOrderValue / 100).toFixed(2)}
                  </p>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-gray-500">No performance data for today</p>
        )}
      </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={async () => {
              const result = await window.mcp.callTool('clover_list_employees', {});
              alert(`Found ${result.count} employees`);
            }}
            className="px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            View All
          </button>
          <button
            onClick={() => window.mcp.showApp('employee-schedule')}
            className="px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700"
          >
            Schedule
          </button>
          <button
            onClick={async () => {
              const name = prompt('Employee name:');
              const role = prompt('Role:');
              if (name && role) {
                await window.mcp.callTool('clover_create_employee', {
                  name,
                  role,
                });
                fetchStats();
              }
            }}
            className="px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
          >
            Add Employee
          </button>
          <button
            onClick={() => alert('Roles feature coming soon')}
            className="px-4 py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700"
          >
            Manage Roles
          </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>
  );
}
