'use client'

import { useState } from 'react'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import { History, Globe, User } from 'lucide-react'

import { ConsentRecord } from './_types'
import { useConsents } from './_hooks/useConsents'
import { EinwilligungenNavTabs } from './_components/EinwilligungenNavTabs'
import { StatsGrid } from './_components/StatsGrid'
import { SearchAndFilter } from './_components/SearchAndFilter'
import { RecordsTable } from './_components/RecordsTable'
import { Pagination } from './_components/Pagination'
import { ConsentDetailModal } from './_components/ConsentDetailModal'
import BannerConsentsTab from './_components/BannerConsentsTab'

type ConsentTab = 'visitors' | 'users'

export default function EinwilligungenPage() {
  const [activeTab, setActiveTab] = useState<ConsentTab>('visitors')

  const {
    records,
    currentPage,
    setCurrentPage,
    totalRecords,
    globalStats,
    handleRevoke,
  } = useConsents()

  const [filter, setFilter] = useState<string>('all')
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedRecord, setSelectedRecord] = useState<ConsentRecord | null>(null)

  const filteredRecords = records.filter(record => {
    const matchesFilter = filter === 'all' || record.consentType === filter || record.status === filter
    const matchesSearch = searchQuery === '' ||
      record.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      record.identifier.toLowerCase().includes(searchQuery.toLowerCase())
    return matchesFilter && matchesSearch
  })

  const versionUpdates = records.reduce(
    (acc, r) => acc + r.history.filter(h => h.action === 'version_update').length,
    0,
  )

  const stepInfo = STEP_EXPLANATIONS['einwilligungen']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="einwilligungen"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <ConsentExportButton />
      </StepHeader>

      {/* Navigation Tabs */}
      <EinwilligungenNavTabs />

      {/* Consent Type Tabs: Website-Besucher / Login-Nutzer */}
      <div className="flex gap-1 p-1 bg-gray-100 rounded-xl w-fit">
        <button
          onClick={() => setActiveTab('visitors')}
          className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
            activeTab === 'visitors'
              ? 'bg-white text-purple-700 shadow-sm'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          <Globe className="w-4 h-4" />
          Website-Besucher
        </button>
        <button
          onClick={() => setActiveTab('users')}
          className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
            activeTab === 'users'
              ? 'bg-white text-purple-700 shadow-sm'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          <User className="w-4 h-4" />
          Login-Nutzer
        </button>
      </div>

      {/* Tab Content */}
      {activeTab === 'visitors' ? (
        <BannerConsentsTab />
      ) : (
        <>
          {/* Stats */}
          <StatsGrid
            total={globalStats.total}
            active={globalStats.active}
            revoked={globalStats.revoked}
            versionUpdates={versionUpdates}
          />

          {/* Info Banner */}
          <div className="bg-gradient-to-r from-purple-50 to-indigo-50 rounded-xl border border-purple-200 p-4 flex items-start gap-3">
            <History className="w-5 h-5 text-purple-600 mt-0.5" />
            <div>
              <div className="font-medium text-purple-900">Consent-Historie aktiviert</div>
              <div className="text-sm text-purple-700">
                Alle Änderungen an Einwilligungen werden protokolliert, inkl. Zustimmungen zu neuen Versionen von AGB, DSI und anderen Dokumenten.
                Klicken Sie auf &quot;Details&quot; um die vollständige Historie eines Nutzers einzusehen.
              </div>
            </div>
          </div>

          {/* Search and Filter */}
          <SearchAndFilter
            searchQuery={searchQuery}
            onSearchChange={setSearchQuery}
            filter={filter}
            onFilterChange={setFilter}
          />

          {/* Records Table */}
          <RecordsTable records={filteredRecords} onShowDetails={setSelectedRecord} />

          {/* Pagination */}
          <Pagination
            currentPage={currentPage}
            totalRecords={totalRecords}
            onPageChange={setCurrentPage}
          />

          {/* Detail Modal */}
          {selectedRecord && (
            <ConsentDetailModal
              record={selectedRecord}
              onClose={() => setSelectedRecord(null)}
              onRevoke={handleRevoke}
            />
          )}
        </>
      )}
    </div>
  )
}

// Export-Dropdown im Step-Header. Streamt CSV/JSON direkt aus dem
// Backend via /api/sdk/v1/einwilligungen/export-Proxy.
function ConsentExportButton() {
  return (
    <div className="relative group">
      <button className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors">
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
        </svg>
        Export
      </button>
      <div className="absolute right-0 top-full mt-1 w-60 bg-white border border-gray-200 rounded-lg shadow-lg invisible group-hover:visible opacity-0 group-hover:opacity-100 transition-all z-10">
        <a href="/api/sdk/v1/einwilligungen/export?format=csv&kind=consents" download
           className="block px-4 py-2 text-sm text-gray-700 hover:bg-purple-50 first:rounded-t-lg">
          Einwilligungen als CSV
        </a>
        <a href="/api/sdk/v1/einwilligungen/export?format=json&kind=consents" download
           className="block px-4 py-2 text-sm text-gray-700 hover:bg-purple-50">
          Einwilligungen als JSON
        </a>
        <a href="/api/sdk/v1/einwilligungen/export?format=csv&kind=history" download
           className="block px-4 py-2 text-sm text-gray-700 hover:bg-purple-50 last:rounded-b-lg border-t border-gray-100">
          Aenderungs-Historie als CSV
        </a>
      </div>
    </div>
  )
}
