'use client'

import React, { useState, useEffect, useCallback } from 'react'
import { useTenantSelection } from '@payloadcms/plugin-multi-tenant/client'
import './TenantDashboard.scss'

interface EmailStats {
  total: number
  sent: number
  failed: number
  pending: number
  successRate: number
}

interface SourceStats {
  manual: number
  form: number
  system: number
  newsletter: number
}

interface RecentFailure {
  id: number
  to: string
  subject: string
  error: string
  createdAt: string
}

interface StatsResponse {
  success: boolean
  period: string
  periodStart: string
  stats: EmailStats
  bySource: SourceStats
  recentFailures: RecentFailure[]
}

type Period = '24h' | '7d' | '30d'

/**
 * Tenant Self-Service Dashboard
 * Zeigt E-Mail-Statistiken und Quick-Actions für Tenant-Admins
 */
export const TenantDashboard: React.FC = () => {
  const { selectedTenantID, options } = useTenantSelection()
  const [stats, setStats] = useState<StatsResponse | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [period, setPeriod] = useState<Period>('7d')

  // Aktueller Tenant-Name
  const currentTenant = options?.find((opt) => opt.value === selectedTenantID)
  // Handle localized labels (Record<string, string>) or plain strings
  const tenantName = currentTenant?.label
    ? (typeof currentTenant.label === 'string'
        ? currentTenant.label
        : (currentTenant.label as Record<string, string>)?.de || (currentTenant.label as Record<string, string>)?.en || String(selectedTenantID))
    : 'Unbekannt'

  const fetchStats = useCallback(async () => {
    if (!selectedTenantID) {
      setLoading(false)
      return
    }

    setLoading(true)
    setError(null)

    try {
      const response = await fetch(
        `/api/email-logs/stats?tenantId=${selectedTenantID}&period=${period}`,
        {
          credentials: 'include',
        },
      )

      if (!response.ok) {
        throw new Error('Fehler beim Laden der Statistiken')
      }

      const data = await response.json()
      setStats(data)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    } finally {
      setLoading(false)
    }
  }, [selectedTenantID, period])

  useEffect(() => {
    fetchStats()
  }, [fetchStats])

  // Formatiere Datum
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('de-DE', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    })
  }

  // Periode-Labels
  const periodLabels: Record<Period, string> = {
    '24h': 'Letzte 24 Stunden',
    '7d': 'Letzte 7 Tage',
    '30d': 'Letzte 30 Tage',
  }

  if (!selectedTenantID) {
    return (
      <div className="tenant-dashboard tenant-dashboard--empty">
        <p>Bitte wählen Sie einen Tenant aus, um das Dashboard anzuzeigen.</p>
      </div>
    )
  }

  return (
    <div className="tenant-dashboard">
      <div className="tenant-dashboard__header">
        <div className="tenant-dashboard__title-section">
          <h2 className="tenant-dashboard__title">Dashboard: {tenantName}</h2>
          <p className="tenant-dashboard__subtitle">E-Mail-Statistiken und Übersicht</p>
        </div>

        <div className="tenant-dashboard__controls">
          <select
            className="tenant-dashboard__period-select"
            value={period}
            onChange={(e) => setPeriod(e.target.value as Period)}
          >
            {Object.entries(periodLabels).map(([key, label]) => (
              <option key={key} value={key}>
                {label}
              </option>
            ))}
          </select>

          <button
            className="tenant-dashboard__refresh-btn"
            onClick={fetchStats}
            disabled={loading}
            title="Aktualisieren"
          >
            <svg
              className={`tenant-dashboard__refresh-icon ${loading ? 'tenant-dashboard__refresh-icon--spinning' : ''}`}
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
            >
              <path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16" />
            </svg>
          </button>
        </div>
      </div>

      {loading && !stats && (
        <div className="tenant-dashboard__loading">
          <div className="tenant-dashboard__spinner" />
          <span>Lade Statistiken...</span>
        </div>
      )}

      {error && (
        <div className="tenant-dashboard__error">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <circle cx="12" cy="12" r="10" />
            <line x1="12" y1="8" x2="12" y2="12" />
            <line x1="12" y1="16" x2="12.01" y2="16" />
          </svg>
          <span>{error}</span>
        </div>
      )}

      {stats && (
        <>
          {/* Statistik-Karten */}
          <div className="tenant-dashboard__stats-grid">
            <div className="tenant-dashboard__stat-card">
              <div className="tenant-dashboard__stat-icon tenant-dashboard__stat-icon--total">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
                  <polyline points="22,6 12,13 2,6" />
                </svg>
              </div>
              <div className="tenant-dashboard__stat-content">
                <span className="tenant-dashboard__stat-value">{stats.stats.total}</span>
                <span className="tenant-dashboard__stat-label">Gesamt</span>
              </div>
            </div>

            <div className="tenant-dashboard__stat-card tenant-dashboard__stat-card--success">
              <div className="tenant-dashboard__stat-icon tenant-dashboard__stat-icon--sent">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <polyline points="20 6 9 17 4 12" />
                </svg>
              </div>
              <div className="tenant-dashboard__stat-content">
                <span className="tenant-dashboard__stat-value">{stats.stats.sent}</span>
                <span className="tenant-dashboard__stat-label">Gesendet</span>
              </div>
            </div>

            <div className="tenant-dashboard__stat-card tenant-dashboard__stat-card--error">
              <div className="tenant-dashboard__stat-icon tenant-dashboard__stat-icon--failed">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <circle cx="12" cy="12" r="10" />
                  <line x1="15" y1="9" x2="9" y2="15" />
                  <line x1="9" y1="9" x2="15" y2="15" />
                </svg>
              </div>
              <div className="tenant-dashboard__stat-content">
                <span className="tenant-dashboard__stat-value">{stats.stats.failed}</span>
                <span className="tenant-dashboard__stat-label">Fehlgeschlagen</span>
              </div>
            </div>

            <div className="tenant-dashboard__stat-card tenant-dashboard__stat-card--rate">
              <div className="tenant-dashboard__stat-icon tenant-dashboard__stat-icon--rate">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <line x1="12" y1="20" x2="12" y2="10" />
                  <line x1="18" y1="20" x2="18" y2="4" />
                  <line x1="6" y1="20" x2="6" y2="16" />
                </svg>
              </div>
              <div className="tenant-dashboard__stat-content">
                <span className="tenant-dashboard__stat-value">{stats.stats.successRate}%</span>
                <span className="tenant-dashboard__stat-label">Erfolgsrate</span>
              </div>
            </div>
          </div>

          {/* Aufschlüsselung nach Quelle */}
          <div className="tenant-dashboard__section">
            <h3 className="tenant-dashboard__section-title">Nach Quelle</h3>
            <div className="tenant-dashboard__source-grid">
              <div className="tenant-dashboard__source-item">
                <span className="tenant-dashboard__source-label">Formular</span>
                <span className="tenant-dashboard__source-value">{stats.bySource.form}</span>
              </div>
              <div className="tenant-dashboard__source-item">
                <span className="tenant-dashboard__source-label">Manuell (API)</span>
                <span className="tenant-dashboard__source-value">{stats.bySource.manual}</span>
              </div>
              <div className="tenant-dashboard__source-item">
                <span className="tenant-dashboard__source-label">System</span>
                <span className="tenant-dashboard__source-value">{stats.bySource.system}</span>
              </div>
              <div className="tenant-dashboard__source-item">
                <span className="tenant-dashboard__source-label">Newsletter</span>
                <span className="tenant-dashboard__source-value">{stats.bySource.newsletter}</span>
              </div>
            </div>
          </div>

          {/* Letzte Fehler */}
          {stats.recentFailures.length > 0 && (
            <div className="tenant-dashboard__section tenant-dashboard__section--failures">
              <h3 className="tenant-dashboard__section-title">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
                  <line x1="12" y1="9" x2="12" y2="13" />
                  <line x1="12" y1="17" x2="12.01" y2="17" />
                </svg>
                Letzte fehlgeschlagene E-Mails
              </h3>
              <div className="tenant-dashboard__failures-list">
                {stats.recentFailures.map((failure) => (
                  <div key={failure.id} className="tenant-dashboard__failure-item">
                    <div className="tenant-dashboard__failure-header">
                      <span className="tenant-dashboard__failure-to">{failure.to}</span>
                      <span className="tenant-dashboard__failure-date">
                        {formatDate(failure.createdAt)}
                      </span>
                    </div>
                    <div className="tenant-dashboard__failure-subject">{failure.subject}</div>
                    {failure.error && (
                      <div className="tenant-dashboard__failure-error">{failure.error}</div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Quick Actions */}
          <div className="tenant-dashboard__actions">
            <a
              href={`/admin/collections/email-logs?where[tenant][equals]=${selectedTenantID}`}
              className="tenant-dashboard__action-btn"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                <polyline points="14 2 14 8 20 8" />
                <line x1="16" y1="13" x2="8" y2="13" />
                <line x1="16" y1="17" x2="8" y2="17" />
              </svg>
              Alle E-Mail-Logs anzeigen
            </a>
            <a
              href={`/admin/collections/tenants/${selectedTenantID}`}
              className="tenant-dashboard__action-btn"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="12" cy="12" r="3" />
                <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" />
              </svg>
              E-Mail-Einstellungen
            </a>
          </div>
        </>
      )}
    </div>
  )
}

export default TenantDashboard
