'use client'

import Link from 'next/link'
import { useCallback, useState } from 'react'
import { LISTING_CATEGORIES } from '@/data/listing-field-options'
import type { ListingImportRow } from '@/lib/listing-imports'
import type { ImportStatus } from '@/lib/listing-imports'

type Props = {
  initialItems: ListingImportRow[]
  initialCounts: Record<ImportStatus, number>
  loadError?: string | null
}

export default function AdminImportShell({ initialItems, initialCounts, loadError }: Props) {
  const [items, setItems] = useState(initialItems)
  const [counts, setCounts] = useState(initialCounts)
  const [busyId, setBusyId] = useState<string | null>(null)
  const [runBusy, setRunBusy] = useState(false)
  const [message, setMessage] = useState<string | null>(null)
  const [categoryOverrides, setCategoryOverrides] = useState<Record<string, string>>({})

  const refresh = useCallback(async () => {
    const res = await fetch('/api/admin/imports', { cache: 'no-store' })
    if (!res.ok) {
      const data = (await res.json().catch(() => ({}))) as { error?: string }
      setMessage(data.error ?? `Błąd odczytu listy (${res.status}).`)
      return
    }
    const data = (await res.json()) as { items: ListingImportRow[]; counts: Record<ImportStatus, number> }
    setItems(data.items)
    setCounts(data.counts)
  }, [])

  async function runDiagnose() {
    setMessage(null)
    try {
      const res = await fetch('/api/admin/imports/diagnose', { cache: 'no-store' })
      const data = await res.json()
      if (!res.ok) {
        setMessage(data.error ?? 'Błąd diagnostyki.')
        return
      }
      const c = data.staging.countsByStatus as Record<string, number> | undefined
      const statusLine = c
        ? ` · w bazie: pending ${c.pending ?? 0}, approved ${c.approved ?? 0}, rejected ${c.rejected ?? 0}, expired ${c.expired ?? 0}`
        : ` · staging pending: ${data.staging.pending}/${data.staging.total}`
      setMessage(
        `Diagnostyka: OLX ${data.olx.ok ? 'OK' : 'BŁĄD'} (${data.olx.sampleCount} ofert próbka)` +
          `${data.olx.error ? ` — ${data.olx.error}` : ''}` +
          statusLine +
          ` · limit: ${data.limits.maxOffersPerRun} ofert/przebieg.`,
      )
    } catch {
      setMessage('Błąd połączenia (diagnostyka).')
    }
  }

  async function runImport() {
    setRunBusy(true)
    setMessage('Import trwa — zwykle 1–3 minuty. Możesz odświeżyć stronę po chwili.')
    try {
      const res = await fetch('/api/admin/imports/run', { method: 'POST' })
      const data = await res.json()
      if (!res.ok) {
        setMessage(data.error ?? 'Błąd importu.')
        return
      }
      const c = data.counts as Record<string, number> | undefined
      const dbLine = c
        ? ` W bazie: oczekujące ${c.pending ?? 0}, zatwierdzone ${c.approved ?? 0}, odrzucone ${c.rejected ?? 0}.`
        : ''
      const skippedHint =
        data.result.skipped > 0 && data.result.created === 0 && data.result.updated === 0
          ? ' Pominięte = te same oferty OLX już są w bazie (zatwierdzone/odrzucone/wygasłe) — panel pokazuje tylko oczekujące.'
          : ''
      setMessage(
        `Import zakończony: ${data.result.created} nowych, ${data.result.updated} zaktualizowanych, ${data.result.skipped ?? 0} pominiętych (już w bazie), ${data.result.scanned} przeskanowanych.` +
          (data.result.errors ? ` Błędy: ${data.result.errors}.` : '') +
          (data.result.errorSamples?.length
            ? ` Przykłady: ${data.result.errorSamples.join(' · ')}`
            : '') +
          (data.result.stoppedReason ? ` (${data.result.stoppedReason})` : '') +
          dbLine +
          skippedHint +
          (data.result.created === 0 && data.result.scanned === 0
            ? ' Sprawdź „Diagnostyka” — możliwa blokada OLX na serwerze.'
            : ''),
      )
      if (c) setCounts(c as Record<ImportStatus, number>)
      await refresh()
    } catch {
      setMessage('Błąd połączenia podczas importu.')
    } finally {
      setRunBusy(false)
    }
  }

  async function approve(id: string) {
    setBusyId(id)
    setMessage(null)
    try {
      const categoryId = categoryOverrides[id]
      const res = await fetch(`/api/admin/imports/${id}/approve`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(categoryId ? { categoryId } : {}),
      })
      const data = await res.json()
      if (!res.ok) {
        setMessage(data.error ?? 'Błąd zatwierdzania.')
        return
      }
      setMessage(`Opublikowano: ${data.url}`)
      await refresh()
    } catch {
      setMessage('Błąd połączenia.')
    } finally {
      setBusyId(null)
    }
  }

  async function reject(id: string) {
    if (!confirm('Odrzucić tę ofertę? Nie trafi na giełdę.')) return
    setBusyId(id)
    setMessage(null)
    try {
      const res = await fetch(`/api/admin/imports/${id}/reject`, { method: 'POST' })
      const data = await res.json()
      if (!res.ok) {
        setMessage(data.error ?? 'Błąd odrzucania.')
        return
      }
      await refresh()
    } catch {
      setMessage('Błąd połączenia.')
    } finally {
      setBusyId(null)
    }
  }

  function formatPrice(item: ListingImportRow): string {
    if (item.priceOnRequest && item.pricePln == null) return 'Cena do uzgodnienia'
    if (item.pricePln != null) {
      const suffix = item.offerType === 'negotiable' ? ' (do negocjacji)' : ''
      return `${item.pricePln.toLocaleString('pl-PL')} zł${suffix}`
    }
    return '—'
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-100 to-slate-200 px-4 pb-16 pt-28">
      <div className="mx-auto max-w-5xl">
        <div className="mb-6 flex flex-wrap items-start justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Import ogłoszeń (OLX)</h1>
            <p className="mt-1 text-sm text-gray-600">
              Oferty oczekujące: <strong>{counts.pending}</strong> · zatwierdzone: {counts.approved} ·
              odrzucone: {counts.rejected}
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link
              href="/admin"
              className="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
            >
              Pulpit
            </Link>
            <button
              type="button"
              onClick={() => void runImport()}
              disabled={runBusy}
              className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-60"
            >
              {runBusy ? 'Importuję… (1–3 min)' : 'Uruchom import OLX'}
            </button>
            <button
              type="button"
              onClick={() => void runDiagnose()}
              disabled={runBusy}
              className="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-60"
            >
              Diagnostyka
            </button>
            <button
              type="button"
              onClick={() => void refresh()}
              disabled={runBusy}
              className="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-60"
            >
              Odśwież listę
            </button>
            <Link
              href="/profil"
              className="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
            >
              Moje konto
            </Link>
          </div>
        </div>

        {loadError ? (
          <p className="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-900">
            {loadError}
          </p>
        ) : null}

        {message ? (
          <p className="mb-4 rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-900">
            {message}
          </p>
        ) : null}

        {items.length === 0 ? (
          <div className="rounded-2xl border border-gray-200 bg-white p-8 text-center shadow-sm">
            <p className="text-gray-700">Brak ofert do moderacji.</p>
            {counts.pending > 0 ? (
              <p className="mt-2 text-sm text-amber-700">
                W bazie jest {counts.pending} oczekujących, ale lista się nie wczytała — kliknij Diagnostyka lub
                odśwież stronę (Ctrl+F5).
              </p>
            ) : null}
            <p className="mt-2 text-sm text-gray-500">
              Kliknij „Uruchom import OLX” lub poczekaj na cron. Upewnij się, że migracja SQL i DATABASE_URL są
              skonfigurowane.
            </p>
          </div>
        ) : (
          <ul className="space-y-6">
            {items.map((item) => (
              <li
                key={item.id}
                className="overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-sm"
              >
                <div className="grid gap-4 p-5 md:grid-cols-[200px_1fr]">
                  <div className="flex gap-2 overflow-x-auto md:flex-col md:overflow-y-auto md:max-h-48">
                    {(item.imagePaths.length > 0 ? item.imagePaths : ['/images/shop-hero.jpg']).map((src, i) => (
                      <div
                        key={`${item.id}-img-${i}`}
                        className="relative h-24 w-32 shrink-0 overflow-hidden rounded-lg bg-gray-100 md:h-20 md:w-full"
                      >
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img src={src} alt="" className="h-full w-full object-cover" loading="lazy" />
                      </div>
                    ))}
                  </div>

                  <div className="min-w-0">
                    <div className="flex flex-wrap items-start justify-between gap-2">
                      <h2 className="text-lg font-semibold text-gray-900">{item.title}</h2>
                      <span className="shrink-0 text-lg font-bold text-gray-900">{formatPrice(item)}</span>
                    </div>

                    <p className="mt-1 text-sm text-gray-600">
                      {item.suggestedCategoryLabel ?? '—'}
                      {item.locationText ? ` · ${item.locationText}` : ''}
                      {item.regionSlug ? ` · ${item.regionSlug}` : ''}
                      {item.sellerName ? ` · ${item.sellerName}` : ''}
                    </p>

                    <p className="mt-3 line-clamp-4 whitespace-pre-wrap text-sm text-gray-700">
                      {item.descriptionText || 'Brak opisu.'}
                    </p>

                    <div className="mt-4 flex flex-wrap items-center gap-3">
                      <label className="flex items-center gap-2 text-sm text-gray-700">
                        Kategoria:
                        <select
                          value={categoryOverrides[item.id] ?? item.suggestedCategoryId ?? 'power'}
                          onChange={(e) =>
                            setCategoryOverrides((prev) => ({ ...prev, [item.id]: e.target.value }))
                          }
                          className="rounded border border-gray-300 px-2 py-1 text-sm"
                        >
                          {LISTING_CATEGORIES.map((c) => (
                            <option key={c.id} value={c.id}>
                              {c.label}
                            </option>
                          ))}
                        </select>
                      </label>

                      <a
                        href={item.sourceUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-sm font-medium text-blue-700 underline"
                      >
                        Zobacz na OLX ↗
                      </a>
                    </div>

                    <div className="mt-4 flex flex-wrap gap-2">
                      <button
                        type="button"
                        disabled={busyId === item.id}
                        onClick={() => void approve(item.id)}
                        className="rounded-lg bg-green-600 px-4 py-2 text-sm font-semibold text-white hover:bg-green-700 disabled:opacity-60"
                      >
                        Zatwierdź i opublikuj
                      </button>
                      <button
                        type="button"
                        disabled={busyId === item.id}
                        onClick={() => void reject(item.id)}
                        className="rounded-lg border border-red-300 bg-white px-4 py-2 text-sm font-semibold text-red-700 hover:bg-red-50 disabled:opacity-60"
                      >
                        Odrzuć
                      </button>
                    </div>

                    <p className="mt-2 text-xs text-gray-400">
                      OLX #{item.externalId} · pobrano {new Date(item.scrapedAt).toLocaleString('pl-PL')}
                    </p>
                  </div>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  )
}
