'use client'

import { useState, useTransition } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import AdminDealerToggle from './AdminDealerToggle'
import AdminDealerDelete from './AdminDealerDelete'

export interface DealerRow {
  id: number
  companyName: string
  contactName: string
  dealerCode: string
  email: string
  phone: string | null
  discountRate: number
  isActive: boolean
  status: string
  createdAt: string
  orderCount: number
}

interface Props {
  active: DealerRow[]
  pending: DealerRow[]
}

export default function AdminDealersClient({ active, pending }: Props) {
  const [tab, setTab] = useState<'active' | 'pending'>(pending.length > 0 ? 'pending' : 'active')

  return (
    <div>
      {/* Sekmeler */}
      <div className="flex items-center gap-2 mb-6 border-b border-sand">
        <button
          onClick={() => setTab('active')}
          className={`px-4 py-2.5 font-body text-sm tracking-wide transition-colors border-b-2 -mb-px ${
            tab === 'active' ? 'border-orange text-brown font-medium' : 'border-transparent text-brown/50 hover:text-brown'
          }`}
        >
          Aktif Bayiler ({active.length})
        </button>
        <button
          onClick={() => setTab('pending')}
          className={`px-4 py-2.5 font-body text-sm tracking-wide transition-colors border-b-2 -mb-px flex items-center gap-2 ${
            tab === 'pending' ? 'border-orange text-brown font-medium' : 'border-transparent text-brown/50 hover:text-brown'
          }`}
        >
          Bekleyen Başvurular
          {pending.length > 0 && (
            <span className="bg-orange text-cream text-xs font-medium px-2 py-0.5 rounded-full">{pending.length}</span>
          )}
        </button>
      </div>

      {tab === 'active' ? <ActiveTable rows={active} /> : <PendingTable rows={pending} />}
    </div>
  )
}

function ActiveTable({ rows }: { rows: DealerRow[] }) {
  if (rows.length === 0) {
    return <p className="font-body text-sm text-brown/40 py-12 text-center">Kayıtlı bayi yok.</p>
  }
  return (
    <div className="bg-white shadow-sm rounded-xl overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="bg-sand/50 text-left">
              {['Firma', 'Bayi Kodu', 'Email', 'İndirim', 'Sipariş', 'Durum', 'Düzenle', 'Sil'].map(h => (
                <th key={h} className="px-5 py-3 font-body text-xs text-brown/50 tracking-widest uppercase whitespace-nowrap">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-sand">
            {rows.map(d => (
              <tr key={d.id} className="hover:bg-sand/20 transition-colors">
                <td className="px-5 py-3">
                  <p className="font-body text-sm font-medium text-brown">{d.companyName}</p>
                  <p className="font-body text-xs text-brown/40">{d.contactName}</p>
                </td>
                <td className="px-5 py-3 font-mono text-sm text-earth">{d.dealerCode}</td>
                <td className="px-5 py-3 font-body text-sm text-brown/70">{d.email}</td>
                <td className="px-5 py-3 font-body text-sm text-brown">{d.discountRate > 0 ? `%${d.discountRate}` : '—'}</td>
                <td className="px-5 py-3 font-body text-sm text-brown">{d.orderCount}</td>
                <td className="px-5 py-3"><AdminDealerToggle id={d.id} isActive={d.isActive} /></td>
                <td className="px-5 py-3">
                  <Link href={`/admin/dealers/${d.id}/edit`} className="font-body text-xs text-earth hover:text-brown transition-colors">
                    Düzenle
                  </Link>
                </td>
                <td className="px-5 py-3"><AdminDealerDelete id={d.id} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}

function PendingTable({ rows }: { rows: DealerRow[] }) {
  if (rows.length === 0) {
    return <p className="font-body text-sm text-brown/40 py-12 text-center">Bekleyen başvuru yok.</p>
  }
  return (
    <div className="bg-white shadow-sm rounded-xl overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="bg-sand/50 text-left">
              {['Firma', 'Ad Soyad', 'Email', 'Telefon', 'Başvuru Tarihi', 'İşlem'].map(h => (
                <th key={h} className="px-5 py-3 font-body text-xs text-brown/50 tracking-widest uppercase whitespace-nowrap">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-sand">
            {rows.map(d => (
              <PendingRow key={d.id} dealer={d} />
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}

function PendingRow({ dealer }: { dealer: DealerRow }) {
  const router = useRouter()
  const [pending, start] = useTransition()
  const [error, setError] = useState<string | null>(null)

  function act(action: 'approve' | 'reject') {
    if (action === 'reject' && !confirm(`"${dealer.companyName}" başvurusunu reddetmek istediğinize emin misiniz?`)) return
    start(async () => {
      setError(null)
      try {
        const res = await fetch(`/api/admin/dealers/${dealer.id}/${action}`, { method: 'PATCH' })
        if (res.ok) {
          router.refresh()
          return
        }
        const d = await res.json().catch(() => ({}))
        setError(d.error ?? 'İşlem başarısız.')
      } catch {
        setError('Bir hata oluştu.')
      }
    })
  }

  return (
    <tr className="hover:bg-sand/20 transition-colors">
      <td className="px-5 py-3 font-body text-sm font-medium text-brown">{dealer.companyName}</td>
      <td className="px-5 py-3 font-body text-sm text-brown/70">{dealer.contactName}</td>
      <td className="px-5 py-3 font-body text-sm text-brown/70">{dealer.email}</td>
      <td className="px-5 py-3 font-body text-sm text-brown/70">{dealer.phone ?? '—'}</td>
      <td className="px-5 py-3 font-body text-sm text-brown/60">
        {new Date(dealer.createdAt).toLocaleDateString('tr-TR')}
      </td>
      <td className="px-5 py-3">
        <div className="flex flex-col items-start gap-1">
          <div className="flex items-center gap-2">
            <button
              onClick={() => act('approve')}
              disabled={pending}
              className="px-3 py-1.5 rounded-lg bg-green-600 text-white font-body text-xs hover:bg-green-700 transition-colors disabled:opacity-50"
            >
              ✅ Onayla
            </button>
            <button
              onClick={() => act('reject')}
              disabled={pending}
              className="px-3 py-1.5 rounded-lg bg-red-600 text-white font-body text-xs hover:bg-red-700 transition-colors disabled:opacity-50"
            >
              ❌ Reddet
            </button>
          </div>
          {error && <span className="font-body text-xs text-red-600">{error}</span>}
        </div>
      </td>
    </tr>
  )
}
