'use client'

import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'

const STATUSES = [
  { value: 'PENDING', label: 'Beklemede' },
  { value: 'CONFIRMED', label: 'Onaylandı' },
  { value: 'PREPARING', label: 'Hazırlanıyor' },
  { value: 'SHIPPED', label: 'Kargoya Verildi' },
  { value: 'DELIVERED', label: 'Teslim Edildi' },
  { value: 'CANCELLED', label: 'İptal Edildi' },
]

interface Props {
  orderNo: string
  currentStatus: string
  paymentMethod: string
  paymentStatus: string
}

export default function AdminOrderActions({ orderNo, currentStatus, paymentMethod, paymentStatus }: Props) {
  const router = useRouter()
  const [status, setStatus] = useState(currentStatus)
  const [description, setDescription] = useState('')
  const [trackingNo, setTrackingNo] = useState('')
  const [pStatus, setPStatus] = useState(paymentStatus)
  const [pending, start] = useTransition()
  const [msg, setMsg] = useState<{ type: 'ok' | 'err'; text: string } | null>(null)

  async function updateStatus() {
    start(async () => {
      setMsg(null)
      const res = await fetch(`/api/admin/orders/${orderNo}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status, description, trackingNo }),
      })
      if (res.ok) {
        setMsg({ type: 'ok', text: 'Durum güncellendi, bayi bilgilendirildi.' })
        router.refresh()
      } else {
        const d = await res.json()
        setMsg({ type: 'err', text: d.error ?? 'Güncelleme başarısız' })
      }
    })
  }

  async function confirmPayment() {
    start(async () => {
      setMsg(null)
      const res = await fetch(`/api/admin/orders/${orderNo}/payment`, { method: 'PATCH' })
      if (res.ok) {
        setPStatus('PAID')
        setMsg({ type: 'ok', text: 'Ödeme onaylandı, bayi bilgilendirildi.' })
        router.refresh()
      } else {
        const d = await res.json()
        setMsg({ type: 'err', text: d.error ?? 'İşlem başarısız' })
      }
    })
  }

  const ic = 'w-full px-3 py-2 rounded-lg border border-sand bg-cream font-body text-sm focus:outline-none focus:border-earth transition-colors'

  return (
    <div className="space-y-4">
      {/* Durum güncelle */}
      <div className="bg-white p-5 shadow-sm rounded-xl space-y-4">
        <h3 className="font-display text-lg text-brown">Sipariş Durumu</h3>
        <select value={status} onChange={e => setStatus(e.target.value)} className={ic}>
          {STATUSES.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
        </select>
        {status === 'SHIPPED' && (
          <input type="text" placeholder="Kargo takip no" value={trackingNo}
            onChange={e => setTrackingNo(e.target.value)} className={ic} />
        )}
        <textarea rows={2} placeholder="Bayiye gönderilecek açıklama (opsiyonel)"
          value={description} onChange={e => setDescription(e.target.value)}
          className={`${ic} resize-none`} />
        <button onClick={updateStatus} disabled={pending}
          className="w-full py-2 rounded-lg bg-brown text-cream font-body text-sm tracking-widest uppercase hover:bg-earth transition-colors disabled:opacity-60">
          {pending ? 'Güncelleniyor...' : 'Durumu Güncelle'}
        </button>
      </div>

      {/* Ödeme onaylama — sadece Havale + WAITING */}
      {paymentMethod === 'BANK_TRANSFER' && pStatus === 'WAITING' && (
        <div className="bg-white p-5 shadow-sm rounded-xl">
          <h3 className="font-display text-lg text-brown mb-3">Ödeme Onayı</h3>
          <p className="font-body text-xs text-brown/50 mb-3">
            Havale alındığında aşağıdaki butona basın. Bayi'ye email gönderilir.
          </p>
          <button onClick={confirmPayment} disabled={pending}
            className="w-full py-2 rounded-lg bg-green-700 text-white font-body text-sm tracking-widest uppercase hover:bg-green-800 transition-colors disabled:opacity-60">
            Ödeme Alındı ✓
          </button>
        </div>
      )}

      {pStatus === 'PAID' && (
        <div className="bg-green-50 border border-green-200 rounded-lg p-4">
          <p className="font-body text-sm text-green-700 font-medium">✓ Ödeme Onaylandı</p>
        </div>
      )}

      {msg && (
        <div className={`p-3 rounded-lg font-body text-sm ${msg.type === 'ok' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-600'}`}>
          {msg.text}
        </div>
      )}
    </div>
  )
}
