'use client'

import { useCallback, useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import { Link } from '@/i18n/navigation'
import { useTranslations } from 'next-intl'
import { toast } from 'react-hot-toast'
import { Package, Truck, MapPin, CreditCard, Printer, CheckCircle, XCircle, Home, ImageOff } from 'lucide-react'
import Image from 'next/image'
import AccountLayout from '@/components/frontend/account/AccountLayout'
import OrderStatusBadge from '@/components/frontend/account/OrderStatusBadge'
import { useCurrencyStore } from '@/store/currencyStore'
import { getApiErrorMessage } from '@/lib/utils/apiError'

interface OrderItem {
  id: string
  product_name: string
  variant_name: string | null
  quantity: number
  unit_price: number
  total_price: number
  image_url: string | null
}

interface Order {
  id: string
  order_number: string
  status: 'pending' | 'confirmed' | 'shipped' | 'delivered' | 'cancelled' | 'returned' | 'refunded'
  payment_method: 'cod' | 'bank_transfer' | 'paypal' | 'stripe'
  payment_status: string
  delivery_fee: number
  tax_amount: number
  tax_percentage: number
  coupon_discount_amount: number
  shipping_full_name: string
  shipping_phone: string
  shipping_address_line1: string
  shipping_address_line2: string | null
  shipping_city: string
  shipping_landmark: string | null
  created_at: string
}

interface StatusHistoryEntry {
  new_status: string
  note: string | null
  created_at: string
}

const STEPS = ['pending', 'confirmed', 'shipped', 'delivered'] as const

export default function OrderDetailPageClient() {
  const { id } = useParams<{ id: string }>()
  const formatAmount = useCurrencyStore((s) => s.formatAmount)
  const t = useTranslations('Account.orderDetail')

  const [order, setOrder] = useState<Order | null>(null)
  const [items, setItems] = useState<OrderItem[]>([])
  const [statusHistory, setStatusHistory] = useState<StatusHistoryEntry[]>([])
  const [status, setStatus] = useState<'loading' | 'idle' | 'error'>('loading')
  const [cancelling, setCancelling] = useState(false)
  const [confirmingCancel, setConfirmingCancel] = useState(false)

  const load = useCallback(() => {
    fetch(`/api/frontend/orders/${id}`, { credentials: 'include' })
      .then((res) => res.json())
      .then((data) => {
        if (!data.success) throw new Error(getApiErrorMessage(data, t('notFound')))
        setOrder(data.data.order)
        setItems(data.data.items)
        setStatusHistory(data.data.statusHistory)
        setStatus('idle')
      })
      .catch(() => setStatus('error'))
  }, [id, t])

  useEffect(() => {
    load()
  }, [load])

  const handleCancel = async () => {
    setCancelling(true)
    try {
      const res = await fetch(`/api/frontend/orders/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ action: 'cancel' }),
      })
      const data = await res.json()
      if (!res.ok || !data.success) {
        toast.error(getApiErrorMessage(data, t('cancelFailed')))
        return
      }
      toast.success(t('cancelSuccess'))
      setConfirmingCancel(false)
      load()
    } catch {
      toast.error(t('networkError'))
    } finally {
      setCancelling(false)
    }
  }

  if (status === 'loading') {
    return (
      <AccountLayout title={t('title')} description={t('loading')}>
        <div className="text-center py-12">
          <div className="animate-spin w-10 h-10 border-4 border-primary border-t-transparent rounded-full mx-auto" />
        </div>
      </AccountLayout>
    )
  }

  if (status === 'error' || !order) {
    return (
      <AccountLayout title={t('title')} description="">
        <div className="text-center py-12">
          <XCircle size={48} className="mx-auto text-gray-300 mb-3" />
          <h3 className="text-lg font-semibold text-dark mb-1">{t('notFound')}</h3>
          <p className="text-gray-custom text-sm">{t('notFoundDescription')}</p>
        </div>
      </AccountLayout>
    )
  }

  const subtotal = items.reduce((sum, item) => sum + Number(item.total_price), 0)
  const total = Math.max(subtotal + order.delivery_fee + order.tax_amount - order.coupon_discount_amount, 0)
  const currentStepIndex = (STEPS as readonly string[]).indexOf(order.status)
  const isTerminal = ['cancelled', 'returned', 'refunded'].includes(order.status)
  const canCancel = order.status === 'pending' || order.status === 'confirmed'
  // Once shipped a customer can no longer cancel it themselves, and once
  // delivered the only path is a return — both go to support via the contact
  // form, pre-filled with this order's number (lands in the admin inbox).
  const contactBase = `/contact?subject=order&order=${encodeURIComponent(order.order_number)}`
  const requestType = order.status === 'shipped' ? 'cancel' : order.status === 'delivered' ? 'return' : null
  const stepLabels: Record<(typeof STEPS)[number], string> = {
    pending: t('steps.pending'),
    confirmed: t('steps.confirmed'),
    shipped: t('steps.shipped'),
    delivered: t('steps.delivered'),
  }

  return (
    <AccountLayout title={t('orderNumber', { number: order.order_number })} description={new Date(order.created_at).toLocaleDateString()}>
      <div className="space-y-6">
        {/* Status + Actions */}
        <div className="flex flex-wrap justify-between items-center gap-4">
          <OrderStatusBadge status={order.status} className="text-sm px-3 py-1" />
          <button onClick={() => window.print()} className="text-gray-custom hover:text-primary transition flex items-center gap-1 text-sm">
            <Printer size={14} /> {t('print')}
          </button>
        </div>

        {/* Timeline */}
        {!isTerminal ? (
          <div className="bg-white rounded-xl border border-gray-100 p-6">
            <h3 className="font-semibold text-dark mb-6">{t('orderTimeline')}</h3>
            <div className="relative">
              <div className="absolute left-5 top-0 bottom-0 w-0.5 bg-gray-200" />
              <div className="space-y-6 relative">
                {STEPS.map((step, index) => {
                  const done = index <= currentStepIndex
                  const historyEntry = statusHistory.find((h) => h.new_status === step)
                  return (
                    <div key={step} className="relative pl-12">
                      <div
                        className={`absolute left-0 w-10 h-10 rounded-full flex items-center justify-center z-10 ${
                          done ? (step === 'delivered' ? 'bg-green-500 text-white' : 'bg-primary text-white') : 'bg-gray-100 text-gray-custom'
                        }`}
                      >
                        {step === 'pending' && <Package size={18} />}
                        {step === 'confirmed' && <CheckCircle size={18} />}
                        {step === 'shipped' && <Truck size={18} />}
                        {step === 'delivered' && <Home size={18} />}
                      </div>
                      <div>
                        <h4 className={`font-semibold ${done ? 'text-dark' : 'text-gray-custom'}`}>
                          {stepLabels[step]}
                        </h4>
                        {historyEntry && (
                          <p className="text-xs text-gray-custom mt-0.5">{new Date(historyEntry.created_at).toLocaleString()}</p>
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>
          </div>
        ) : (
          <div className="bg-white rounded-xl border border-gray-100 p-6 flex items-center gap-3">
            <XCircle size={24} className="text-red-500" />
            <div>
              <p className="font-semibold text-dark capitalize">{order.status}</p>
              <p className="text-sm text-gray-custom">{new Date(order.created_at).toLocaleDateString()}</p>
            </div>
          </div>
        )}

        {/* Items */}
        <div className="bg-white rounded-xl border border-gray-100 p-6">
          <h3 className="font-semibold text-dark mb-4">{t('orderItems')}</h3>
          <div className="space-y-3">
            {items.map((item) => (
              <div key={item.id} className="flex justify-between items-center py-2 border-b border-gray-100 last:border-0">
                <div className="flex items-center gap-3">
                  <div className="relative w-12 h-12 shrink-0 rounded-lg overflow-hidden bg-light-gray">
                    {item.image_url ? (
                      <Image src={item.image_url} alt={item.product_name} fill className="object-cover" sizes="48px" />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center">
                        <ImageOff size={16} className="text-gray-300" />
                      </div>
                    )}
                  </div>
                  <div>
                    <p className="font-medium text-dark">{item.product_name}</p>
                    {item.variant_name && <p className="text-xs text-gray-custom">{item.variant_name}</p>}
                    <p className="text-xs text-gray-custom">{t('qty', { count: item.quantity })}</p>
                  </div>
                </div>
                <p className="font-medium text-dark">{formatAmount(item.total_price)}</p>
              </div>
            ))}
          </div>
        </div>

        {/* Payment Summary */}
        <div className="bg-white rounded-xl border border-gray-100 p-6">
          <h3 className="font-semibold text-dark mb-4">{t('paymentSummary')}</h3>
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span className="text-gray-custom">{t('subtotal')}</span>
              <span>{formatAmount(subtotal)}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-gray-custom">{t('deliveryFee')}</span>
              <span>{order.delivery_fee === 0 ? t('free') : formatAmount(order.delivery_fee)}</span>
            </div>
            {order.tax_amount > 0 && (
              <div className="flex justify-between text-sm">
                <span className="text-gray-custom">{t('tax', { percentage: order.tax_percentage })}</span>
                <span>{formatAmount(order.tax_amount)}</span>
              </div>
            )}
            {order.coupon_discount_amount > 0 && (
              <div className="flex justify-between text-sm text-green-600">
                <span>{t('discount')}</span>
                <span>- {formatAmount(order.coupon_discount_amount)}</span>
              </div>
            )}
            <div className="border-t border-gray-100 pt-2 mt-2">
              <div className="flex justify-between font-semibold">
                <span>{t('totalPaid')}</span>
                <span className="text-primary">{formatAmount(total)}</span>
              </div>
            </div>
            <div className="mt-3 p-2 bg-gray-50 rounded-lg text-xs text-gray-custom flex items-center gap-2">
              <CreditCard size={14} />
              {t('paidVia', { method: order.payment_method === 'cod' ? t('cod') : order.payment_method === 'bank_transfer' ? t('bankTransfer') : order.payment_method })}
            </div>
          </div>
        </div>

        {/* Delivery Details */}
        <div className="bg-white rounded-xl border border-gray-100 p-6">
          <h3 className="font-semibold text-dark mb-4">{t('deliveryDetails')}</h3>
          <div className="flex gap-3">
            <MapPin size={16} className="text-primary flex-shrink-0" />
            <div>
              <p className="text-dark font-medium">{t('shippingAddress')}</p>
              <p className="text-sm text-gray-custom">
                {order.shipping_address_line1}
                {order.shipping_address_line2 && `, ${order.shipping_address_line2}`}, {order.shipping_city}
              </p>
              {order.shipping_landmark && <p className="text-sm text-gray-custom">{t('landmark')}: {order.shipping_landmark}</p>}
              <p className="text-sm text-gray-custom">{t('phone')}: {order.shipping_phone}</p>
            </div>
          </div>
        </div>

        {/* Actions */}
        <div className="flex flex-wrap gap-3">
          <Link href="/" className="bg-gradient-primary text-white px-6 py-2.5 rounded-lg font-medium hover:shadow-md transition">
            {t('shopAgain')}
          </Link>
          {canCancel && !confirmingCancel && (
            <button
              onClick={() => setConfirmingCancel(true)}
              className="text-red-500 border border-red-200 px-6 py-2.5 rounded-lg font-medium hover:bg-red-50 transition"
            >
              {t('cancelOrder')}
            </button>
          )}
          {canCancel && confirmingCancel && (
            <div className="flex items-center gap-2 border border-red-200 rounded-lg px-4 py-2 bg-red-50">
              <span className="text-sm text-dark">{t('cancelConfirm')}</span>
              <button
                onClick={handleCancel}
                disabled={cancelling}
                className="text-sm font-semibold text-white bg-red-500 px-3 py-1 rounded-md hover:bg-red-600 transition disabled:opacity-50"
              >
                {cancelling ? t('cancelling') : t('yesCancel')}
              </button>
              <button
                onClick={() => setConfirmingCancel(false)}
                className="text-sm text-dark border border-gray-200 px-3 py-1 rounded-md hover:bg-gray-100 transition"
              >
                {t('noKeepOrder')}
              </button>
            </div>
          )}
          {requestType && (
            <Link
              href={`${contactBase}&request=${requestType}`}
              className="text-red-500 border border-red-200 px-6 py-2.5 rounded-lg font-medium hover:bg-red-50 transition"
            >
              {requestType === 'cancel' ? t('requestCancellation') : t('requestReturn')}
            </Link>
          )}
          <Link
            href={contactBase}
            className="text-gray-custom border border-gray-200 px-6 py-2.5 rounded-lg font-medium hover:border-primary hover:text-primary transition"
          >
            {t('needHelp')}
          </Link>
        </div>
      </div>
    </AccountLayout>
  )
}
