'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import Image from 'next/image'
import { useLocale, useTranslations } from 'next-intl'
import * as motion from 'framer-motion/m'
import {
  PackageSearch, Package, CheckCircle, Truck, Home, XCircle, RotateCcw, Wallet,
  Search, ArrowLeft, MapPin, CreditCard, ImageOff, Clock, MessageCircle, Loader2,
} from 'lucide-react'
import { Link } from '@/i18n/navigation'
import Container from '@/components/frontend/Container'
import OrderStatusBadge, { type OrderStatus } from '@/components/frontend/account/OrderStatusBadge'
import { useCurrencyStore } from '@/store/currencyStore'

// ─── Types (shape of POST /api/frontend/orders/track) ────────────────────────

interface TrackedOrder {
  order_number: string
  status: OrderStatus
  payment_method: 'cod' | 'bank_transfer' | 'paypal' | 'stripe'
  payment_status: 'pending' | 'paid' | 'failed' | 'refunded' | 'partially_refunded'
  delivery_fee: number
  tax_amount: number
  tax_percentage: number
  coupon_discount_amount: number
  shipping_full_name: string | null
  shipping_city: string | null
  cancelled_at: string | null
  created_at: string
  updated_at: string
}

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

interface HistoryEntry {
  status: string
  note: string | null
  created_at: string
}

interface TrackResult {
  order: TrackedOrder
  items: TrackedItem[]
  history: HistoryEntry[]
}

// ─── Status model ────────────────────────────────────────────────────────────

const STEPS = ['pending', 'confirmed', 'shipped', 'delivered'] as const
type Step = (typeof STEPS)[number]
type TerminalStatus = 'cancelled' | 'returned' | 'refunded'

const STEP_ICONS: Record<Step, typeof Package> = {
  pending: Package,
  confirmed: CheckCircle,
  shipped: Truck,
  delivered: Home,
}

const TERMINAL_ICONS: Record<TerminalStatus, typeof Package> = {
  cancelled: XCircle,
  returned: RotateCcw,
  refunded: Wallet,
}

const TERMINAL_COLORS: Record<TerminalStatus, string> = {
  cancelled: 'bg-red-500 text-white',
  returned: 'bg-purple-500 text-white',
  refunded: 'bg-gray-500 text-white',
}

const isTerminal = (status: string): status is TerminalStatus =>
  status === 'cancelled' || status === 'returned' || status === 'refunded'

// The most recent time the order entered `status` (an order can move back
// and forth, e.g. confirmed → pending → confirmed; the latest one counts).
function lastEntryFor(history: HistoryEntry[], status: string): HistoryEntry | undefined {
  for (let i = history.length - 1; i >= 0; i--) {
    if (history[i].status === status) return history[i]
  }
  return undefined
}

// How far along the normal flow the order got. For a cancelled/returned/
// refunded order that's the furthest normal step it reached before that.
function reachedStepIndex(order: TrackedOrder, history: HistoryEntry[]): number {
  if (!isTerminal(order.status)) return STEPS.indexOf(order.status as Step)
  return history.reduce((max, h) => Math.max(max, STEPS.indexOf(h.status as Step)), 0)
}

// ─── Component ───────────────────────────────────────────────────────────────

interface TrackOrderClientProps {
  initialOrderNumber: string
  isLoggedIn: boolean
}

