import { useState } from 'react';
import Link from 'next/link';
import { Package, ExternalLink } from 'lucide-react';
import { OrderItem } from '@/lib/api';
import { formatPrice } from '@/lib/utils';
import { getImageUrl } from '@/lib/api';

interface OrderItemsProps {
  items: OrderItem[];
  total: number;
}

export function OrderItems({ items, total }: OrderItemsProps) {
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 5; // Количество товаров на странице
  
  // Расчет индексов текущей страницы товаров
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = items.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(items.length / itemsPerPage);

  // Обработчик изменения страницы
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  return (
    <div className="px-6 py-4 border-t border-gray-200">
      <div className="flex items-center mb-4">
        <Package className="h-5 w-5 text-indigo-500 mr-2" />
        <h3 className="text-lg font-medium text-gray-900">Товары в заказе</h3>
      </div>

      <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">Товар</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">
            {currentItems.map((item) => (
              <tr key={item.id} className="hover:bg-gray-50">
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="flex items-center">
                    {item.product?.image ? (
                      <img
                        src={getImageUrl(item.product.image)}
                        alt={item.product.name}
                        className="h-12 w-12 rounded-md object-cover border border-gray-200"
                      />
                    ) : (
                      <div className="h-12 w-12 rounded-md bg-gray-200 flex items-center justify-center border border-gray-300">
                        <Package className="h-6 w-6 text-gray-400" />
                      </div>
                    )}
                    <div className="ml-4">
                      <div className="text-sm font-medium text-gray-900">
                        {item.product?.name || 'Товар не найден'}
                      </div>
                      {item.product?.id && (
                        <Link 
                          href={`/admin/products/${item.product.id}`}
                          className="text-xs text-indigo-600 hover:text-indigo-900 inline-flex items-center"
                        >
                          Открыть товар
                          <ExternalLink className="h-3 w-3 ml-1" />
                        </Link>
                      )}
                    </div>
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {item.variant_name || '—'}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {item.quantity}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {formatPrice(item.price || 0)}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 text-right font-medium">
                  {formatPrice((item.price || 0) * (item.quantity || 0))}
                </td>
              </tr>
            ))}
          </tbody>
          <tfoot className="bg-gray-50">
            <tr>
              <td colSpan={4} className="px-6 py-4 text-right text-sm font-medium text-gray-500">
                Итого:
              </td>
              <td className="px-6 py-4 text-right text-base font-semibold text-indigo-700">
                {formatPrice(total || 0)}
              </td>
            </tr>
          </tfoot>
        </table>
        
        {/* Пагинация */}
        {totalPages > 1 && (
          <div className="flex justify-center mt-4 space-x-1">
            <button 
              onClick={() => handlePageChange(Math.max(1, currentPage - 1))}
              disabled={currentPage === 1}
              className="px-3 py-1 rounded-md border border-gray-300 text-sm font-medium text-gray-700 
                        hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              &laquo;
            </button>
            {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
              <button
                key={page}
                onClick={() => handlePageChange(page)}
                className={`px-3 py-1 rounded-md border text-sm font-medium 
                          ${currentPage === page 
                            ? 'bg-indigo-600 text-white border-indigo-600' 
                            : 'text-gray-700 border-gray-300 hover:bg-gray-50'}`}
              >
                {page}
              </button>
            ))}
            <button 
              onClick={() => handlePageChange(Math.min(totalPages, currentPage + 1))}
              disabled={currentPage === totalPages}
              className="px-3 py-1 rounded-md border border-gray-300 text-sm font-medium text-gray-700 
                        hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              &raquo;
            </button>
          </div>
        )}
      </div>
    </div>
  );
} 