'use client'

import React, { useState, useCallback, useEffect } from 'react'
import { useDocumentInfo, useAuth } from '@payloadcms/ui'
import './TestEmailButton.scss'

type TestStatus = 'idle' | 'loading' | 'success' | 'error'

interface TestResult {
  success: boolean
  message?: string
  messageId?: string
}

// CSRF Constants (muss mit src/lib/security/csrf.ts übereinstimmen)
const CSRF_COOKIE_NAME = 'csrf-token'
const CSRF_HEADER_NAME = 'X-CSRF-Token'

/**
 * Liest einen Cookie-Wert
 */
function getCookie(name: string): string | null {
  if (typeof document === 'undefined') return null
  const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`))
  return match ? decodeURIComponent(match[2]) : null
}

/**
 * Holt ein CSRF-Token vom Server und setzt es als Cookie
 */
async function fetchCsrfToken(): Promise<string | null> {
  try {
    const response = await fetch('/api/csrf-token', {
      method: 'GET',
      credentials: 'include',
    })

    if (response.ok) {
      const data = await response.json()
      return data.token || null
    }
  } catch (error) {
    console.error('Failed to fetch CSRF token:', error)
  }
  return null
}

/**
 * Button zum Senden einer Test-E-Mail für SMTP-Konfigurationstest
 * Implementiert CSRF-Schutz via Double Submit Cookie
 */
export const TestEmailButton: React.FC = () => {
  const { id: documentId } = useDocumentInfo()
  const { user } = useAuth()
  const [status, setStatus] = useState<TestStatus>('idle')
  const [result, setResult] = useState<TestResult | null>(null)
  const [recipientEmail, setRecipientEmail] = useState('')
  const [csrfToken, setCsrfToken] = useState<string | null>(null)

  // Standardmäßig die E-Mail des aktuellen Users verwenden
  const defaultEmail = (user as { email?: string })?.email || ''

  // CSRF-Token beim Mount laden
  useEffect(() => {
    const initCsrf = async () => {
      // Erst versuchen aus Cookie zu lesen
      let token = getCookie(CSRF_COOKIE_NAME)

      // Falls kein Cookie vorhanden, Token vom Server holen
      if (!token) {
        token = await fetchCsrfToken()
      }

      setCsrfToken(token)
    }

    initCsrf()
  }, [])

  const handleSendTest = useCallback(async () => {
    const emailToUse = recipientEmail || defaultEmail

    if (!emailToUse) {
      setResult({ success: false, message: 'Bitte eine Empfänger-E-Mail angeben' })
      setStatus('error')
      return
    }

    if (!documentId) {
      setResult({ success: false, message: 'Tenant muss erst gespeichert werden' })
      setStatus('error')
      return
    }

    setStatus('loading')
    setResult(null)

    try {
      // CSRF-Token aus State oder frisch aus Cookie lesen
      let token = csrfToken || getCookie(CSRF_COOKIE_NAME)

      // Falls immer noch kein Token, neues holen
      if (!token) {
        token = await fetchCsrfToken()
        if (token) {
          setCsrfToken(token)
        }
      }

      if (!token) {
        setResult({ success: false, message: 'CSRF-Token konnte nicht geladen werden. Bitte Seite neu laden.' })
        setStatus('error')
        return
      }

      const response = await fetch('/api/test-email', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          [CSRF_HEADER_NAME]: token,
        },
        credentials: 'include',
        body: JSON.stringify({
          tenantId: documentId,
          recipientEmail: emailToUse,
        }),
      })

      const contentType = response.headers.get('content-type') || ''
      if (!contentType.includes('application/json')) {
        setResult({
          success: false,
          message: `Server-Fehler (HTTP ${response.status}). Bitte Seite neu laden und erneut versuchen.`,
        })
        setStatus('error')
        return
      }

      const data = await response.json()

      if (response.ok && data.success) {
        setResult({
          success: true,
          message: 'Test-E-Mail erfolgreich gesendet!',
          messageId: data.messageId,
        })
        setStatus('success')
      } else {
        // Bei CSRF-Fehler Token neu laden
        if (response.status === 403 && data.error?.includes('CSRF')) {
          const newToken = await fetchCsrfToken()
          if (newToken) {
            setCsrfToken(newToken)
          }
          setResult({
            success: false,
            message: 'Sicherheitstoken abgelaufen. Bitte erneut versuchen.',
          })
        } else {
          setResult({
            success: false,
            message: data.error || data.message || 'Fehler beim Senden der Test-E-Mail',
          })
        }
        setStatus('error')
      }
    } catch (error) {
      setResult({
        success: false,
        message: error instanceof Error ? error.message : 'Netzwerkfehler',
      })
      setStatus('error')
    }
  }, [documentId, recipientEmail, defaultEmail, csrfToken])

  return (
    <div className="test-email-button">
      <div className="test-email-button__header">
        <h4 className="test-email-button__title">SMTP-Konfiguration testen</h4>
        <p className="test-email-button__description">
          Senden Sie eine Test-E-Mail um zu prüfen, ob die SMTP-Einstellungen korrekt sind.
        </p>
      </div>

      <div className="test-email-button__form">
        <div className="test-email-button__input-group">
          <label htmlFor="test-email-recipient" className="test-email-button__label">
            Empfänger-E-Mail
          </label>
          <input
            id="test-email-recipient"
            type="email"
            className="test-email-button__input"
            placeholder={defaultEmail || 'empfaenger@example.com'}
            value={recipientEmail}
            onChange={(e) => setRecipientEmail(e.target.value)}
            disabled={status === 'loading'}
          />
        </div>

        <button
          type="button"
          className={`test-email-button__button test-email-button__button--${status}`}
          onClick={handleSendTest}
          disabled={status === 'loading' || !documentId}
        >
          {status === 'loading' ? (
            <>
              <span className="test-email-button__spinner" />
              Sende...
            </>
          ) : (
            <>
              <svg
                className="test-email-button__icon"
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <path d="M22 2L11 13" />
                <path d="M22 2L15 22L11 13L2 9L22 2Z" />
              </svg>
              Test-E-Mail senden
            </>
          )}
        </button>
      </div>

      {result && (
        <div
          className={`test-email-button__result test-email-button__result--${result.success ? 'success' : 'error'}`}
        >
          <span className="test-email-button__result-icon">
            {result.success ? (
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <polyline points="20 6 9 17 4 12" />
              </svg>
            ) : (
              <svg width="16" height="16" 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>
            )}
          </span>
          <span className="test-email-button__result-message">
            {result.message}
            {result.messageId && (
              <small className="test-email-button__result-id">ID: {result.messageId}</small>
            )}
          </span>
        </div>
      )}

      {!documentId && (
        <p className="test-email-button__warning">
          Speichern Sie den Tenant zuerst, um eine Test-E-Mail senden zu können.
        </p>
      )}
    </div>
  )
}

export default TestEmailButton
