import { useEffect, useState } from 'react'
import {
  FaFloppyDisk,
  FaPlus,
  FaSpinner,
  FaTrash,
  FaXmark,
} from 'react-icons/fa6'
import { FaEdit } from 'react-icons/fa'
import CopyableCredential, {
  getCustomerPortalPassword,
} from '../components/CopyableCredential'
import { useAuth } from '../context/AuthContext'
import { useAdminConfig } from '../hooks/useAdminConfig'
import { useCustomers } from '../hooks/useCustomers'
import { useEmployees } from '../hooks/useEmployees'
import './AdminPage.css'

const EMPTY_CONFIG = {
  ticketTypes: [],
  systems: [],
  responseLevels: [],
  serviceTypes: [],
  priorities: [],
}

const EMPTY_CUSTOMER = {
  code: '',
  name: '',
  location: '',
  email: '',
  phone: '',
  password: '',
}

const EMPTY_EMPLOYEE = {
  displayName: '',
  email: '',
  password: '',
  shortcode: '',
  isAdmin: false,
}

const CONFIG_GROUPS = [
  { field: 'ticketTypes', title: 'Ticketarten', placeholder: 'Neue Ticketart' },
  { field: 'systems', title: 'Betroffene Systeme', placeholder: 'Neues System' },
  { field: 'responseLevels', title: 'Reaktionsstufen', placeholder: 'Neue Stufe' },
  { field: 'serviceTypes', title: 'Leistungsarten', placeholder: 'Neue Leistungsart' },
]

function Notice({ notice }) {
  if (!notice?.text) return null
  return <div className={`admin-notice ${notice.type}`}>{notice.text}</div>
}

function ConfigList({ title, field, values, placeholder, onAdd, onRemove, onChange }) {
  return (
    <section className="admin-config-card">
      <div className="admin-section-head">
        <div>
          <h3>{title}</h3>
          <span>{values.length} Einträge</span>
        </div>
        <button type="button" className="admin-icon-button" onClick={() => onAdd(field)}>
          <FaPlus />
          <span>Hinzufügen</span>
        </button>
      </div>
      <div className="admin-config-list">
        {values.length === 0 && <p className="admin-empty-line">Noch keine Einträge.</p>}
        {values.map((value, index) => (
          <div className="admin-config-row" key={`${field}-${index}`}>
            <input
              className="form-control"
              value={value}
              placeholder={placeholder}
              onChange={(event) => onChange(field, index, event.target.value)}
            />
            <button
              type="button"
              className="admin-icon-button danger"
              onClick={() => onRemove(field, index)}
              aria-label={`${value || 'Eintrag'} entfernen`}
            >
              <FaTrash />
            </button>
          </div>
        ))}
      </div>
    </section>
  )
}

