'use client'

import { useState } from 'react'
import type { EmailAccount } from '../types'
import { API_BASE } from '../constants'
import AddAccountModal from './AddAccountModal'

export default function AccountsTab({
  accounts,
  loading,
  onRefresh
}: {
  accounts: EmailAccount[]
  loading: boolean
  onRefresh: () => void
}) {
  const [showAddModal, setShowAddModal] = useState(false)

  const testConnection = async (accountId: string) => {
    try {
      const res = await fetch(`${API_BASE}/api/v1/mail/accounts/${accountId}/test`, {
        method: 'POST',
      })
      if (res.ok) {
        alert('Verbindung erfolgreich!')
      } else {
        alert('Verbindungsfehler')
      }
    } catch (err) {
      alert('Verbindungsfehler')
    }
  }

  const statusColors = {
    active: 'bg-green-100 text-green-800',
    inactive: 'bg-gray-100 text-gray-800',
    error: 'bg-red-100 text-red-800',
    syncing: 'bg-yellow-100 text-yellow-800',
  }

  const statusLabels = {
    active: 'Aktiv',
    inactive: 'Inaktiv',
    error: 'Fehler',
    syncing: 'Synchronisiert...',
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-slate-900">E-Mail-Konten</h2>
          <p className="text-sm text-slate-500">Verwalten Sie die verbundenen E-Mail-Konten</p>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="px-4 py-2 text-sm font-medium text-white bg-primary-600 rounded-lg hover:bg-primary-700 flex items-center gap-2"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
          Konto hinzufügen
        </button>
      </div>

      {/* Loading State */}
      {loading && (
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
        </div>
      )}

      {/* Accounts Grid */}
      {!loading && (
        <div className="grid gap-4">
          {accounts.length === 0 ? (
            <div className="bg-slate-50 rounded-lg p-8 text-center">
              <svg className="w-12 h-12 text-slate-400 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
              </svg>
              <h3 className="text-lg font-medium text-slate-900 mb-2">Keine E-Mail-Konten</h3>
              <p className="text-slate-500 mb-4">Fügen Sie Ihr erstes E-Mail-Konto hinzu.</p>
            </div>
          ) : (
            accounts.map((account) => (
              <div
                key={account.id}
                className="bg-white rounded-lg border border-slate-200 p-6 hover:shadow-md transition-shadow"
              >
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 bg-primary-100 rounded-lg flex items-center justify-center">
                      <svg className="w-6 h-6 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                      </svg>
                    </div>
                    <div>
                      <h3 className="text-lg font-semibold text-slate-900">
                        {account.displayName || account.email}
                      </h3>
                      <p className="text-sm text-slate-500">{account.email}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className={`px-3 py-1 rounded-full text-xs font-medium ${statusColors[account.status]}`}>
                      {statusLabels[account.status]}
                    </span>
                    <button
                      onClick={() => testConnection(account.id)}
                      className="p-2 text-slate-400 hover:text-slate-600"
                      title="Verbindung testen"
                    >
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                      </svg>
                    </button>
                  </div>
                </div>

                <div className="mt-4 grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div>
                    <p className="text-xs text-slate-500 uppercase tracking-wider">E-Mails</p>
                    <p className="text-lg font-semibold text-slate-900">{account.emailCount}</p>
                  </div>
                  <div>
                    <p className="text-xs text-slate-500 uppercase tracking-wider">Ungelesen</p>
                    <p className="text-lg font-semibold text-slate-900">{account.unreadCount}</p>
                  </div>
                  <div>
                    <p className="text-xs text-slate-500 uppercase tracking-wider">IMAP</p>
                    <p className="text-sm font-mono text-slate-700">{account.imapHost}:{account.imapPort}</p>
                  </div>
                  <div>
                    <p className="text-xs text-slate-500 uppercase tracking-wider">Letzte Sync</p>
                    <p className="text-sm text-slate-700">
                      {account.lastSync
                        ? new Date(account.lastSync).toLocaleString('de-DE')
                        : 'Nie'}
                    </p>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>
      )}

      {/* Add Account Modal */}
      {showAddModal && (
        <AddAccountModal onClose={() => setShowAddModal(false)} onSuccess={() => { setShowAddModal(false); onRefresh(); }} />
      )}
    </div>
  )
}
