'use client';

import { BASE_URL } from '@/shared/config/api/URLs';
import { useRouter } from '@/shared/config/i18n/navigation';
import formatPrice from '@/shared/lib/formatPrice';
import { Button } from '@/shared/ui/button';
import { Card, CardContent } from '@/shared/ui/card';
import { useQuery } from '@tanstack/react-query';
import {
  Calendar,
  Loader2,
  MessageSquare,
  Package,
  RefreshCw,
  ShoppingBag,
} from 'lucide-react';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
import { order_api, OrderList } from '../lib/api';

const HistoryTabs = () => {
  const t = useTranslations();
  const router = useRouter();

  const { data, isLoading } = useQuery({
    queryKey: ['order_list'],
    queryFn: () => order_api.list(),
    select: (res) => res.data,
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
      </div>
    );
  }

  if (!data || data.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center px-4">
        <div className="bg-gray-100 p-6 rounded-full mb-4">
          <Package className="w-16 h-16 text-gray-400" />
        </div>
        <p className="text-xl font-bold text-gray-800 mb-2">
          {t('Buyurtmalar topilmadi')}
        </p>
        <p className="text-sm text-gray-500 max-w-md">
          {t(
            "Hali buyurtma qilmagansiz. Mahsulotlarni ko'rib chiqing va birinchi buyurtmangizni bering!",
          )}
        </p>
        <Button onClick={() => router.push('/')} className="mt-6">
          <ShoppingBag className="w-4 h-4 mr-2" />
          {t('Xarid qilish')}
        </Button>
      </div>
    );
  }

  return (
    <div className="max-w-5xl mx-auto px-3 md:px-0">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between mb-6 pb-4 border-b gap-2">
        <div>
          <h2 className="text-2xl md:text-3xl font-bold text-gray-900">
            {t('Buyurtmalar tarixi')}
          </h2>
          <p className="text-sm text-gray-500 mt-1">
            {data.length} {t('ta buyurtma')}
          </p>
        </div>
      </div>

      {/* Orders List */}
      <div className="space-y-4 md:space-y-6">
        {data.map((order: OrderList) => {
          const totalPrice = order.items.reduce(
            (sum, item) => sum + Number(item.price) * item.quantity,
            0,
          );

          return (
            <Card
              key={order.id}
              className="border-2 border-gray-200 hover:border-blue-400 transition-all duration-200 shadow-sm hover:shadow-lg"
            >
              <CardContent className="p-0">
                {/* Order Header */}
                <div className="bg-gradient-to-r from-blue-50 to-indigo-50 p-3 md:p-4 border-b-2 border-gray-200">
                  <div className="flex flex-col md:flex-row md:items-center justify-between gap-3">
                    <div className="flex items-center gap-3">
                      <div className="bg-blue-600 text-white px-3 py-1 rounded-full text-sm font-bold">
                        #{order.id}
                      </div>
                      <div>
                        <p className="text-xs text-gray-500">
                          {t('Buyurtma raqami')}
                        </p>
                      </div>
                    </div>

                    {order.delivery_date && (
                      <div className="flex items-center gap-2 bg-white px-3 py-2 rounded-lg shadow-sm">
                        <Calendar className="w-4 h-4 text-blue-600" />
                        <div>
                          <p className="text-xs text-gray-500">
                            {t('Yetkazib berish')}
                          </p>
                          <p className="text-sm font-semibold text-gray-800">
                            {order.delivery_date}
                          </p>
                        </div>
                      </div>
                    )}
                  </div>

                  {/* Comment */}
                  {order.comment && (
                    <div className="mt-3 bg-white p-3 rounded-lg shadow-sm border border-gray-200">
                      <div className="flex items-start gap-2">
                        <MessageSquare className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
                        <div className="flex-1">
                          <p className="text-xs font-medium text-gray-500 mb-1">
                            {t('Izoh')}:
                          </p>
                          <p className="text-sm text-gray-700 leading-relaxed">
                            {order.comment}
                          </p>
                        </div>
                      </div>
                    </div>
                  )}
                </div>

                {/* Products */}
                <div className="p-3 md:p-4 space-y-3">
                  {order.items.map((item, index) => {
                    const product = item.product;

                    const productImage = product.images?.[0]?.images
                      ? product.images[0].images.includes(BASE_URL)
                        ? product.images[0].images
                        : BASE_URL + product.images[0].images
                      : '/placeholder.svg';

                    return (
                      <div
                        key={item.id}
                        className="border-2 border-gray-100 rounded-xl p-3 md:p-4 bg-gradient-to-br from-white to-gray-50 hover:shadow-md transition-shadow"
                      >
                        <div className="flex gap-3 md:gap-4">
                          {/* Image */}
                          <div className="flex-shrink-0">
                            <div className="w-16 h-16 md:w-24 md:h-24 bg-gray-100 rounded-lg overflow-hidden border-2 border-gray-200">
                              <Image
                                src={productImage}
                                alt={product.name}
                                width={96}
                                height={96}
                                className="w-full h-full object-contain"
                                unoptimized
                              />
                            </div>
                          </div>

                          {/* Info */}
                          <div className="flex-1 min-w-0">
                            <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-2 mb-2">
                              <div className="min-w-0">
                                <div className="flex items-center gap-2 mb-1">
                                  <span className="bg-blue-100 text-blue-800 text-xs font-semibold px-2 py-1 rounded">
                                    {index + 1}
                                  </span>
                                  <h3 className="font-bold text-sm md:text-lg text-gray-900 truncate">
                                    {product.name}
                                  </h3>
                                </div>

                                {product.short_name && (
                                  <p className="text-xs md:text-sm text-gray-600 line-clamp-2">
                                    {product.short_name}
                                  </p>
                                )}
                              </div>

                              <div className="text-left md:text-right">
                                <p className="text-xs text-gray-500">
                                  {t('Mahsulotlar narxi')}
                                </p>
                                <p className="text-base md:text-lg font-bold text-blue-600">
                                  {formatPrice(Number(item.price), true)}
                                </p>
                              </div>
                            </div>

                            {/* Details */}
                            <div className="grid grid-cols-2 gap-2 md:gap-3 p-2 md:p-3 bg-white rounded-lg border border-gray-200">
                              <div>
                                <span className="text-xs text-gray-500">
                                  {t('Miqdor')}
                                </span>
                                <p className="text-sm md:text-base font-bold">
                                  {item.quantity}
                                </p>
                              </div>

                              <div className="text-right">
                                <span className="text-xs text-gray-500">
                                  {t('Jami')}
                                </span>
                                <p className="text-sm md:text-base font-bold text-green-600">
                                  {formatPrice(
                                    Number(item.price) * item.quantity,
                                    true,
                                  )}
                                </p>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>

                {/* Footer */}
                <div className="bg-gradient-to-r from-gray-50 to-blue-50 p-3 md:p-4 border-t-2 border-gray-200">
                  <div className="space-y-1 md:space-y-2 text-sm">
                    <div className="flex justify-between text-gray-600">
                      <span>{t('Mahsulotlar narxi')}:</span>
                      <span className="font-semibold">
                        {formatPrice(totalPrice, true)}
                      </span>
                    </div>

                    <div className="flex justify-between text-gray-600">
                      <span>{t('Mahsulotlar soni')}:</span>
                      <span className="font-semibold">
                        {order.items.reduce(
                          (sum, item) => sum + item.quantity,
                          0,
                        )}{' '}
                        {t('dona')}
                      </span>
                    </div>

                    <div className="border-t border-dashed pt-2 flex justify-between items-center">
                      <span className="font-bold">{t('Umumiy summa')}:</span>
                      <span className="text-lg md:text-2xl font-bold text-green-600">
                        {formatPrice(totalPrice, true)}
                      </span>
                    </div>
                  </div>

                  <Button
                    variant="outline"
                    onClick={() =>
                      router.push(`/profile/refresh-order?id=${order.id}`)
                    }
                    className="w-full md:w-auto mt-3 gap-2"
                  >
                    <RefreshCw className="w-4 h-4" />
                    {t('Qayta buyurtma')}
                  </Button>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>
    </div>
  );
};

export default HistoryTabs;