export default function AdminPage() {
  const { user, isAdmin } = useAuth()
  const { config, loading, error, updateConfig } = useAdminConfig()
  const {
    customers,
    loading: customersLoading,
    createCustomer,
    updateCustomer,
    deleteCustomer,
  } = useCustomers()
  const {
    employees,
    loading: employeesLoading,
    error: employeesError,
    createEmployee,
    updateEmployee,
    deleteEmployee,
  } = useEmployees()

  const [activeSection, setActiveSection] = useState('config')
  const [localConfig, setLocalConfig] = useState(EMPTY_CONFIG)
  const [savingConfig, setSavingConfig] = useState(false)
  const [customerForm, setCustomerForm] = useState(EMPTY_CUSTOMER)
  const [editingCustomer, setEditingCustomer] = useState(null)
  const [customerBusy, setCustomerBusy] = useState(false)
  const [employeeForm, setEmployeeForm] = useState(EMPTY_EMPLOYEE)
  const [editingEmployee, setEditingEmployee] = useState(null)
  const [employeeBusy, setEmployeeBusy] = useState(false)
  const [createdCredential, setCreatedCredential] = useState(null)
  const [notice, setNotice] = useState(null)

  useEffect(() => {
    if (config && Object.keys(config).length > 0) {
      setLocalConfig({ ...EMPTY_CONFIG, ...config })
    }
  }, [config])

  const showNotice = (type, text) => {
    setNotice({ type, text })
    window.setTimeout(() => setNotice(null), 4500)
  }

  if (!isAdmin) {
    return (
      <main className="page admin-page">
        <section className="admin-access-denied">
          <span>403</span>
          <h1>Zugriff verweigert</h1>
          <p>Für diesen Bereich ist ein Admin-Account erforderlich.</p>
        </section>
      </main>
    )
  }

  const addConfigItem = (field) => {
    setLocalConfig((current) => ({
      ...current,
      [field]: [
        ...(current[field] || []),
        field === 'priorities'
          ? { value: current.priorities?.length || 0, label: 'Neue Priorität' }
          : '',
      ],
    }))
  }

  const removeConfigItem = (field, index) => {
    setLocalConfig((current) => ({
      ...current,
      [field]: (current[field] || []).filter((_, itemIndex) => itemIndex !== index),
    }))
  }

  const updateConfigItem = (field, index, value) => {
    setLocalConfig((current) => {
      const next = [...(current[field] || [])]
      next[index] = value
      return { ...current, [field]: next }
    })
  }

  const saveConfiguration = async () => {
    setSavingConfig(true)
    const result = await updateConfig(localConfig)
    setSavingConfig(false)
    showNotice(
      result.success ? 'success' : 'error',
      result.success
        ? 'Konfiguration gespeichert.'
        : `Speichern fehlgeschlagen: ${result.error || 'Unbekannter Fehler'}`
    )
  }

  const resetCustomerForm = () => {
    setCustomerForm(EMPTY_CUSTOMER)
    setEditingCustomer(null)
  }

  const submitCustomer = async (event) => {
    event.preventDefault()
    if (!customerForm.name.trim() || !customerForm.email.trim()) {
      showNotice('error', 'Name und E-Mail sind erforderlich.')
      return
    }
    if (!editingCustomer && customerForm.password.length < 8) {
      showNotice('error', 'Das Portal-Passwort muss mindestens 8 Zeichen haben.')
      return
    }
    if (editingCustomer && customerForm.password && customerForm.password.length < 8) {
      showNotice('error', 'Ein neues Passwort muss mindestens 8 Zeichen haben.')
      return
    }

    setCustomerBusy(true)
    const result = editingCustomer
      ? await updateCustomer(editingCustomer, customerForm)
      : await createCustomer(customerForm)
    setCustomerBusy(false)
    if (!result.success) {
      showNotice('error', result.error || 'Kunde konnte nicht gespeichert werden.')
      return
    }
    showNotice('success', editingCustomer ? 'Kunde aktualisiert.' : 'Kunde angelegt.')
    resetCustomerForm()
  }

  const editCustomer = (customer) => {
    setEditingCustomer(customer.$id)
    setCustomerForm({
      code: customer.code || '',
      name: customer.name || '',
      location: customer.location || '',
      email: customer.email || '',
      phone: customer.phone || '',
      password: '',
    })
  }

  const removeCustomer = async (customer) => {
    if (!window.confirm(`${customer.name || customer.email} wirklich löschen?`)) return
    const result = await deleteCustomer(customer.$id)
    showNotice(
      result.success ? 'success' : 'error',
      result.success ? 'Kunde und Portalzugang gelöscht.' : result.error
    )
  }

  const resetEmployeeForm = () => {
    setEmployeeForm(EMPTY_EMPLOYEE)
    setEditingEmployee(null)
  }

  const submitEmployee = async (event) => {
    event.preventDefault()
    if (!employeeForm.displayName.trim() || !employeeForm.email.trim()) {
      showNotice('error', 'Name und E-Mail sind erforderlich.')
      return
    }
    if (!editingEmployee && employeeForm.password.length < 8) {
      showNotice('error', 'Das Passwort muss mindestens 8 Zeichen haben.')
      return
    }
    if (editingEmployee && employeeForm.password && employeeForm.password.length < 8) {
      showNotice('error', 'Ein neues Passwort muss mindestens 8 Zeichen haben.')
      return
    }

    setEmployeeBusy(true)
    const result = editingEmployee
      ? await updateEmployee(editingEmployee, employeeForm)
      : await createEmployee(employeeForm)
    setEmployeeBusy(false)
    if (!result.success) {
      showNotice('error', result.error || 'Mitarbeiter konnte nicht gespeichert werden.')
      return
    }
    if (!editingEmployee) {
      setCreatedCredential({
        email: employeeForm.email.trim(),
        password: employeeForm.password,
      })
    }
    showNotice('success', editingEmployee ? 'Mitarbeiter aktualisiert.' : 'Mitarbeiter angelegt. Der Login ist sofort aktiv.')
    resetEmployeeForm()
  }

  const editEmployee = (employee) => {
    setEditingEmployee(employee.$id)
    setEmployeeForm({
      displayName: employee.displayName || '',
      email: employee.email || '',
      password: '',
      shortcode: employee.shortcode || '',
      isAdmin: Boolean(employee.isAdmin),
    })
  }

  const removeEmployee = async (employee) => {
    if (!window.confirm(`${employee.displayName || employee.email} und dessen Login wirklich löschen?`)) return
    const result = await deleteEmployee(employee.$id)
    showNotice(
      result.success ? 'success' : 'error',
      result.success ? 'Mitarbeiter und Login gelöscht.' : result.error
    )
  }

  return (
    <main className="page admin-page">
      <header className="admin-header">
        <div>
          <span className="admin-eyebrow">Systemverwaltung</span>
          <h1>Admin</h1>
          <p>Konfiguration, Kundenkonten und Mitarbeiterzugänge zentral verwalten.</p>
        </div>
        <div className="admin-current-user">
          <span>Angemeldet als</span>
          <strong>{user?.name || user?.email}</strong>
        </div>
      </header>

      <Notice notice={notice} />
      {error && <Notice notice={{ type: 'error', text: error }} />}

      <nav className="admin-tabs" aria-label="Admin-Bereiche">
        {[
          ['config', 'Konfiguration'],
          ['customers', `Kunden (${customers.length})`],
          ['employees', `Mitarbeiter (${employees.length})`],
        ].map(([id, label]) => (
          <button
            type="button"
            key={id}
            className={activeSection === id ? 'active' : ''}
            onClick={() => setActiveSection(id)}
          >
            {label}
          </button>
        ))}
      </nav>

      {activeSection === 'config' && (
        <section>
          {loading && !config ? (
            <div className="admin-loading"><FaSpinner className="spinner" /> Konfiguration wird geladen …</div>
          ) : (
            <>
              <div className="admin-config-grid">
                {CONFIG_GROUPS.map((group) => (
                  <ConfigList
                    key={group.field}
                    {...group}
                    values={localConfig[group.field] || []}
                    onAdd={addConfigItem}
                    onRemove={removeConfigItem}
                    onChange={updateConfigItem}
                  />
                ))}
                <section className="admin-config-card priorities">
                  <div className="admin-section-head">
                    <div><h3>Prioritäten</h3><span>{localConfig.priorities?.length || 0} Einträge</span></div>
                    <button type="button" className="admin-icon-button" onClick={() => addConfigItem('priorities')}>
                      <FaPlus /><span>Hinzufügen</span>
                    </button>
                  </div>
                  <div className="admin-config-list">
                    {(localConfig.priorities || []).map((priority, index) => (
                      <div className="admin-priority-row" key={`priority-${index}`}>
                        <input
                          type="number"
                          className="form-control"
                          value={priority.value}
                          aria-label="Prioritätswert"
                          onChange={(event) => updateConfigItem('priorities', index, {
                            ...priority,
                            value: Number(event.target.value),
                          })}
                        />
                        <input
                          className="form-control"
                          value={priority.label}
                          aria-label="Prioritätsname"
                          onChange={(event) => updateConfigItem('priorities', index, {
                            ...priority,
                            label: event.target.value,
                          })}
                        />
                        <button type="button" className="admin-icon-button danger" onClick={() => removeConfigItem('priorities', index)}>
                          <FaTrash />
                        </button>
                      </div>
                    ))}
                  </div>
                </section>
              </div>
              <div className="admin-savebar">
                <span>Änderungen gelten für neue und bestehende Ticketformulare.</span>
                <button type="button" className="admin-primary-button" disabled={savingConfig} onClick={saveConfiguration}>
                  {savingConfig ? <FaSpinner className="spin" /> : <FaFloppyDisk />}
                  Konfiguration speichern
                </button>
              </div>
            </>
          )}
        </section>
      )}

      {activeSection === 'customers' && (
        <section className="admin-split-layout">
          <form className="admin-form-card" onSubmit={submitCustomer}>
            <div className="admin-section-head">
              <div>
                <h2>{editingCustomer ? 'Kunde bearbeiten' : 'Kunde anlegen'}</h2>
                <span>Portalzugang für project.webklar.com</span>
              </div>
              {editingCustomer && (
                <button type="button" className="admin-icon-button" onClick={resetCustomerForm} aria-label="Bearbeitung schließen">
                  <FaXmark />
                </button>
              )}
            </div>
            <label className="admin-field">
              <span>Kundencode <em>manuell</em></span>
              <input className="form-control" value={customerForm.code} onChange={(event) => setCustomerForm({ ...customerForm, code: event.target.value })} placeholder="z. B. C001" />
            </label>
            <label className="admin-field">
              <span>Name</span>
              <input className="form-control" required value={customerForm.name} onChange={(event) => setCustomerForm({ ...customerForm, name: event.target.value })} />
            </label>
            <label className="admin-field">
              <span>Standort</span>
              <input className="form-control" value={customerForm.location} onChange={(event) => setCustomerForm({ ...customerForm, location: event.target.value })} />
            </label>
            <label className="admin-field">
              <span>E-Mail</span>
              <input type="email" className="form-control" required value={customerForm.email} onChange={(event) => setCustomerForm({ ...customerForm, email: event.target.value })} />
            </label>
            <label className="admin-field">
              <span>Telefon</span>
              <input className="form-control" value={customerForm.phone} onChange={(event) => setCustomerForm({ ...customerForm, phone: event.target.value })} />
            </label>
            <label className="admin-field">
              <span>{editingCustomer ? 'Neues Passwort (optional)' : 'Portal-Passwort'}</span>
              <input type="password" className="form-control" autoComplete="new-password" required={!editingCustomer} value={customerForm.password} onChange={(event) => setCustomerForm({ ...customerForm, password: event.target.value })} placeholder="Mindestens 8 Zeichen" />
            </label>
            <button className="admin-primary-button" disabled={customerBusy}>
              {customerBusy ? <FaSpinner className="spin" /> : editingCustomer ? <FaFloppyDisk /> : <FaPlus />}
              {editingCustomer ? 'Änderungen speichern' : 'Kunde anlegen'}
            </button>
          </form>

          <section className="admin-list-card">
            <div className="admin-section-head">
              <div><h2>Kundenkonten</h2><span>E-Mail sichtbar, Passwort geschützt</span></div>
            </div>
            {customersLoading ? (
              <div className="admin-loading"><FaSpinner className="spinner" /> Kunden werden geladen …</div>
            ) : customers.length === 0 ? (
              <div className="admin-empty-state"><h3>Noch keine Kunden</h3><p>Lege links den ersten Portalzugang an.</p></div>
            ) : (
              <div className="admin-table-wrap">
                <table className="admin-table">
                  <thead><tr><th>Code / Kunde</th><th>Zugang</th><th>Standort / Telefon</th><th>Status</th><th><span className="sr-only">Aktionen</span></th></tr></thead>
                  <tbody>
                    {customers.map((customer) => (
                      <tr key={customer.$id}>
                        <td><strong>{customer.code || 'Ohne Code'}</strong><span>{customer.name || '–'}</span></td>
                        <td>
                          <CopyableCredential value={customer.email} label="E-Mail" />
                          <CopyableCredential value={getCustomerPortalPassword(customer)} secret label="Passwort" />
                        </td>
                        <td><strong>{customer.location || '–'}</strong><span>{customer.phone || '–'}</span></td>
                        <td><span className={`admin-status ${customer.portalAccessEnabled ? 'active' : ''}`}>{customer.portalAccessEnabled ? 'Aktiv' : 'Inaktiv'}</span></td>
                        <td className="admin-row-actions">
                          <button type="button" className="admin-icon-button" onClick={() => editCustomer(customer)} aria-label={`${customer.name} bearbeiten`}><FaEdit /></button>
                          <button type="button" className="admin-icon-button danger" onClick={() => removeCustomer(customer)} aria-label={`${customer.name} löschen`}><FaTrash /></button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </section>
        </section>
      )}

      {activeSection === 'employees' && (
        <section>
          {createdCredential && (
            <div className="admin-credential-result">
              <div><strong>Login wurde angelegt</strong><span>Diese Zugangsdaten jetzt sicher weitergeben.</span></div>
              <CopyableCredential value={createdCredential.email} label="E-Mail" />
              <CopyableCredential value={createdCredential.password} secret label="Passwort" />
              <button type="button" className="admin-icon-button" onClick={() => setCreatedCredential(null)} aria-label="Hinweis schließen"><FaXmark /></button>
            </div>
          )}
          <div className="admin-split-layout">
            <form className="admin-form-card" onSubmit={submitEmployee}>
              <div className="admin-section-head">
                <div>
                  <h2>{editingEmployee ? 'Mitarbeiter bearbeiten' : 'Mitarbeiter anlegen'}</h2>
                  <span>Die User-ID wird automatisch vergeben.</span>
                </div>
                {editingEmployee && <button type="button" className="admin-icon-button" onClick={resetEmployeeForm} aria-label="Bearbeitung schließen"><FaXmark /></button>}
              </div>
              <label className="admin-field"><span>Name</span><input className="form-control" required value={employeeForm.displayName} onChange={(event) => setEmployeeForm({ ...employeeForm, displayName: event.target.value })} /></label>
              <label className="admin-field"><span>E-Mail</span><input type="email" className="form-control" required value={employeeForm.email} onChange={(event) => setEmployeeForm({ ...employeeForm, email: event.target.value })} /></label>
              <label className="admin-field"><span>{editingEmployee ? 'Neues Passwort (optional)' : 'Passwort'}</span><input type="password" className="form-control" autoComplete="new-password" required={!editingEmployee} value={employeeForm.password} onChange={(event) => setEmployeeForm({ ...employeeForm, password: event.target.value })} placeholder="Mindestens 8 Zeichen" /></label>
              <label className="admin-field"><span>Kürzel</span><input className="form-control" maxLength={10} value={employeeForm.shortcode} onChange={(event) => setEmployeeForm({ ...employeeForm, shortcode: event.target.value.toUpperCase() })} placeholder="z. B. KNSO" /></label>
              <label className={`admin-checkbox ${editingEmployee && employees.find((item) => item.$id === editingEmployee)?.userId === user?.$id ? 'disabled' : ''}`}>
                <input
                  type="checkbox"
                  checked={employeeForm.isAdmin}
                  disabled={editingEmployee && employees.find((item) => item.$id === editingEmployee)?.userId === user?.$id}
                  onChange={(event) => setEmployeeForm({ ...employeeForm, isAdmin: event.target.checked })}
                />
                <span><strong>Admin-Account</strong><small>Darf Systemkonfiguration und Benutzer verwalten.</small></span>
              </label>
              <button className="admin-primary-button" disabled={employeeBusy}>
                {employeeBusy ? <FaSpinner className="spin" /> : editingEmployee ? <FaFloppyDisk /> : <FaPlus />}
                {editingEmployee ? 'Änderungen speichern' : 'Mitarbeiter anlegen'}
              </button>
            </form>

            <section className="admin-list-card">
              <div className="admin-section-head"><div><h2>Mitarbeiterkonten</h2><span>Aktive Logins für das Ticketsystem</span></div></div>
              {employeesError && <Notice notice={{ type: 'error', text: employeesError }} />}
              {employeesLoading ? (
                <div className="admin-loading"><FaSpinner className="spinner" /> Mitarbeiter werden geladen …</div>
              ) : employees.length === 0 ? (
                <div className="admin-empty-state"><h3>Noch keine Mitarbeiter</h3><p>Lege links den ersten Login an.</p></div>
              ) : (
                <div className="admin-table-wrap">
                  <table className="admin-table">
                    <thead><tr><th>Mitarbeiter</th><th>E-Mail</th><th>Kürzel</th><th>Rolle</th><th>User-ID</th><th><span className="sr-only">Aktionen</span></th></tr></thead>
                    <tbody>
                      {employees.map((employee) => (
                        <tr key={employee.$id}>
                          <td><strong>{employee.displayName || '–'}</strong></td>
                          <td><CopyableCredential value={employee.email} label="E-Mail" /></td>
                          <td><span className="admin-shortcode">{employee.shortcode || '–'}</span></td>
                          <td><span className={`admin-role ${employee.isAdmin ? 'admin' : ''}`}>{employee.isAdmin ? 'Admin' : 'Mitarbeiter'}</span></td>
                          <td><CopyableCredential value={employee.userId} label="User-ID" /></td>
                          <td className="admin-row-actions">
                            <button type="button" className="admin-icon-button" onClick={() => editEmployee(employee)} aria-label={`${employee.displayName} bearbeiten`}><FaEdit /></button>
                            {employee.userId !== user?.$id && <button type="button" className="admin-icon-button danger" onClick={() => removeEmployee(employee)} aria-label={`${employee.displayName} löschen`}><FaTrash /></button>}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </section>
          </div>
        </section>
      )}
    </main>
  )
}
