'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Search, Filter, ChevronDown } from 'lucide-react';
import { fetchOrders, Order } from '@/lib/api';
import { formatDate, formatPrice } from '@/lib/utils';

// Компонент для фильтрации заказов
interface FilterDropdownProps {
  options: { value: string; label: string }[];
  value: string;
  onChange: (value: string) => void;
  label: string;
}

const FilterDropdown = ({ options, value, onChange, label }: FilterDropdownProps) => {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div className="relative">
      <button
        type="button"
        className="flex items-center px-3 py-2 border border-gray-300 rounded-md bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
        onClick={() => setIsOpen(!isOpen)}
      >
        {label}: {options.find(option => option.value === value)?.label || 'Все'}
        <ChevronDown className="ml-2 h-4 w-4" />
      </button>
      
      {isOpen && (
        <div className="origin-top-right absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-10">
          <div className="py-1" role="menu" aria-orientation="vertical">
            {options.map(option => (
              <button
                key={option.value}
                className={`block px-4 py-2 text-sm w-full text-left ${
                  value === option.value 
                    ? 'bg-indigo-100 text-indigo-900' 
                    : 'text-gray-700 hover:bg-gray-100'
                }`}
                onClick={() => {
                  onChange(option.value);
                  setIsOpen(false);
                }}
                role="menuitem"
              >
                {option.label}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default function OrdersPage() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [filteredOrders, setFilteredOrders] = useState<Order[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [dateFilter, setDateFilter] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [sortField, setSortField] = useState<string>('created_at');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');

  // Массив статусов заказов
  const statusOptions = [
    { value: '', label: 'Все статусы' },
    { value: 'pending', label: 'Ожидает оплаты' },
    { value: 'processing', label: 'В обработке' },
    { value: 'shipped', label: 'Отправлен' },
    { value: 'delivered', label: 'Доставлен' },
    { value: 'cancelled', label: 'Отменен' },
    { value: 'refunded', label: 'Возвращен' }
  ];

  // Массив фильтров по дате
  const dateOptions = [
    { value: '', label: 'За все время' },
    { value: 'today', label: 'Сегодня' },
    { value: 'yesterday', label: 'Вчера' },
    { value: 'week', label: 'За неделю' },
    { value: 'month', label: 'За месяц' }
  ];

  // Функция сортировки заказов
  const sortOrders = (orders: Order[], field: string, direction: 'asc' | 'desc') => {
    return [...orders].sort((a, b) => {
      let valueA, valueB;
      
      switch (field) {
        case 'id':
          valueA = a.id;
          valueB = b.id;
          break;
        case 'user_name':
          valueA = a.user_name || '';
          valueB = b.user_name || '';
          break;
        case 'created_at':
          valueA = new Date(a.created_at).getTime();
          valueB = new Date(b.created_at).getTime();
          break;
        case 'items_count':
          valueA = a.items_count || 0;
          valueB = b.items_count || 0;
          break;
        case 'total':
          valueA = a.total || 0;
          valueB = b.total || 0;
          break;
        default:
          valueA = a[field as keyof Order] || '';
          valueB = b[field as keyof Order] || '';
      }
      
      if (valueA < valueB) return direction === 'asc' ? -1 : 1;
      if (valueA > valueB) return direction === 'asc' ? 1 : -1;
      return 0;
    });
  };

  // Обработчик клика по заголовку таблицы для сортировки
  const handleSort = (field: string) => {
    const newDirection = sortField === field && sortDirection === 'asc' ? 'desc' : 'asc';
    setSortField(field);
    setSortDirection(newDirection);
    
    // Сортируем заказы
    const sortedOrders = sortOrders(filteredOrders, field, newDirection);
    setFilteredOrders(sortedOrders);
  };

  // Получить иконку направления сортировки
  const getSortIcon = (field: string) => {
    if (sortField !== field) return null;
    
    return (
      <span className="ml-1 inline-block">
        {sortDirection === 'asc' ? '↑' : '↓'}
      </span>
    );
  };

  // Загрузка заказов
  useEffect(() => {
    const loadOrders = async () => {
      try {
        setLoading(true);
        setError(null);

        // Формируем параметры запроса
        const params: any = {
          limit: 100 // Максимальное количество заказов
        };

        // Добавляем фильтр по статусу
        if (statusFilter) {
          params.status = statusFilter;
        }

        // Добавляем фильтр по дате
        if (dateFilter) {
          const now = new Date();
          const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
          const yesterday = new Date(today);
          yesterday.setDate(yesterday.getDate() - 1);
          const weekAgo = new Date(today);
          weekAgo.setDate(weekAgo.getDate() - 7);
          const monthAgo = new Date(today);
          monthAgo.setMonth(monthAgo.getMonth() - 1);

          switch (dateFilter) {
            case 'today':
              params.dateFrom = today.toISOString();
              break;
            case 'yesterday':
              params.dateFrom = yesterday.toISOString();
              params.dateTo = today.toISOString();
              break;
            case 'week':
              params.dateFrom = weekAgo.toISOString();
              break;
            case 'month':
              params.dateFrom = monthAgo.toISOString();
              break;
          }
        }

        // Добавляем поисковый запрос
        if (searchTerm) {
          params.search = searchTerm;
        }

        const response = await fetchOrders(params);
        
        if (response.data) {
          // Обработка возможных форматов ответа API
          let orderData: Order[] = [];
          
          if (Array.isArray(response.data)) {
            orderData = response.data;
          } else {
            // Если response.data - это объект, проверяем наличие свойства orders
            const data = response.data as any;
            if (data.orders && Array.isArray(data.orders)) {
              orderData = data.orders;
            }
          }
          
          // Применяем сортировку к загруженным данным
          const sortedOrders = sortOrders(orderData, sortField, sortDirection);
          
          setOrders(orderData);
          setFilteredOrders(sortedOrders);
        } else {
          throw new Error('Не удалось получить данные заказов');
        }
      } catch (err) {
        console.error('Ошибка при загрузке заказов:', err);
        setError('Не удалось загрузить заказы');
      } finally {
        setLoading(false);
      }
    };

    loadOrders();
  }, [statusFilter, dateFilter, searchTerm, sortField, sortDirection]);

  // Получить строковое представление статуса заказа
  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'pending':
        return 'Ожидает оплаты';
      case 'processing':
        return 'В обработке';
      case 'shipped':
        return 'Отправлен';
      case 'delivered':
        return 'Доставлен';
      case 'cancelled':
        return 'Отменен';
      case 'refunded':
        return 'Возвращен';
      default:
        return status;
    }
  };

  // Получить класс для стиля статуса заказа
  const getStatusClass = (status: string) => {
    switch (status) {
      case 'pending':
        return 'bg-yellow-100 text-yellow-800';
      case 'processing':
        return 'bg-blue-100 text-blue-800';
      case 'shipped':
        return 'bg-purple-100 text-purple-800';
      case 'delivered':
        return 'bg-green-100 text-green-800';
      case 'cancelled':
        return 'bg-red-100 text-red-800';
      case 'refunded':
        return 'bg-gray-100 text-gray-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  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>
        {filteredOrders.length > 0 && (
          <div className="text-sm text-gray-500">
            Найдено заказов: <span className="font-medium">{filteredOrders.length}</span>
          </div>
        )}
      </div>

      <div className="bg-white rounded-lg shadow p-4 mb-6">
        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1 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="Поиск по имени клиента или номеру заказа"
              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 className="flex gap-2">
            <FilterDropdown
              options={statusOptions}
              value={statusFilter}
              onChange={setStatusFilter}
              label="Статус"
            />
            
            <FilterDropdown
              options={dateOptions}
              value={dateFilter}
              onChange={setDateFilter}
              label="Дата"
            />
          </div>
        </div>
      </div>

      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="overflow-x-auto">
          <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 cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('id')}
                >
                  № заказа {getSortIcon('id')}
                </th>
                <th 
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('user_name')}
                >
                  Клиент {getSortIcon('user_name')}
                </th>
                <th 
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('created_at')}
                >
                  Дата {getSortIcon('created_at')}
                </th>
                <th 
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('items_count')}
                >
                  Товары {getSortIcon('items_count')}
                </th>
                <th 
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('status')}
                >
                  Статус {getSortIcon('status')}
                </th>
                <th 
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('total')}
                >
                  Сумма {getSortIcon('total')}
                </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">
              {filteredOrders.length > 0 ? (
                filteredOrders.map((order) => (
                  <tr key={order.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">#{order.id}</td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      <div className="font-medium">{order.user_name || `Пользователь #${order.user_id}`}</div>
                      {order.user_email && (
                        <div className="text-xs text-gray-400">{order.user_email}</div>
                      )}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      <div title={order.created_at}>
                        {formatDate(order.created_at)}
                      </div>
                      {order.updated_at && order.updated_at !== order.created_at && (
                        <div className="text-xs text-gray-400" title={`Обновлен: ${order.updated_at}`}>
                          изменен: {new Date(order.updated_at).toLocaleDateString('ru-RU')}
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      <div className="flex items-center">
                        <span className="font-medium">{order.items_count || (order.items && order.items.length) || 0}</span>
                        <span className="ml-1">шт.</span>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusClass(order.status)}`}
                            title={order.updated_at ? `Обновлено: ${formatDate(order.updated_at)}` : ''}>
                        {getStatusLabel(order.status)}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {formatPrice(order.total || 0)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <Link 
                        href={`/admin/orders/${order.id}`} 
                        className="inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                      >
                        Подробнее
                      </Link>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={7} className="px-6 py-12 text-center text-sm text-gray-500">
                    <div className="flex flex-col items-center">
                      <p className="text-lg mb-2">Заказы не найдены</p>
                      <p className="text-sm text-gray-400">Попробуйте изменить параметры поиска или фильтрации</p>
                      <button 
                        className="mt-4 inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                        onClick={() => {
                          setSearchTerm('');
                          setStatusFilter('');
                          setDateFilter('');
                        }}
                      >
                        Сбросить фильтры
                      </button>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
} 