export default function TrackOrderClient({ initialOrderNumber, isLoggedIn }: TrackOrderClientProps) {
  const t = useTranslations('TrackOrder')

  const [orderNumber, setOrderNumber] = useState(initialOrderNumber)
  const [contact, setContact] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<TrackResult | null>(null)

  const track = useCallback(async (number: string, contactValue: string, silent = false) => {
    setLoading(true)
    if (!silent) setError('')
    try {
      const res = await fetch('/api/frontend/orders/track', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ orderNumber: number.trim(), contact: contactValue.trim() }),
      })
      const data = await res.json()
      if (res.ok && data.success) {
        setResult(data.data)
        setError('')
        return
      }
      if (!silent) setError(res.status === 429 ? t('errors.tooMany') : t('errors.notFound'))
    } catch {
      if (!silent) setError(t('errors.generic'))
    } finally {
      setLoading(false)
    }
  }, [t])

  // Logged-in customer arriving from their order confirmation: their session
  // proves ownership, so try without asking for email/phone first. If it
  // isn't their order, quietly fall back to the pre-filled form.
  const autoTried = useRef(false)
  useEffect(() => {
    if (autoTried.current || !initialOrderNumber || !isLoggedIn) return
    autoTried.current = true
    track(initialOrderNumber, '', true)
  }, [initialOrderNumber, isLoggedIn, track])

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!orderNumber.trim()) return setError(t('errors.orderNumberRequired'))
    if (!contact.trim()) return setError(t('errors.contactRequired'))
    track(orderNumber, contact)
  }

  function trackAnother() {
    setResult(null)
    setOrderNumber('')
    setContact('')
    setError('')
  }

  return (
    <Container className="py-8">
      {/* Hero */}
      <section className="relative overflow-hidden rounded-2xl">
        <div className="absolute inset-0 bg-gradient-primary opacity-90" />
        <div className="absolute top-0 end-0 w-64 h-64 bg-white/10 rounded-full blur-3xl" />
        <div className="absolute bottom-0 start-0 w-80 h-80 bg-white/5 rounded-full blur-3xl" />
        <motion.div
          animate={{ y: [0, -10, 0], x: [0, 5, 0] }}
          transition={{ duration: 4, repeat: Infinity }}
          className="absolute top-10 end-20 w-20 h-20 bg-white/10 rounded-full blur-xl"
        />
        <div className={`relative z-10 px-6 text-center ${result ? 'py-10' : 'pt-12 pb-24 md:pt-16 md:pb-28'}`}>
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
            className="inline-flex items-center gap-2 bg-white/20 backdrop-blur-sm px-4 py-2 rounded-full mb-4"
          >
            <PackageSearch size={16} className="text-white" />
            <span className="text-white text-sm font-medium uppercase tracking-wide">{t('badge')}</span>
          </motion.div>
          <motion.h1
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: 0.1 }}
            className="text-3xl md:text-4xl font-bold text-white mb-3"
          >
            {result ? t('result.orderNumber', { number: result.order.order_number }) : t('title')}
          </motion.h1>
          {!result && (
            <motion.p
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.2 }}
              className="text-white/80 text-base md:text-lg max-w-2xl mx-auto"
            >
              {t('subtitle')}
            </motion.p>
          )}
        </div>
      </section>

      {result ? (
        <TrackResultView result={result} onTrackAnother={trackAnother} />
      ) : (
        <div className="relative z-10 max-w-xl mx-auto -mt-16 md:-mt-20">
          <form onSubmit={handleSubmit} noValidate className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 md:p-8 space-y-5">
            <div>
              <label htmlFor="track-order-number" className="block text-sm font-medium text-dark mb-1.5">
                {t('form.orderNumber')}
              </label>
              <input
                id="track-order-number"
                type="text"
                value={orderNumber}
                onChange={(e) => setOrderNumber(e.target.value)}
                placeholder={t('form.orderNumberPlaceholder')}
                autoComplete="off"
                className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 transition uppercase placeholder:normal-case"
              />
              <p className="text-xs text-gray-custom mt-1">{t('form.orderNumberHint')}</p>
            </div>

            <div>
              <label htmlFor="track-order-contact" className="block text-sm font-medium text-dark mb-1.5">
                {t('form.contact')}
              </label>
              <input
                id="track-order-contact"
                type="text"
                inputMode="email"
                value={contact}
                onChange={(e) => setContact(e.target.value)}
                placeholder={t('form.contactPlaceholder')}
                autoComplete="email"
                className="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 transition"
              />
            </div>

            {error && (
              <div role="alert" className="flex items-start gap-2 bg-red-50 border border-red-100 text-red-700 text-sm rounded-lg p-3">
                <XCircle size={16} className="shrink-0 mt-0.5" />
                <span>{error}</span>
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              className="w-full flex items-center justify-center gap-2 bg-gradient-primary text-white py-3 rounded-lg font-medium hover:shadow-md transition disabled:opacity-60 cursor-pointer"
            >
              {loading ? <Loader2 size={18} className="animate-spin" /> : <Search size={18} />}
              {loading ? t('form.submitting') : t('form.submit')}
            </button>

            {isLoggedIn && (
              <p className="text-center text-sm text-gray-custom">
                {t('form.loggedInHint')}{' '}
                <Link href="/account/orders" className="text-primary font-medium hover:underline">
                  {t('form.myOrders')}
                </Link>
              </p>
            )}
          </form>
        </div>
      )}
    </Container>
  )
}

// ─── Result view ─────────────────────────────────────────────────────────────

