import React, { useState, useEffect } from 'react';
import { Search, User, Plus, Eye } from 'lucide-react';

export default function CustomerGrid() {
  const [customers, setCustomers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');

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

  const fetchCustomers = async () => {
    setLoading(true);
    try {
      const result = await window.mcp.callTool('clover_list_customers', {
        expand: 'emailAddresses,phoneNumbers',
        limit: 100,
      });
      setCustomers(result.customers || []);
    } catch (error) {
      console.error('Failed to fetch customers:', error);
    } finally {
      setLoading(false);
    }
  };

  const searchCustomers = async () => {
    if (!searchTerm) {
      fetchCustomers();
      return;
    }

    setLoading(true);
    try {
      const result = await window.mcp.callTool('clover_search_customers', {
        query: searchTerm,
      });
      setCustomers(result.customers || []);
    } catch (error) {
      console.error('Search failed:', error);
    } finally {
      setLoading(false);
    }
  };

  const createCustomer = async () => {
    const firstName = prompt('First name:');
    const lastName = prompt('Last name:');
    if (!firstName || !lastName) return;

    try {
      await window.mcp.callTool('clover_create_customer', {
        firstName,
        lastName,
      });
      fetchCustomers();
    } catch (error) {
      alert('Failed to create customer');
    }
  };

  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">Customers</h1>
        <button
          onClick={createCustomer}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
        >
          <Plus className="w-5 h-5" />
          New Customer
        </button>
      </div>

      <div className="bg-white rounded-lg shadow p-6 mb-6">
        <div className="flex gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-3 text-gray-400 w-5 h-5" />
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && searchCustomers()}
              placeholder="Search customers by name..."
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg"
            />
          </div>
          <button
            onClick={searchCustomers}
            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Search
          </button>
        </div>
      </div>

      {loading ? (
        <div className="text-center py-12 text-gray-500">
          Loading customers...
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {customers.map((customer) => (
            <div key={customer.id} className="bg-white rounded-lg shadow p-6">
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                    <User className="w-6 h-6 text-blue-600" />
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-900">
                      {customer.firstName} {customer.lastName}
                    </h3>
                    <p className="text-sm text-gray-600">
                      ID: {customer.id.slice(0, 8)}...
                    </p>
                  </div>
                </div>
              </div>

              {customer.emailAddresses?.[0] && (
                <p className="text-sm text-gray-600 mb-2">
                  📧 {customer.emailAddresses[0].emailAddress}
                </p>
              )}
              {customer.phoneNumbers?.[0] && (
                <p className="text-sm text-gray-600 mb-4">
                  📞 {customer.phoneNumbers[0].phoneNumber}
                </p>
              )}

              <button
                onClick={() =>
                  window.mcp.showApp('customer-detail', { customerId: customer.id })
                }
                className="w-full px-4 py-2 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 flex items-center justify-center gap-2"
              >
                <Eye className="w-4 h-4" />
                View Details
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
