import { useState, useEffect } from 'react';
import './styles.css';

interface Customer {
  id: string;
  name: string;
  email: string;
  phone: string;
  visitCount: number;
  totalSpent: number;
  avgSpend: number;
  lastVisit: string;
  loyaltyPoints: number;
  tags: string[];
}

export default function CustomerDirectory() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<'name' | 'visits' | 'spent'>('name');

  useEffect(() => {
    // Mock data
    setCustomers([
      { id: '1', name: 'Sarah Johnson', email: 'sarah.j@email.com', phone: '555-0101', visitCount: 23, totalSpent: 1847.50, avgSpend: 80.33, lastVisit: '2024-02-14', loyaltyPoints: 2340, tags: ['VIP', 'Regular'] },
      { id: '2', name: 'Mike Chen', email: 'mike.chen@email.com', phone: '555-0102', visitCount: 45, totalSpent: 3245.75, avgSpend: 72.13, lastVisit: '2024-02-15', loyaltyPoints: 4890, tags: ['VIP', 'Regular', 'Anniversary'] },
      { id: '3', name: 'Emma Davis', email: 'emma.d@email.com', phone: '555-0103', visitCount: 8, totalSpent: 567.20, avgSpend: 70.90, lastVisit: '2024-02-12', loyaltyPoints: 850, tags: [] },
      { id: '4', name: 'John Smith', email: 'john.smith@email.com', phone: '555-0104', visitCount: 12, totalSpent: 982.40, avgSpend: 81.87, lastVisit: '2024-02-10', loyaltyPoints: 1470, tags: ['Regular'] },
      { id: '5', name: 'Lisa Park', email: 'lisa.park@email.com', phone: '555-0105', visitCount: 34, totalSpent: 2456.90, avgSpend: 72.26, lastVisit: '2024-02-15', loyaltyPoints: 3685, tags: ['VIP'] },
      { id: '6', name: 'David Wilson', email: 'david.w@email.com', phone: '555-0106', visitCount: 5, totalSpent: 342.50, avgSpend: 68.50, lastVisit: '2024-02-08', loyaltyPoints: 515, tags: [] },
      { id: '7', name: 'Amy Chen', email: 'amy.chen@email.com', phone: '555-0107', visitCount: 18, totalSpent: 1456.80, avgSpend: 80.93, lastVisit: '2024-02-13', loyaltyPoints: 2185, tags: ['Regular'] },
      { id: '8', name: 'Robert Taylor', email: 'robert.t@email.com', phone: '555-0108', visitCount: 29, totalSpent: 2123.60, avgSpend: 73.23, lastVisit: '2024-02-14', loyaltyPoints: 3185, tags: ['VIP', 'Regular'] },
    ]);
  }, []);

  const filteredCustomers = customers
    .filter((customer) =>
      customer.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      customer.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      customer.phone.includes(searchQuery)
    )
    .sort((a, b) => {
      if (sortBy === 'name') return a.name.localeCompare(b.name);
      if (sortBy === 'visits') return b.visitCount - a.visitCount;
      if (sortBy === 'spent') return b.totalSpent - a.totalSpent;
      return 0;
    });

  const totalCustomers = customers.length;
  const totalRevenue = customers.reduce((sum, c) => sum + c.totalSpent, 0);
  const avgVisits = customers.reduce((sum, c) => sum + c.visitCount, 0) / customers.length;

  return (
    <div className="app">
      <header className="app-header">
        <h1>👥 Customer Directory</h1>
        <p>Searchable customer database</p>
      </header>

      <div className="stats-bar">
        <div className="stat-card">
          <span className="stat-label">Total Customers</span>
          <span className="stat-value">{totalCustomers}</span>
        </div>
        <div className="stat-card">
          <span className="stat-label">Total Revenue</span>
          <span className="stat-value revenue">${totalRevenue.toFixed(2)}</span>
        </div>
        <div className="stat-card">
          <span className="stat-label">Avg Visits</span>
          <span className="stat-value">{avgVisits.toFixed(1)}</span>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          className="search-input"
          placeholder="Search by name, email, or phone..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <select
          className="sort-select"
          value={sortBy}
          onChange={(e) => setSortBy(e.target.value as any)}
        >
          <option value="name">Sort by Name</option>
          <option value="visits">Sort by Visits</option>
          <option value="spent">Sort by Spending</option>
        </select>
        <button className="btn-primary">+ Add Customer</button>
      </div>

      <div className="customer-grid">
        {filteredCustomers.map((customer) => (
          <div key={customer.id} className="customer-card">
            <div className="customer-header">
              <h3>{customer.name}</h3>
              {customer.tags.length > 0 && (
                <div className="tags">
                  {customer.tags.map((tag) => (
                    <span key={tag} className={`tag ${tag.toLowerCase()}`}>
                      {tag}
                    </span>
                  ))}
                </div>
              )}
            </div>

            <div className="customer-contact">
              <div className="contact-item">
                <span className="icon">📧</span>
                <span>{customer.email}</span>
              </div>
              <div className="contact-item">
                <span className="icon">📱</span>
                <span>{customer.phone}</span>
              </div>
            </div>

            <div className="customer-stats">
              <div className="stat-item">
                <span className="stat-value">{customer.visitCount}</span>
                <span className="stat-label">Visits</span>
              </div>
              <div className="stat-item">
                <span className="stat-value">${customer.totalSpent.toFixed(0)}</span>
                <span className="stat-label">Total Spent</span>
              </div>
              <div className="stat-item">
                <span className="stat-value">${customer.avgSpend.toFixed(0)}</span>
                <span className="stat-label">Avg Spend</span>
              </div>
              <div className="stat-item">
                <span className="stat-value">{customer.loyaltyPoints}</span>
                <span className="stat-label">Points</span>
              </div>
            </div>

            <div className="customer-footer">
              <span className="last-visit">
                Last visit: {new Date(customer.lastVisit).toLocaleDateString()}
              </span>
              <button className="view-btn">View Profile</button>
            </div>
          </div>
        ))}
      </div>

      {filteredCustomers.length === 0 && (
        <div className="no-results">No customers found</div>
      )}
    </div>
  );
}
