'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Search, Mail, Phone, Calendar, User } from 'lucide-react';

// Типы для клиентов
interface Customer {
  id: number;
  email: string;
  first_name: string;
  last_name: string;
  phone?: string;
  created_at: string;
  orders_count: number;
  total_spent: number;
  last_order_date?: string;
  is_active: boolean;
}

// Временные данные до реализации API
const mockCustomers: Customer[] = [
  { 
    id: 101, 
    email: 'ivan@example.com', 
    first_name: 'Иван', 
    last_name: 'Иванов', 
    phone: '+7 (999) 123-45-67', 
    created_at: '2023-01-10T14:30:00Z', 
    orders_count: 8, 
    total_spent: 45700,
    last_order_date: '2023-03-15T14:30:00Z',
    is_active: true
  },
  { 
    id: 102, 
    email: 'anna@example.com', 
    first_name: 'Анна', 
    last_name: 'Петрова', 
    phone: '+7 (999) 765-43-21', 
    created_at: '2023-02-05T10:15:00Z', 
    orders_count: 3, 
    total_spent: 12500,
    last_order_date: '2023-03-14T10:15:00Z',
    is_active: true
  },
  { 
    id: 103, 
    email: 'sergey@example.com', 
    first_name: 'Сергей', 
    last_name: 'Сидоров', 
    phone: '+7 (999) 555-55-55', 
    created_at: '2023-01-20T18:45:00Z', 
    orders_count: 5, 
    total_spent: 28900,
    last_order_date: '2023-03-13T18:45:00Z',
    is_active: true
  },
  { 
    id: 104, 
    email: 'elena@example.com', 
    first_name: 'Елена', 
    last_name: 'Смирнова', 
    created_at: '2023-02-15T09:20:00Z', 
    orders_count: 1, 
    total_spent: 6300,
    last_order_date: '2023-03-12T09:20:00Z',
    is_active: true
  },
  { 
    id: 105, 
    email: 'dmitry@example.com', 
    first_name: 'Дмитрий', 
    last_name: 'Кузнецов', 
    phone: '+7 (999) 888-77-66', 
    created_at: '2023-01-05T12:10:00Z', 
    orders_count: 4, 
    total_spent: 19800,
    last_order_date: '2023-03-11T12:10:00Z',
    is_active: false
  }
];

export default function CustomersPage() {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [filteredCustomers, setFilteredCustomers] = useState<Customer[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Загрузка клиентов при монтировании
  useEffect(() => {
    // Здесь должен быть запрос к API
    // В будущем заменить на реальный запрос
    setLoading(true);
    
    setTimeout(() => {
      setCustomers(mockCustomers);
      setFilteredCustomers(mockCustomers);
      setLoading(false);
    }, 500);
  }, []);

  // Обработчик поиска
  useEffect(() => {
    if (searchTerm.trim() === '') {
      setFilteredCustomers(customers);
    } else {
      const search = searchTerm.toLowerCase();
      const filtered = customers.filter(customer => 
        customer.email.toLowerCase().includes(search) ||
        customer.first_name.toLowerCase().includes(search) ||
        customer.last_name.toLowerCase().includes(search) ||
        (customer.phone && customer.phone.toLowerCase().includes(search))
      );
      setFilteredCustomers(filtered);
    }
  }, [searchTerm, customers]);

  // Форматирование даты
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('ru-RU');
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-6">
        <strong className="font-bold">Ошибка!</strong>
        <span className="block sm:inline"> {error}</span>
      </div>
    );
  }

  return (
    <div>
      <div className="mb-6 flex justify-between items-center">
        <h2 className="text-xl font-semibold text-gray-800">Управление клиентами</h2>
      </div>

      <div className="bg-white rounded-lg shadow p-4 mb-6">
        <div className="relative">
          <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <Search className="h-5 w-5 text-gray-400" />
          </div>
          <input
            type="text"
            placeholder="Поиск по имени, email или телефону"
            className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
      </div>

      <div className="bg-white rounded-lg shadow overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Клиент</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Контакты</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Регистрация</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Заказы</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Сумма</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Последний заказ</th>
              <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Действия</th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {filteredCustomers.map((customer) => (
              <tr key={customer.id} className={`${!customer.is_active ? 'bg-gray-50' : ''}`}>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="flex items-center">
                    <div className="flex-shrink-0 h-10 w-10 bg-gray-200 rounded-full flex items-center justify-center">
                      <User className="h-5 w-5 text-gray-500" />
                    </div>
                    <div className="ml-4">
                      <div className="text-sm font-medium text-gray-900">
                        {customer.first_name} {customer.last_name}
                      </div>
                      <div className="text-sm text-gray-500">
                        ID: {customer.id}
                      </div>
                    </div>
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm text-gray-900 flex items-center">
                    <Mail className="h-4 w-4 mr-1 text-gray-500" />
                    {customer.email}
                  </div>
                  {customer.phone && (
                    <div className="text-sm text-gray-500 flex items-center mt-1">
                      <Phone className="h-4 w-4 mr-1 text-gray-500" />
                      {customer.phone}
                    </div>
                  )}
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm text-gray-900 flex items-center">
                    <Calendar className="h-4 w-4 mr-1 text-gray-500" />
                    {formatDate(customer.created_at)}
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {customer.orders_count}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {customer.total_spent.toLocaleString('ru-RU')} ₽
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {customer.last_order_date ? formatDate(customer.last_order_date) : '—'}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <Link href={`/admin/customers/${customer.id}`} className="text-indigo-600 hover:text-indigo-900 mr-4">
                    Профиль
                  </Link>
                  <Link href={`/admin/customers/${customer.id}/orders`} className="text-indigo-600 hover:text-indigo-900">
                    Заказы
                  </Link>
                </td>
              </tr>
            ))}
            {filteredCustomers.length === 0 && (
              <tr>
                <td colSpan={7} className="px-6 py-4 text-center text-sm text-gray-500">
                  Клиенты не найдены
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
} 