'use client'

import { useState } from 'react'
import { X, Clock, AlertTriangle, Info } from 'lucide-react'
import type { TenantInfo } from '@/components/providers/auth-provider'

interface TrialBannerProps {
  tenant: TenantInfo
}

export function TrialBanner({ tenant }: TrialBannerProps) {
  const [dismissed, setDismissed] = useState(false)

  if (dismissed) return null
  if (tenant.subscriptionStatus !== 'TRIAL') return null
  if (!tenant.trialEndsAt) return null

  const now = new Date()
  const trialEnd = new Date(tenant.trialEndsAt)
  const diffMs = trialEnd.getTime() - now.getTime()
  const daysLeft = Math.ceil(diffMs / (1000 * 60 * 60 * 24))

  // Don't show if trial already expired (handled elsewhere) or more than 14 days left
  if (daysLeft > 14) return null

  const isExpired = daysLeft <= 0
  const isUrgent = daysLeft <= 3
  const isWarning = daysLeft <= 7

  let bgColor = 'bg-blue-50 border-blue-200 text-blue-800'
  let Icon = Info
  let message = ''

  if (isExpired) {
    bgColor = 'bg-red-50 border-red-200 text-red-800'
    Icon = AlertTriangle
    message = `Ihre Testphase ist abgelaufen. Ihr Konto wurde auf den Free-Plan umgestellt. Upgraden Sie für erweiterte Funktionen.`
  } else if (isUrgent) {
    bgColor = 'bg-orange-50 border-orange-200 text-orange-800'
    Icon = AlertTriangle
    message = `Ihre Testphase endet ${daysLeft === 1 ? 'morgen' : `in ${daysLeft} Tagen`}. Danach wechselt Ihr Konto automatisch zum Free-Plan.`
  } else if (isWarning) {
    bgColor = 'bg-yellow-50 border-yellow-200 text-yellow-800'
    Icon = Clock
    message = `Noch ${daysLeft} Tage in Ihrer Testphase. Upgraden Sie rechtzeitig, um alle Funktionen zu behalten.`
  } else {
    bgColor = 'bg-blue-50 border-blue-200 text-blue-800'
    Icon = Info
    message = `Testphase: Noch ${daysLeft} Tage. Sie nutzen aktuell alle Funktionen kostenlos.`
  }

  const endDateStr = trialEnd.toLocaleDateString('de-CH', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  })

  return (
    <div className={`${bgColor} border-b px-4 py-2 flex items-center gap-3 text-sm shrink-0 print:hidden`}>
      <Icon className="w-4 h-4 shrink-0" />
      <div className="flex-1 min-w-0">
        <span className="font-medium">{message}</span>
        <span className="text-xs opacity-75 ml-2">(Ablauf: {endDateStr})</span>
      </div>
      {!isExpired && (
        <button
          onClick={() => setDismissed(true)}
          className="p-1 rounded hover:bg-black/10 transition-colors shrink-0"
          title="Ausblenden"
        >
          <X className="w-3.5 h-3.5" />
        </button>
      )}
    </div>
  )
}
