import { auth } from '../../../../auth'
import { prisma } from '@peyzajart/db'
import { notFound } from 'next/navigation'
import Link from 'next/link'
import { formatTL } from '../../../../lib/format'

export const dynamic = 'force-dynamic'

const STATUS_LABELS: Record<string, string> = {
  PENDING: 'Beklemede',
  CONFIRMED: 'Onaylandı',
  PREPARING: 'Hazırlanıyor',
  SHIPPED: 'Kargoya Verildi',
  DELIVERED: 'Teslim Edildi',
  CANCELLED: 'İptal Edildi',
}

const STATUS_COLORS: Record<string, string> = {
  PENDING: 'bg-yellow-100 text-yellow-800',
  CONFIRMED: 'bg-blue-100 text-blue-800',
  PREPARING: 'bg-purple-100 text-purple-800',
  SHIPPED: 'bg-orange-100 text-orange-800',
  DELIVERED: 'bg-green-100 text-green-800',
  CANCELLED: 'bg-red-100 text-red-800',
}

interface Props {
  params: { orderNo: string }
}

export default async function OrderDetailPage({ params }: Props) {
  const session = await auth()

  const order = await prisma.order.findUnique({
    where: { orderNo: params.orderNo },
    include: {
      dealer: { select: { id: true, companyName: true, dealerCode: true } },
      items: {
        include: {
          product: { select: { nameTr: true, category: true, size: true, slug: true } },
        },
      },
    },
  })

  if (!order) notFound()

  // Güvenlik: sadece kendi siparişini görebilir (admin hariç)
  if (!session!.user.isAdmin && order.dealerId !== session!.user.dealerId) {
    notFound()
  }

  return (
    <div className="p-6 md:p-8 max-w-3xl">
        {/* Başlık */}
        <div className="mb-8 flex items-start justify-between gap-4">
          <div>
            <Link
              href="/bayi/orders"
              className="font-body text-xs text-earth hover:text-brown transition-colors"
            >
              ← Siparişlerim
            </Link>
            <h1 className="font-display text-3xl font-light text-brown mt-2">
              {order.orderNo}
            </h1>
            <p className="font-body text-sm text-brown/50 mt-1">
              {new Date(order.createdAt).toLocaleDateString('tr-TR', {
                day: 'numeric',
                month: 'long',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
              })}
            </p>
          </div>
          <span
            className={`px-3 py-1.5 rounded-full font-body text-sm flex-shrink-0 ${STATUS_COLORS[order.status] ?? ''}`}
          >
            {STATUS_LABELS[order.status]}
          </span>
        </div>

        {/* Sipariş kalemleri */}
        <div className="bg-white shadow-sm rounded-xl overflow-hidden mb-6">
          <div className="px-6 py-4 border-b border-sand">
            <h2 className="font-display text-xl text-brown">Ürünler</h2>
          </div>
          <table className="w-full">
            <thead>
              <tr className="border-b border-sand">
                <th className="text-left px-6 py-3 font-body text-xs text-brown/50 tracking-widest uppercase">
                  Ürün
                </th>
                <th className="text-right px-6 py-3 font-body text-xs text-brown/50 tracking-widest uppercase">
                  Adet
                </th>
                <th className="text-right px-6 py-3 font-body text-xs text-brown/50 tracking-widest uppercase">
                  Birim Fiyat
                </th>
                <th className="text-right px-6 py-3 font-body text-xs text-brown/50 tracking-widest uppercase">
                  Toplam
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-sand">
              {order.items.map((item) => (
                <tr key={item.id}>
                  <td className="px-6 py-4">
                    <p className="font-body text-sm text-brown">{item.product.nameTr}</p>
                    {item.product.size && (
                      <p className="font-body text-xs text-brown/40">{item.product.size}</p>
                    )}
                  </td>
                  <td className="px-6 py-4 text-right font-body text-sm text-brown">
                    {item.quantity}
                  </td>
                  <td className="px-6 py-4 text-right font-body text-sm text-brown">
                    {formatTL(item.unitPrice)}
                  </td>
                  <td className="px-6 py-4 text-right font-body text-sm font-medium text-brown">
                    {formatTL(item.unitPrice * item.quantity)}
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr className="border-t border-brown/10 bg-sand/50">
                <td colSpan={3} className="px-6 py-4 font-body text-sm font-medium text-brown text-right">
                  TOPLAM
                </td>
                <td className="px-6 py-4 font-display text-lg text-brown text-right">
                  {formatTL(order.totalUSD)}
                </td>
              </tr>
            </tfoot>
          </table>
        </div>

        {/* Sipariş bilgileri */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
          <div className="bg-white p-5 shadow-sm rounded-xl space-y-3">
            <h3 className="font-display text-lg text-brown border-b border-sand pb-2">
              Ödeme Bilgisi
            </h3>
            <div className="font-body text-sm space-y-1">
              <p>
                <span className="text-brown/50">Yöntem: </span>
                <span className="text-brown">
                  {order.paymentMethod === 'ONLINE' ? 'İyzico (Online)' : 'Havale/EFT'}
                </span>
              </p>
              <p>
                <span className="text-brown/50">Durum: </span>
                <span
                  className={
                    order.paymentStatus === 'PAID'
                      ? 'text-green-700 font-medium'
                      : order.paymentStatus === 'FAILED'
                      ? 'text-red-600 font-medium'
                      : 'text-yellow-700'
                  }
                >
                  {order.paymentStatus === 'WAITING'
                    ? 'Ödeme Bekleniyor'
                    : order.paymentStatus === 'PAID'
                    ? 'Ödendi'
                    : 'Başarısız'}
                </span>
              </p>
            </div>
          </div>

          <div className="bg-white p-5 shadow-sm rounded-xl space-y-3">
            <h3 className="font-display text-lg text-brown border-b border-sand pb-2">
              Teslimat Adresi
            </h3>
            <p className="font-body text-sm text-brown/80 whitespace-pre-wrap">
              {order.shippingAddress}
            </p>
          </div>

          {order.notes && (
            <div className="bg-white p-5 shadow-sm rounded-xl sm:col-span-2">
              <h3 className="font-display text-lg text-brown border-b border-sand pb-2 mb-3">
                Sipariş Notu
              </h3>
              <p className="font-body text-sm text-brown/70">{order.notes}</p>
            </div>
          )}
        </div>
    </div>
  )
}
