import { usePathname, useRouter } from '@/shared/config/i18n/navigation';
import formatDate from '@/shared/lib/formatDate';
import formatPrice from '@/shared/lib/formatPrice';
import { cn } from '@/shared/lib/utils';
import { Button } from '@/shared/ui/button';
import { Card, CardContent } from '@/shared/ui/card';
import { GlobalPagination } from '@/shared/ui/global-pagination';
import { useQuery } from '@tanstack/react-query';
import {
  Calendar,
  CheckCircle,
  Clock,
  Loader2,
  Package,
  RefreshCw,
} from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { order_api, OrderListRes } from '../lib/api';

const HistoryTabs = () => {
  const t = useTranslations();
  const searchParams = useSearchParams();
  const [page, setPage] = useState(1);
  const PAGE_SIZE = 36;
  const router = useRouter();
  const pathname = usePathname();

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

  useEffect(() => {
    const urlPage = Number(searchParams.get('page')) || 1;
    setPage(urlPage);
  }, [searchParams]);

  const handlePageChange = (newPage: number) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set('page', newPage.toString());

    router.push(`${pathname}?${params.toString()}`, {
      scroll: true,
    });
  };

  const getStatusConfig = (status: 'NEW' | 'DONE') => {
    return status === 'DONE'
      ? {
          bgColor: 'bg-emerald-100',
          textColor: 'text-emerald-600',
          icon: CheckCircle,
          text: 'Yetkazildi',
        }
      : {
          bgColor: 'bg-yellow-100',
          textColor: 'text-yellow-600',
          icon: Clock,
          text: 'Kutilmoqda',
        };
  };

  const getPaymentTypeText = (type: 'CASH' | 'ACCOUNT_NUMBER') => {
    return type === 'CASH' ? 'Naqd pul' : 'Hisob raqami';
  };

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

  if (!data?.results || data.results.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-12 text-center">
        <Package className="w-16 h-16 text-muted-foreground mb-4" />
        <p className="text-lg font-semibold text-foreground mb-2">
          {t('Buyurtmalar topilmadi')}
        </p>
        <p className="text-sm text-muted-foreground">
          {t('Hali buyurtma qilmagansiz')}
        </p>
      </div>
    );
  }

  return (
    <>
      <div className="flex items-center justify-between mb-4 md:mb-6">
        <h2 className="text-xl md:text-2xl font-bold text-foreground">
          {t('Buyurtmalar tarixi')}
        </h2>
        <div className="text-sm text-muted-foreground">
          {data.results.length} ta buyurtma
        </div>
      </div>

      <div className="space-y-3 md:space-y-4">
        {data.results.map((order: OrderListRes, idx: number) => {
          const statusConfig = getStatusConfig(order.status);
          const StatusIcon = statusConfig.icon;

          return (
            <div key={order.id} className="flex gap-3 md:gap-4">
              {/* Status Timeline */}
              <div className="flex flex-col items-center">
                <div
                  className={cn(
                    'w-8 h-8 md:w-10 md:h-10 rounded-full flex items-center justify-center shrink-0',
                    statusConfig.bgColor,
                  )}
                >
                  <StatusIcon
                    className={cn(
                      'w-4 h-4 md:w-5 md:h-5',
                      statusConfig.textColor,
                    )}
                  />
                </div>

                {idx < data.results.length - 1 && (
                  <div className="w-0.5 flex-1 bg-slate-200 my-2" />
                )}
              </div>

              {/* Order Card */}
              <Card className="flex-1 border-0 shadow-sm hover:shadow-md transition-shadow">
                <CardContent className="p-3 md:p-4">
                  {/* Header */}
                  <div className="flex flex-col md:flex-row md:items-start justify-between mb-3 gap-2">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <p className="font-semibold text-sm md:text-base text-foreground">
                          #{order.order_number}
                        </p>
                        <span
                          className={cn(
                            'text-xs px-2 py-0.5 rounded-full',
                            statusConfig.bgColor,
                            statusConfig.textColor,
                          )}
                        >
                          {statusConfig.text}
                        </span>
                      </div>
                      <div className="flex items-center gap-2 text-xs md:text-sm text-muted-foreground flex-wrap">
                        <span className="flex items-center gap-1">
                          <Calendar className="w-3 h-3 md:w-4 md:h-4" />
                          {formatDate.format(
                            order.created_at,
                            'DD.MM.YYYY HH:mm',
                          )}
                        </span>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="font-bold text-base md:text-lg text-foreground">
                        {formatPrice(
                          order.total_price + order.delivery_price,
                          true,
                        )}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {getPaymentTypeText(order.payment_type)}
                      </p>
                    </div>
                  </div>

                  {order.comment && (
                    <div className="mb-3 p-2 bg-slate-50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">
                        Izoh:
                      </p>
                      <p className="text-sm text-foreground">{order.comment}</p>
                    </div>
                  )}

                  {/* Total Price Breakdown */}
                  <div className="border-t pt-3 mb-3 space-y-1 text-sm">
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">
                        Mahsulotlar narxi:
                      </span>
                      <span className="font-medium">
                        {formatPrice(order.total_price, true)}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">Yetkazish:</span>
                      <span className="font-medium">
                        {formatPrice(order.delivery_price, true)}
                      </span>
                    </div>
                    <div className="flex justify-between font-bold text-base pt-1 border-t">
                      <span>Jami:</span>
                      <span>
                        {formatPrice(
                          order.total_price + order.delivery_price,
                          true,
                        )}
                      </span>
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        router.push('/profile/refresh-order');
                        // setOrder(order);
                      }}
                      className="bg-transparent gap-1 md:gap-2 text-xs md:text-sm h-8 md:h-9 px-2 md:px-3"
                    >
                      <RefreshCw className="w-3 h-3 md:w-4 md:h-4" />
                      {t('Qayta buyurtma')}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </div>
          );
        })}
      </div>

      <div className="w-full flex justify-end mt-5">
        <GlobalPagination
          onChange={handlePageChange}
          page={page}
          total={data.total_pages}
          pageSize={PAGE_SIZE}
        />
      </div>
    </>
  );
};

export default HistoryTabs;
