'use client'

import { useState } from 'react'
import { useBannerConsents } from '../_hooks/useBannerConsents'
import { BannerConsentRecord, PAGE_SIZE } from '../_types'

function formatDate(iso: string | null): string {
  if (!iso) return '—'
  return new Date(iso).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })
}

function shortenFingerprint(fp: string): string {
  return fp.length > 12 ? fp.slice(0, 12) + '...' : fp
}

function shortenUA(ua: string | null): string {
  if (!ua) return '—'
  const match = ua.match(/(Chrome|Safari|Firefox|Edge|Opera)\/[\d.]+/)
  if (match) return match[0]
  return ua.length > 30 ? ua.slice(0, 30) + '...' : ua
}

const categoryColors: Record<string, string> = {
  essential: 'bg-gray-100 text-gray-700',
  functional: 'bg-blue-100 text-blue-700',
  analytics: 'bg-purple-100 text-purple-700',
  marketing: 'bg-pink-100 text-pink-700',
}

export default function BannerConsentsTab() {
  const {
    records, sites, selectedSite, changeSite,
    stats, currentPage, setCurrentPage, totalRecords, loading,
  } = useBannerConsents()

  const [detail, setDetail] = useState<BannerConsentRecord | null>(null)
  const totalPages = Math.ceil(totalRecords / PAGE_SIZE)

  return (
    <div className="space-y-6">
      {/* Stats + Site Selector */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className="text-sm text-gray-500">
            <span className="text-2xl font-bold text-gray-900">{totalRecords}</span> Consents
          </div>
          {stats && Object.keys(stats.category_acceptance).length > 0 && (
            <div className="flex gap-2">
              {Object.entries(stats.category_acceptance).map(([cat, data]) => (
                <span key={cat} className={`text-xs px-2 py-1 rounded-full ${categoryColors[cat] || 'bg-gray-100 text-gray-600'}`}>
                  {cat}: {data.rate}%
                </span>
              ))}
            </div>
          )}
        </div>
        {sites.length > 0 && (
          <select
            value={selectedSite}
            onChange={e => changeSite(e.target.value)}
            className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm bg-white"
          >
            {sites.map(s => (
              <option key={s.site_id} value={s.site_id}>
                {s.site_name || s.site_id}
              </option>
            ))}
          </select>
        )}
      </div>

      {/* Table */}
      <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Device</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Kategorien</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Verknüpft mit</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Erteilt am</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Ablauf</th>
              <th className="text-left px-4 py-3 font-medium text-gray-500">Browser</th>
              <th className="text-right px-4 py-3 font-medium text-gray-500">Aktion</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {loading && records.length === 0 ? (
              <tr><td colSpan={7} className="px-4 py-8 text-center text-gray-400">Laden...</td></tr>
            ) : records.length === 0 ? (
              <tr><td colSpan={7} className="px-4 py-8 text-center text-gray-400">Keine Consents vorhanden</td></tr>
            ) : (
              records.map(record => (
                <tr key={record.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-4 py-3 font-mono text-xs text-gray-600">{shortenFingerprint(record.device_fingerprint)}</td>
                  <td className="px-4 py-3">
                    <div className="flex flex-wrap gap-1">
                      {record.categories.length > 0 ? record.categories.map(cat => (
                        <span key={cat} className={`text-xs px-2 py-0.5 rounded-full ${categoryColors[cat] || 'bg-gray-100 text-gray-600'}`}>
                          {cat}
                        </span>
                      )) : <span className="text-xs text-gray-400">—</span>}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-xs">
                    {record.linked_email
                      ? <span className="text-purple-600">{record.linked_email}</span>
                      : <span className="text-gray-400">— (anonym)</span>
                    }
                  </td>
                  <td className="px-4 py-3 text-xs text-gray-600">{formatDate(record.created_at)}</td>
                  <td className="px-4 py-3 text-xs text-gray-600">{formatDate(record.expires_at)}</td>
                  <td className="px-4 py-3 text-xs text-gray-500">{shortenUA(record.user_agent)}</td>
                  <td className="px-4 py-3 text-right">
                    <button
                      onClick={() => setDetail(record)}
                      className="text-xs text-purple-600 hover:text-purple-800 font-medium"
                    >
                      Details
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between">
          <span className="text-xs text-gray-500">
            Seite {currentPage} von {totalPages} ({totalRecords} Einträge)
          </span>
          <div className="flex gap-1">
            <button
              onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
              disabled={currentPage <= 1}
              className="px-3 py-1 text-xs border border-gray-300 rounded disabled:opacity-30"
            >
              Zurück
            </button>
            <button
              onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
              disabled={currentPage >= totalPages}
              className="px-3 py-1 text-xs border border-gray-300 rounded disabled:opacity-30"
            >
              Weiter
            </button>
          </div>
        </div>
      )}

      {/* Detail Modal */}
      {detail && (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4" onClick={() => setDetail(null)}>
          <div className="bg-white rounded-2xl shadow-xl max-w-lg w-full p-6 max-h-[80vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-900">Consent Details</h3>
              <button onClick={() => setDetail(null)} className="text-gray-400 hover:text-gray-600 text-xl">&times;</button>
            </div>

            <div className="space-y-3 text-sm">
              <div className="flex justify-between"><span className="text-gray-500">ID</span><span className="font-mono text-xs">{detail.id}</span></div>
              <div className="flex justify-between"><span className="text-gray-500">Site</span><span>{detail.site_id}</span></div>
              <div className="flex justify-between"><span className="text-gray-500">Device</span><span className="font-mono text-xs">{detail.device_fingerprint}</span></div>
              <div className="flex justify-between items-start">
                <span className="text-gray-500">Kategorien</span>
                <div className="flex flex-wrap gap-1 justify-end">
                  {detail.categories.map(cat => (
                    <span key={cat} className={`text-xs px-2 py-0.5 rounded-full ${categoryColors[cat] || 'bg-gray-100'}`}>{cat}</span>
                  ))}
                </div>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Verknüpft mit</span>
                <span>{detail.linked_email || '— (anonym)'}</span>
              </div>
              <div className="flex justify-between"><span className="text-gray-500">Erteilt</span><span>{formatDate(detail.created_at)}</span></div>
              <div className="flex justify-between"><span className="text-gray-500">Ablauf</span><span>{formatDate(detail.expires_at)}</span></div>
              <div className="flex justify-between"><span className="text-gray-500">Aktualisiert</span><span>{formatDate(detail.updated_at)}</span></div>
              <div className="border-t border-gray-100 pt-3">
                <span className="text-gray-500 text-xs">User-Agent</span>
                <p className="text-xs text-gray-600 mt-1 font-mono break-all">{detail.user_agent || '—'}</p>
              </div>
              {detail.ip_hash && (
                <div>
                  <span className="text-gray-500 text-xs">IP-Hash</span>
                  <p className="text-xs text-gray-600 mt-1 font-mono">{detail.ip_hash}</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
