"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useTelegram } from "@/components/TelegramProvider";
import { formatPrice } from "@/types/product";

interface OrderSummary {
  id: number;
  orderNumber: string;
  status: string;
  totalAmount: number;
  itemsCount: number;
  createdAt: string;
}

const statusLabels: Record<string, { label: string; color: string }> = {
  new: { label: "Новый", color: "text-amber-400" },
  confirmed: { label: "Подтверждён", color: "text-sky-400" },
  paid: { label: "Оплачен", color: "text-sky-400" },
  shipped: { label: "В пути", color: "text-indigo-400" },
  completed: { label: "Выполнен", color: "text-emerald-400" },
  cancelled: { label: "Отменён", color: "text-rose-400" },
};

export default function OrdersPage() {
  const { user, isReady } = useTelegram();
  const [orders, setOrders] = useState<OrderSummary[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!isReady) return;
    const telegramUserId = user?.id?.toString();
    if (!telegramUserId) {
      setLoading(false);
      return;
    }
    fetch(`/api/orders?telegramUserId=${telegramUserId}`)
      .then((r) => r.json())
      .then((data) => setOrders(data.items ?? []))
      .finally(() => setLoading(false));
  }, [isReady, user]);

  if (loading) {
    return <p className="p-6 text-center text-sm text-[var(--tg-hint)]">Загрузка...</p>;
  }

  if (!user?.id) {
    return (
      <div className="flex min-h-[60vh] flex-col items-center justify-center px-6 text-center">
        <p className="text-5xl">📦</p>
        <p className="mt-4 text-sm text-[var(--tg-hint)]">
          Откройте магазин через Telegram, чтобы увидеть свои заказы
        </p>
      </div>
    );
  }

  if (orders.length === 0) {
    return (
      <div className="flex min-h-[60vh] flex-col items-center justify-center px-6 text-center">
        <p className="text-5xl">📦</p>
        <p className="mt-4 text-base font-semibold">Заказов пока нет</p>
        <Link
          href="/"
          className="mt-5 rounded-xl bg-[var(--tg-accent)] px-5 py-2.5 text-sm font-semibold text-white"
        >
          Перейти в каталог
        </Link>
      </div>
    );
  }

  return (
    <div className="px-4 py-4">
      <h1 className="mb-4 text-xl font-bold">Мои заказы</h1>
      <div className="flex flex-col gap-3">
        {orders.map((order) => {
          const status = statusLabels[order.status] ?? statusLabels.new;
          return (
            <Link
              key={order.id}
              href={`/orders/${order.id}`}
              className="flex items-center justify-between rounded-2xl border border-white/10 bg-[var(--tg-surface)] p-4"
            >
              <div>
                <p className="text-sm font-semibold">{order.orderNumber}</p>
                <p className="text-xs text-[var(--tg-hint)]">
                  {new Date(order.createdAt).toLocaleDateString("ru-RU")} · {order.itemsCount} товар(ов)
                </p>
                <p className={`mt-1 text-xs font-medium ${status.color}`}>{status.label}</p>
              </div>
              <p className="text-base font-bold">{formatPrice(order.totalAmount)}</p>
            </Link>
          );
        })}
      </div>
    </div>
  );
}