function TrackResultView({ result, onTrackAnother }: { result: TrackResult; onTrackAnother: () => void }) {
  const t = useTranslations('TrackOrder')
  const locale = useLocale()
  const formatAmount = useCurrencyStore((s) => s.formatAmount)
  const { order, items, history } = result

  const formatDate = (value: string) =>
    new Date(value).toLocaleDateString(locale, { day: 'numeric', month: 'short', year: 'numeric' })
  const formatDateTime = (value: string) =>
    new Date(value).toLocaleString(locale, { day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit' })

  const terminal = isTerminal(order.status) ? order.status : null
  const reached = reachedStepIndex(order, history)
  const progressPercent = terminal ? 0 : (reached / (STEPS.length - 1)) * 100

  const subtotal = items.reduce((sum, item) => sum + item.total_price, 0)
  const total = Math.max(subtotal + order.delivery_fee + order.tax_amount - order.coupon_discount_amount, 0)

  const terminalEntry = terminal ? lastEntryFor(history, terminal) : undefined
  const terminalTime = terminalEntry?.created_at ?? order.cancelled_at ?? order.updated_at

  const HeaderIcon = terminal ? TERMINAL_ICONS[terminal] : STEP_ICONS[STEPS[Math.max(reached, 0)]]

  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
      className="mt-8 grid lg:grid-cols-3 gap-6"
    >
      <div className="lg:col-span-2 space-y-6">
        {/* Current status */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-start gap-4">
            <div
              className={`w-14 h-14 shrink-0 rounded-full flex items-center justify-center ${
                terminal ? TERMINAL_COLORS[terminal] : order.status === 'delivered' ? 'bg-green-500 text-white' : 'bg-primary text-white'
              }`}
            >
              <HeaderIcon size={26} />
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex flex-wrap items-center gap-2 mb-1">
                <OrderStatusBadge status={order.status} className="text-sm px-3 py-1" />
              </div>
              <p className="text-dark font-medium">{t(`statusMessage.${order.status}`)}</p>
              <p className="text-xs text-gray-custom mt-1 flex flex-wrap gap-x-3">
                <span>{t('result.placedOn', { date: formatDate(order.created_at) })}</span>
                <span>{t('result.lastUpdated', { date: formatDateTime(order.updated_at) })}</span>
              </p>
            </div>
          </div>

          {!terminal && (
            <div className="mt-6">
              <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                <div
                  style={{ width: `${progressPercent}%` }}
                  className={`h-full rounded-full transition-[width] duration-700 ${order.status === 'delivered' ? 'bg-green-500' : 'bg-gradient-primary'}`}
                />
              </div>
              <div className="flex justify-between mt-2 text-[11px] sm:text-xs text-gray-custom">
                {STEPS.map((step, i) => (
                  <span key={step} className={i <= reached ? 'text-dark font-medium' : ''}>
                    {t(`steps.${step}`)}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Delivery progress timeline */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h3 className="font-semibold text-dark mb-6">{t('result.progress')}</h3>
          <ol className="relative">
            {STEPS.map((step, index) => {
              const done = index <= reached
              const isCurrent = !terminal && index === reached && step !== 'delivered'
              const entry = lastEntryFor(history, step)
              const time = entry?.created_at ?? (step === 'pending' ? order.created_at : undefined)
              const Icon = STEP_ICONS[step]
              const isLast = index === STEPS.length - 1 && !terminal
              // Past the step the order stopped at, a terminal order's
              // remaining normal steps are shown as skipped, not pending.
              const skipped = !!terminal && index > reached
              if (skipped) return null
              const lineDone = terminal ? true : index < reached

              return (
                <li key={step} className="relative ps-14 pb-7 last:pb-0">
                  {!isLast && (
                    <span
                      aria-hidden
                      className={`absolute start-5 top-10 -bottom-0 w-0.5 ${lineDone ? 'bg-primary' : 'bg-gray-200'}`}
                    />
                  )}
                  <span
                    className={`absolute start-0 top-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'
                    }`}
                  >
                    {isCurrent && <span className="absolute inset-0 rounded-full bg-primary/40 animate-ping" />}
                    <Icon size={18} className="relative" />
                  </span>
                  <div className="pt-1.5">
                    <h4 className={`font-semibold ${done ? 'text-dark' : 'text-gray-custom'}`}>{t(`steps.${step}`)}</h4>
                    {done && time && (
                      <p className="text-xs text-gray-custom mt-0.5 flex items-center gap-1">
                        <Clock size={12} /> {formatDateTime(time)}
                      </p>
                    )}
                    {done && entry?.note && (
                      <p className="text-sm text-gray-custom mt-1.5 bg-gray-50 rounded-lg px-3 py-2">{entry.note}</p>
                    )}
                  </div>
                </li>
              )
            })}

            {terminal && (() => {
              const Icon = TERMINAL_ICONS[terminal]
              return (
                <li className="relative ps-14">
                  <span className={`absolute start-0 top-0 w-10 h-10 rounded-full flex items-center justify-center z-10 ${TERMINAL_COLORS[terminal]}`}>
                    <Icon size={18} />
                  </span>
                  <div className="pt-1.5">
                    <h4 className="font-semibold text-dark">{t(`steps.${terminal}`)}</h4>
                    <p className="text-xs text-gray-custom mt-0.5 flex items-center gap-1">
                      <Clock size={12} /> {formatDateTime(terminalTime)}
                    </p>
                    {terminalEntry?.note && (
                      <p className="text-sm text-gray-custom mt-1.5 bg-gray-50 rounded-lg px-3 py-2">{terminalEntry.note}</p>
                    )}
                  </div>
                </li>
              )
            })()}
          </ol>
        </div>

        {/* Activity log — every customer-visible status change, newest first */}
        {history.length > 1 && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h3 className="font-semibold text-dark mb-4">{t('result.activity')}</h3>
            <ul className="divide-y divide-gray-100">
              {[...history].reverse().map((entry, i) => (
                <li key={`${entry.status}-${entry.created_at}-${i}`} className="py-3 first:pt-0 last:pb-0 flex flex-wrap items-start justify-between gap-2">
                  <div className="min-w-0">
                    <OrderStatusBadge status={entry.status} />
                    {entry.note && <p className="text-sm text-gray-custom mt-1">{entry.note}</p>}
                  </div>
                  <span className="text-xs text-gray-custom whitespace-nowrap">{formatDateTime(entry.created_at)}</span>
                </li>
              ))}
            </ul>
          </div>
        )}

        {/* Items */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h3 className="font-semibold text-dark mb-4">{t('result.items')}</h3>
          <div className="space-y-3">
            {items.map((item) => (
              <div key={item.id} className="flex justify-between items-center gap-3 py-2 border-b border-gray-100 last:border-0">
                <div className="flex items-center gap-3 min-w-0">
                  <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 className="min-w-0">
                    <p className="font-medium text-dark truncate">{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('result.qty', { count: item.quantity })}</p>
                  </div>
                </div>
                <p className="font-medium text-dark whitespace-nowrap">{formatAmount(item.total_price)}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Sidebar */}
      <div className="space-y-6">
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h3 className="font-semibold text-dark mb-4">{t('result.summary')}</h3>
          <div className="space-y-2 text-sm">
            <div className="flex justify-between">
              <span className="text-gray-custom">{t('result.subtotal')}</span>
              <span>{formatAmount(subtotal)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-custom">{t('result.deliveryFee')}</span>
              <span>{order.delivery_fee === 0 ? t('result.free') : formatAmount(order.delivery_fee)}</span>
            </div>
            {order.tax_amount > 0 && (
              <div className="flex justify-between">
                <span className="text-gray-custom">{t('result.tax', { percentage: order.tax_percentage })}</span>
                <span>{formatAmount(order.tax_amount)}</span>
              </div>
            )}
            {order.coupon_discount_amount > 0 && (
              <div className="flex justify-between text-green-600">
                <span>{t('result.discount')}</span>
                <span>- {formatAmount(order.coupon_discount_amount)}</span>
              </div>
            )}
            <div className="border-t border-gray-100 pt-2 mt-2 flex justify-between font-semibold">
              <span>{t('result.total')}</span>
              <span className="text-primary">{formatAmount(total)}</span>
            </div>
          </div>

          <div className="mt-4 space-y-3 text-sm">
            <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
              <CreditCard size={16} className="text-primary shrink-0 mt-0.5" />
              <div>
                <p className="text-gray-custom text-xs">{t('result.payment')}</p>
                <p className="text-dark font-medium">
                  {t(`paymentMethod.${order.payment_method}`)} · {t(`paymentStatus.${order.payment_status}`)}
                </p>
              </div>
            </div>
            {(order.shipping_full_name || order.shipping_city) && (
              <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                <MapPin size={16} className="text-primary shrink-0 mt-0.5" />
                <div>
                  <p className="text-gray-custom text-xs">{t('result.deliverTo')}</p>
                  <p className="text-dark font-medium">
                    {[order.shipping_full_name, order.shipping_city].filter(Boolean).join(', ')}
                  </p>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="bg-primary/5 border border-primary/20 rounded-xl p-5 text-center">
          <MessageCircle size={22} className="text-primary mx-auto mb-2" />
          <p className="text-sm text-dark font-medium mb-3">{t('result.needHelp')}</p>
          <Link
            href={`/contact?subject=order&order=${encodeURIComponent(order.order_number)}`}
            className="inline-flex items-center justify-center gap-2 bg-gradient-primary text-white px-5 py-2.5 rounded-lg text-sm font-medium hover:shadow-md transition"
          >
            {t('result.contactSupport')}
          </Link>
        </div>

        <button
          type="button"
          onClick={onTrackAnother}
          className="w-full flex items-center justify-center gap-2 border border-gray-200 text-dark py-3 rounded-lg font-medium hover:border-primary hover:text-primary transition cursor-pointer"
        >
          <ArrowLeft size={18} className="rtl:rotate-180" />
          {t('result.trackAnother')}
        </button>
      </div>
    </motion.div>
  )
}
